/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/git/dir.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2007 Canonical Ltd
2
 
# Copyright (C) 2010 Jelmer Vernooij
 
2
# Copyright (C) 2010-2018 Jelmer Vernooij
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
13
13
#
14
14
# You should have received a copy of the GNU General Public License
15
15
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
 
18
18
"""An adapter between a Git control dir and a Bazaar ControlDir."""
19
19
 
20
 
from bzrlib import (
21
 
    errors as bzr_errors,
22
 
    lockable_files,
 
20
from __future__ import absolute_import
 
21
 
 
22
import contextlib
 
23
 
 
24
from .. import (
 
25
    branch as _mod_branch,
 
26
    errors as brz_errors,
 
27
    trace,
 
28
    osutils,
23
29
    urlutils,
24
 
    version_info as bzrlib_version,
25
 
    )
26
 
 
27
 
LockWarner = getattr(lockable_files, "_LockWarner", None)
28
 
 
29
 
from bzrlib.plugins.git import (
30
 
    BareLocalGitControlDirFormat,
31
 
    LocalGitControlDirFormat,
32
 
    )
33
 
try:
34
 
    from bzrlib.controldir import (
35
 
        ControlDir,
36
 
        format_registry,
37
 
        )
38
 
except ImportError:
39
 
    # bzr < 2.3
40
 
    from bzrlib.bzrdir import (
41
 
        BzrDir,
42
 
        format_registry,
43
 
        )
44
 
    ControlDir = BzrDir
45
 
 
46
 
 
47
 
class GitLock(object):
48
 
    """A lock that thunks through to Git."""
49
 
 
50
 
    def lock_write(self, token=None):
51
 
        pass
52
 
 
53
 
    def lock_read(self):
54
 
        pass
55
 
 
56
 
    def unlock(self):
57
 
        pass
58
 
 
59
 
    def peek(self):
60
 
        pass
61
 
 
62
 
    def validate_token(self, token):
63
 
        pass
64
 
 
65
 
    def break_lock(self):
66
 
        pass
67
 
 
68
 
 
69
 
class GitLockableFiles(lockable_files.LockableFiles):
70
 
    """Git specific lockable files abstraction."""
71
 
 
72
 
    def __init__(self, transport, lock):
73
 
        self._lock = lock
74
 
        self._transaction = None
75
 
        self._lock_mode = None
76
 
        self._transport = transport
77
 
        if LockWarner is None:
78
 
            # Bzr 1.13
79
 
            self._lock_count = 0
80
 
        else:
81
 
            self._lock_warner = LockWarner(repr(self))
 
30
    )
 
31
from ..transport import (
 
32
    do_catching_redirections,
 
33
    get_transport_from_path,
 
34
    )
 
35
 
 
36
from ..controldir import (
 
37
    BranchReferenceLoop,
 
38
    ControlDir,
 
39
    ControlDirFormat,
 
40
    format_registry,
 
41
    RepositoryAcquisitionPolicy,
 
42
    )
 
43
 
 
44
from .push import (
 
45
    GitPushResult,
 
46
    )
 
47
from .transportgit import (
 
48
    OBJECTDIR,
 
49
    TransportObjectStore,
 
50
    )
82
51
 
83
52
 
84
53
class GitDirConfig(object):
87
56
        return None
88
57
 
89
58
    def set_default_stack_on(self, value):
90
 
        raise bzr_errors.BzrError("Cannot set configuration")
 
59
        raise brz_errors.BzrError("Cannot set configuration")
 
60
 
 
61
 
 
62
class GitControlDirFormat(ControlDirFormat):
 
63
 
 
64
    colocated_branches = True
 
65
    fixed_components = True
 
66
 
 
67
    def __eq__(self, other):
 
68
        return type(self) == type(other)
 
69
 
 
70
    def is_supported(self):
 
71
        return True
 
72
 
 
73
    def network_name(self):
 
74
        return b"git"
 
75
 
 
76
 
 
77
class UseExistingRepository(RepositoryAcquisitionPolicy):
 
78
    """A policy of reusing an existing repository"""
 
79
 
 
80
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
 
81
                 require_stacking=False):
 
82
        """Constructor.
 
83
 
 
84
        :param repository: The repository to use.
 
85
        :param stack_on: A location to stack on
 
86
        :param stack_on_pwd: If stack_on is relative, the location it is
 
87
            relative to.
 
88
        """
 
89
        super(UseExistingRepository, self).__init__(
 
90
            stack_on, stack_on_pwd, require_stacking)
 
91
        self._repository = repository
 
92
 
 
93
    def acquire_repository(self, make_working_trees=None, shared=False,
 
94
                           possible_transports=None):
 
95
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
 
96
 
 
97
        Returns an existing repository to use.
 
98
        """
 
99
        return self._repository, False
91
100
 
92
101
 
93
102
class GitDir(ControlDir):
100
109
        return False
101
110
 
102
111
    def break_lock(self):
103
 
        pass
 
112
        # There are no global locks, so nothing to break.
 
113
        raise NotImplementedError(self.break_lock)
104
114
 
105
115
    def cloning_metadir(self, stacked=False):
106
 
        return format_registry.make_bzrdir("default")
107
 
 
108
 
    def _branch_name_to_ref(self, name):
109
 
        raise NotImplementedError(self._branch_name_to_ref)
110
 
 
111
 
    if bzrlib_version >= (2, 2):
112
 
        def open_branch(self, name=None, unsupported=False, 
113
 
            ignore_fallbacks=None):
114
 
            return self._open_branch(name=name,
115
 
                ignore_fallbacks=ignore_fallbacks, unsupported=unsupported)
116
 
    else:
117
 
        def open_branch(self, ignore_fallbacks=None, unsupported=False):
118
 
            return self._open_branch(name=None,
119
 
                ignore_fallbacks=ignore_fallbacks, unsupported=unsupported)
 
116
        return format_registry.make_controldir("git")
 
117
 
 
118
    def checkout_metadir(self, stacked=False):
 
119
        return format_registry.make_controldir("git")
 
120
 
 
121
    def _get_selected_ref(self, branch, ref=None):
 
122
        if ref is not None and branch is not None:
 
123
            raise brz_errors.BzrError("can't specify both ref and branch")
 
124
        if ref is not None:
 
125
            return ref
 
126
        if branch is not None:
 
127
            from .refs import branch_name_to_ref
 
128
            return branch_name_to_ref(branch)
 
129
        segment_parameters = getattr(
 
130
            self.user_transport, "get_segment_parameters", lambda: {})()
 
131
        ref = segment_parameters.get("ref")
 
132
        if ref is not None:
 
133
            return urlutils.unquote_to_bytes(ref)
 
134
        if branch is None and getattr(self, "_get_selected_branch", False):
 
135
            branch = self._get_selected_branch()
 
136
            if branch is not None:
 
137
                from .refs import branch_name_to_ref
 
138
                return branch_name_to_ref(branch)
 
139
        return b"HEAD"
120
140
 
121
141
    def get_config(self):
122
142
        return GitDirConfig()
123
143
 
 
144
    def _available_backup_name(self, base):
 
145
        return osutils.available_backup_name(base, self.root_transport.has)
 
146
 
 
147
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
148
               recurse='down', possible_transports=None,
 
149
               accelerator_tree=None, hardlink=False, stacked=False,
 
150
               source_branch=None, create_tree_if_local=True):
 
151
        from ..repository import InterRepository
 
152
        from ..transport.local import LocalTransport
 
153
        from ..transport import get_transport
 
154
        target_transport = get_transport(url, possible_transports)
 
155
        target_transport.ensure_base()
 
156
        cloning_format = self.cloning_metadir()
 
157
        # Create/update the result branch
 
158
        try:
 
159
            result = ControlDir.open_from_transport(target_transport)
 
160
        except brz_errors.NotBranchError:
 
161
            result = cloning_format.initialize_on_transport(target_transport)
 
162
        source_branch = self.open_branch()
 
163
        source_repository = self.find_repository()
 
164
        try:
 
165
            result_repo = result.find_repository()
 
166
        except brz_errors.NoRepositoryPresent:
 
167
            result_repo = result.create_repository()
 
168
        if stacked:
 
169
            raise _mod_branch.UnstackableBranchFormat(
 
170
                self._format, self.user_url)
 
171
        interrepo = InterRepository.get(source_repository, result_repo)
 
172
 
 
173
        if revision_id is not None:
 
174
            determine_wants = interrepo.get_determine_wants_revids(
 
175
                [revision_id], include_tags=True)
 
176
        else:
 
177
            determine_wants = interrepo.determine_wants_all
 
178
        interrepo.fetch_objects(determine_wants=determine_wants,
 
179
                                mapping=source_branch.mapping)
 
180
        result_branch = source_branch.sprout(
 
181
            result, revision_id=revision_id, repository=result_repo)
 
182
        if (create_tree_if_local and
 
183
            result.open_branch(name="").name == result_branch.name and
 
184
            isinstance(target_transport, LocalTransport) and
 
185
                (result_repo is None or result_repo.make_working_trees())):
 
186
            wt = result.create_workingtree(
 
187
                accelerator_tree=accelerator_tree,
 
188
                hardlink=hardlink, from_branch=result_branch)
 
189
        else:
 
190
            wt = None
 
191
        if recurse == 'down':
 
192
            with contextlib.ExitStack() as stack:
 
193
                basis = None
 
194
                if wt is not None:
 
195
                    basis = wt.basis_tree()
 
196
                elif result_branch is not None:
 
197
                    basis = result_branch.basis_tree()
 
198
                elif source_branch is not None:
 
199
                    basis = source_branch.basis_tree()
 
200
                if basis is not None:
 
201
                    stack.enter_context(basis.lock_read())
 
202
                    subtrees = basis.iter_references()
 
203
                else:
 
204
                    subtrees = []
 
205
                for path in subtrees:
 
206
                    target = urlutils.join(url, urlutils.escape(path))
 
207
                    sublocation = wt.reference_parent(
 
208
                        path, possible_transports=possible_transports)
 
209
                    if sublocation is None:
 
210
                        trace.warning(
 
211
                            'Ignoring nested tree %s, parent location unknown.',
 
212
                            path)
 
213
                        continue
 
214
                    sublocation.controldir.sprout(
 
215
                        target, basis.get_reference_revision(path),
 
216
                        force_new_repo=force_new_repo, recurse=recurse,
 
217
                        stacked=stacked)
 
218
        return result
 
219
 
 
220
    def clone_on_transport(self, transport, revision_id=None,
 
221
                           force_new_repo=False, preserve_stacking=False,
 
222
                           stacked_on=None, create_prefix=False,
 
223
                           use_existing_dir=True, no_tree=False):
 
224
        """See ControlDir.clone_on_transport."""
 
225
        from ..repository import InterRepository
 
226
        from .mapping import default_mapping
 
227
        if stacked_on is not None:
 
228
            raise _mod_branch.UnstackableBranchFormat(
 
229
                self._format, self.user_url)
 
230
        if no_tree:
 
231
            format = BareLocalGitControlDirFormat()
 
232
        else:
 
233
            format = LocalGitControlDirFormat()
 
234
        (target_repo, target_controldir, stacking,
 
235
         repo_policy) = format.initialize_on_transport_ex(
 
236
            transport, use_existing_dir=use_existing_dir,
 
237
            create_prefix=create_prefix,
 
238
            force_new_repo=force_new_repo)
 
239
        target_repo = target_controldir.find_repository()
 
240
        target_git_repo = target_repo._git
 
241
        source_repo = self.find_repository()
 
242
        interrepo = InterRepository.get(source_repo, target_repo)
 
243
        if revision_id is not None:
 
244
            determine_wants = interrepo.get_determine_wants_revids(
 
245
                [revision_id], include_tags=True)
 
246
        else:
 
247
            determine_wants = interrepo.determine_wants_all
 
248
        (pack_hint, _, refs) = interrepo.fetch_objects(determine_wants,
 
249
                                                       mapping=default_mapping)
 
250
        for name, val in refs.items():
 
251
            target_git_repo.refs[name] = val
 
252
        result_dir = self.__class__(transport, target_git_repo, format)
 
253
        if revision_id is not None:
 
254
            result_dir.open_branch().set_last_revision(revision_id)
 
255
        try:
 
256
            # Cheaper to check if the target is not local, than to try making
 
257
            # the tree and fail.
 
258
            result_dir.root_transport.local_abspath('.')
 
259
            if result_dir.open_repository().make_working_trees():
 
260
                self.open_workingtree().clone(
 
261
                    result_dir, revision_id=revision_id)
 
262
        except (brz_errors.NoWorkingTree, brz_errors.NotLocalUrl):
 
263
            pass
 
264
 
 
265
        return result_dir
 
266
 
 
267
    def find_repository(self):
 
268
        """Find the repository that should be used.
 
269
 
 
270
        This does not require a branch as we use it to find the repo for
 
271
        new branches as well as to hook existing branches up to their
 
272
        repository.
 
273
        """
 
274
        return self._gitrepository_class(self._find_commondir())
 
275
 
 
276
    def get_refs_container(self):
 
277
        """Retrieve the refs container.
 
278
        """
 
279
        raise NotImplementedError(self.get_refs_container)
 
280
 
 
281
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
 
282
                                    stack_on_pwd=None, require_stacking=False):
 
283
        """Return an object representing a policy to use.
 
284
 
 
285
        This controls whether a new repository is created, and the format of
 
286
        that repository, or some existing shared repository used instead.
 
287
 
 
288
        If stack_on is supplied, will not seek a containing shared repo.
 
289
 
 
290
        :param force_new_repo: If True, require a new repository to be created.
 
291
        :param stack_on: If supplied, the location to stack on.  If not
 
292
            supplied, a default_stack_on location may be used.
 
293
        :param stack_on_pwd: If stack_on is relative, the location it is
 
294
            relative to.
 
295
        """
 
296
        return UseExistingRepository(self.find_repository())
 
297
 
 
298
    def get_branches(self):
 
299
        from .refs import ref_to_branch_name
 
300
        ret = {}
 
301
        for ref in self.get_refs_container().keys():
 
302
            try:
 
303
                branch_name = ref_to_branch_name(ref)
 
304
            except UnicodeDecodeError:
 
305
                trace.warning("Ignoring branch %r with unicode error ref", ref)
 
306
                continue
 
307
            except ValueError:
 
308
                continue
 
309
            ret[branch_name] = self.open_branch(ref=ref)
 
310
        return ret
 
311
 
 
312
    def list_branches(self):
 
313
        return list(self.get_branches().values())
 
314
 
 
315
    def push_branch(self, source, revision_id=None, overwrite=False,
 
316
                    remember=False, create_prefix=False, lossy=False,
 
317
                    name=None):
 
318
        """Push the source branch into this ControlDir."""
 
319
        push_result = GitPushResult()
 
320
        push_result.workingtree_updated = None
 
321
        push_result.master_branch = None
 
322
        push_result.source_branch = source
 
323
        push_result.stacked_on = None
 
324
        from .branch import GitBranch
 
325
        if isinstance(source, GitBranch) and lossy:
 
326
            raise brz_errors.LossyPushToSameVCS(source.controldir, self)
 
327
        target = self.open_branch(name, nascent_ok=True)
 
328
        push_result.branch_push_result = source.push(
 
329
            target, overwrite=overwrite, stop_revision=revision_id,
 
330
            lossy=lossy)
 
331
        push_result.new_revid = push_result.branch_push_result.new_revid
 
332
        push_result.old_revid = push_result.branch_push_result.old_revid
 
333
        try:
 
334
            wt = self.open_workingtree()
 
335
        except brz_errors.NoWorkingTree:
 
336
            push_result.workingtree_updated = None
 
337
        else:
 
338
            if self.open_branch(name="").name == target.name:
 
339
                wt._update_git_tree(
 
340
                    old_revision=push_result.old_revid,
 
341
                    new_revision=push_result.new_revid)
 
342
                push_result.workingtree_updated = True
 
343
            else:
 
344
                push_result.workingtree_updated = False
 
345
        push_result.target_branch = target
 
346
        if source.get_push_location() is None or remember:
 
347
            source.set_push_location(push_result.target_branch.base)
 
348
        return push_result
 
349
 
 
350
 
 
351
class LocalGitControlDirFormat(GitControlDirFormat):
 
352
    """The .git directory control format."""
 
353
 
 
354
    bare = False
 
355
 
 
356
    @classmethod
 
357
    def _known_formats(self):
 
358
        return set([LocalGitControlDirFormat()])
 
359
 
 
360
    @property
 
361
    def repository_format(self):
 
362
        from .repository import GitRepositoryFormat
 
363
        return GitRepositoryFormat()
 
364
 
 
365
    @property
 
366
    def workingtree_format(self):
 
367
        from .workingtree import GitWorkingTreeFormat
 
368
        return GitWorkingTreeFormat()
 
369
 
 
370
    def get_branch_format(self):
 
371
        from .branch import LocalGitBranchFormat
 
372
        return LocalGitBranchFormat()
 
373
 
 
374
    def open(self, transport, _found=None):
 
375
        """Open this directory.
 
376
 
 
377
        """
 
378
        from .transportgit import TransportRepo
 
379
 
 
380
        def _open(transport):
 
381
            try:
 
382
                return TransportRepo(transport, self.bare,
 
383
                                     refs_text=getattr(self, "_refs_text", None))
 
384
            except ValueError as e:
 
385
                if e.args == ('Expected file to start with \'gitdir: \'', ):
 
386
                    raise brz_errors.NotBranchError(path=transport.base)
 
387
                raise
 
388
 
 
389
        def redirected(transport, e, redirection_notice):
 
390
            trace.note(redirection_notice)
 
391
            return transport._redirected_to(e.source, e.target)
 
392
        gitrepo = do_catching_redirections(_open, transport, redirected)
 
393
        if not _found and not gitrepo._controltransport.has('objects'):
 
394
            raise brz_errors.NotBranchError(path=transport.base)
 
395
        return LocalGitDir(transport, gitrepo, self)
 
396
 
 
397
    def get_format_description(self):
 
398
        return "Local Git Repository"
 
399
 
 
400
    def initialize_on_transport(self, transport):
 
401
        from .transportgit import TransportRepo
 
402
        git_repo = TransportRepo.init(transport, bare=self.bare)
 
403
        return LocalGitDir(transport, git_repo, self)
 
404
 
 
405
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
406
                                   create_prefix=False, force_new_repo=False,
 
407
                                   stacked_on=None,
 
408
                                   stack_on_pwd=None, repo_format_name=None,
 
409
                                   make_working_trees=None,
 
410
                                   shared_repo=False, vfs_only=False):
 
411
        if shared_repo:
 
412
            raise brz_errors.SharedRepositoriesUnsupported(self)
 
413
 
 
414
        def make_directory(transport):
 
415
            transport.mkdir('.')
 
416
            return transport
 
417
 
 
418
        def redirected(transport, e, redirection_notice):
 
419
            trace.note(redirection_notice)
 
420
            return transport._redirected_to(e.source, e.target)
 
421
        try:
 
422
            transport = do_catching_redirections(
 
423
                make_directory, transport, redirected)
 
424
        except brz_errors.FileExists:
 
425
            if not use_existing_dir:
 
426
                raise
 
427
        except brz_errors.NoSuchFile:
 
428
            if not create_prefix:
 
429
                raise
 
430
            transport.create_prefix()
 
431
        controldir = self.initialize_on_transport(transport)
 
432
        if repo_format_name:
 
433
            result_repo = controldir.find_repository()
 
434
            repository_policy = UseExistingRepository(result_repo)
 
435
            result_repo.lock_write()
 
436
        else:
 
437
            result_repo = None
 
438
            repository_policy = None
 
439
        return (result_repo, controldir, False,
 
440
                repository_policy)
 
441
 
 
442
    def is_supported(self):
 
443
        return True
 
444
 
 
445
    def supports_transport(self, transport):
 
446
        try:
 
447
            external_url = transport.external_url()
 
448
        except brz_errors.InProcessTransport:
 
449
            raise brz_errors.NotBranchError(path=transport.base)
 
450
        return external_url.startswith("file:")
 
451
 
 
452
    def is_control_filename(self, filename):
 
453
        return (filename == '.git'
 
454
                or filename.startswith('.git/')
 
455
                or filename.startswith('.git\\'))
 
456
 
 
457
 
 
458
class BareLocalGitControlDirFormat(LocalGitControlDirFormat):
 
459
 
 
460
    bare = True
 
461
    supports_workingtrees = False
 
462
 
 
463
    def get_format_description(self):
 
464
        return "Local Git Repository (bare)"
 
465
 
 
466
    def is_control_filename(self, filename):
 
467
        return False
 
468
 
124
469
 
125
470
class LocalGitDir(GitDir):
126
471
    """An adapter to the '.git' dir used by git."""
127
472
 
128
473
    def _get_gitrepository_class(self):
129
 
        from bzrlib.plugins.git.repository import LocalGitRepository
 
474
        from .repository import LocalGitRepository
130
475
        return LocalGitRepository
131
476
 
 
477
    def __repr__(self):
 
478
        return "<%s at %r>" % (
 
479
            self.__class__.__name__, self.root_transport.base)
 
480
 
132
481
    _gitrepository_class = property(_get_gitrepository_class)
133
482
 
134
483
    @property
137
486
 
138
487
    @property
139
488
    def control_transport(self):
140
 
        return self.transport
 
489
        return self._git._controltransport
141
490
 
142
 
    def __init__(self, transport, lockfiles, gitrepo, format):
 
491
    def __init__(self, transport, gitrepo, format):
143
492
        self._format = format
144
493
        self.root_transport = transport
145
494
        self._mode_check_done = False
148
497
            self.transport = transport
149
498
        else:
150
499
            self.transport = transport.clone('.git')
151
 
        self._lockfiles = lockfiles
152
500
        self._mode_check_done = None
153
501
 
154
 
    def _branch_name_to_ref(self, name):
155
 
        from bzrlib.plugins.git.refs import branch_name_to_ref
156
 
        ref = branch_name_to_ref(name, None)
157
 
        if ref == "HEAD":
158
 
            from dulwich.repo import SYMREF
159
 
            refcontents = self._git.refs.read_ref(ref)
160
 
            if refcontents.startswith(SYMREF):
161
 
                ref = refcontents[len(SYMREF):]
162
 
        return ref
163
 
 
164
 
    def is_control_filename(self, filename):
165
 
        return filename == '.git' or filename.startswith('.git/')
 
502
    def _get_symref(self, ref):
 
503
        ref_chain, unused_sha = self._git.refs.follow(ref)
 
504
        if len(ref_chain) == 1:
 
505
            return None
 
506
        return ref_chain[1]
 
507
 
 
508
    def set_branch_reference(self, target_branch, name=None):
 
509
        ref = self._get_selected_ref(name)
 
510
        target_transport = target_branch.controldir.control_transport
 
511
        if self.control_transport.base == target_transport.base:
 
512
            if ref == target_branch.ref:
 
513
                raise BranchReferenceLoop(target_branch)
 
514
            self._git.refs.set_symbolic_ref(ref, target_branch.ref)
 
515
        else:
 
516
            try:
 
517
                target_path = (
 
518
                    target_branch.controldir.control_transport.local_abspath(
 
519
                        '.'))
 
520
            except brz_errors.NotLocalUrl:
 
521
                raise brz_errors.IncompatibleFormat(
 
522
                    target_branch._format, self._format)
 
523
            # TODO(jelmer): Do some consistency checking across branches..
 
524
            self.control_transport.put_bytes(
 
525
                'commondir', target_path.encode('utf-8'))
 
526
            # TODO(jelmer): Urgh, avoid mucking about with internals.
 
527
            self._git._commontransport = (
 
528
                target_branch.repository._git._commontransport.clone())
 
529
            self._git.object_store = TransportObjectStore(
 
530
                self._git._commontransport.clone(OBJECTDIR))
 
531
            self._git.refs.transport = self._git._commontransport
 
532
            target_ref_chain, unused_sha = (
 
533
                target_branch.controldir._git.refs.follow(target_branch.ref))
 
534
            for target_ref in target_ref_chain:
 
535
                if target_ref == b'HEAD':
 
536
                    continue
 
537
                break
 
538
            else:
 
539
                # Can't create a reference to something that is not a in a repository.
 
540
                raise brz_errors.IncompatibleFormat(
 
541
                    self.set_branch_reference, self)
 
542
            self._git.refs.set_symbolic_ref(ref, target_ref)
 
543
 
 
544
    def get_branch_reference(self, name=None):
 
545
        ref = self._get_selected_ref(name)
 
546
        target_ref = self._get_symref(ref)
 
547
        if target_ref is not None:
 
548
            from .refs import ref_to_branch_name
 
549
            try:
 
550
                branch_name = ref_to_branch_name(target_ref)
 
551
            except ValueError:
 
552
                params = {'ref': urlutils.quote(
 
553
                    target_ref.decode('utf-8'), '')}
 
554
            else:
 
555
                if branch_name != '':
 
556
                    params = {'branch': urlutils.quote(branch_name, '')}
 
557
                else:
 
558
                    params = {}
 
559
            try:
 
560
                commondir = self.control_transport.get_bytes('commondir')
 
561
            except brz_errors.NoSuchFile:
 
562
                base_url = self.user_url.rstrip('/')
 
563
            else:
 
564
                base_url = urlutils.local_path_to_url(
 
565
                    commondir.decode(osutils._fs_enc)).rstrip('/.git/') + '/'
 
566
            return urlutils.join_segment_parameters(base_url, params)
 
567
        return None
 
568
 
 
569
    def find_branch_format(self, name=None):
 
570
        from .branch import (
 
571
            LocalGitBranchFormat,
 
572
            )
 
573
        return LocalGitBranchFormat()
166
574
 
167
575
    def get_branch_transport(self, branch_format, name=None):
168
576
        if branch_format is None:
169
577
            return self.transport
170
578
        if isinstance(branch_format, LocalGitControlDirFormat):
171
579
            return self.transport
172
 
        raise bzr_errors.IncompatibleFormat(branch_format, self._format)
 
580
        raise brz_errors.IncompatibleFormat(branch_format, self._format)
173
581
 
174
582
    def get_repository_transport(self, format):
175
583
        if format is None:
176
584
            return self.transport
177
585
        if isinstance(format, LocalGitControlDirFormat):
178
586
            return self.transport
179
 
        raise bzr_errors.IncompatibleFormat(format, self._format)
 
587
        raise brz_errors.IncompatibleFormat(format, self._format)
180
588
 
181
589
    def get_workingtree_transport(self, format):
182
590
        if format is None:
183
591
            return self.transport
184
592
        if isinstance(format, LocalGitControlDirFormat):
185
593
            return self.transport
186
 
        raise bzr_errors.IncompatibleFormat(format, self._format)
 
594
        raise brz_errors.IncompatibleFormat(format, self._format)
187
595
 
188
 
    def _open_branch(self, name=None, ignore_fallbacks=None, unsupported=False):
 
596
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=None,
 
597
                    ref=None, possible_transports=None, nascent_ok=False):
189
598
        """'create' a branch for this dir."""
190
 
        repo = self.open_repository()
191
 
        from bzrlib.plugins.git.branch import LocalGitBranch
192
 
        return LocalGitBranch(self, repo, self._branch_name_to_ref(name),
193
 
            self._lockfiles)
 
599
        repo = self.find_repository()
 
600
        from .branch import LocalGitBranch
 
601
        ref = self._get_selected_ref(name, ref)
 
602
        if not nascent_ok and ref not in self._git.refs:
 
603
            raise brz_errors.NotBranchError(
 
604
                self.root_transport.base, controldir=self)
 
605
        ref_chain, unused_sha = self._git.refs.follow(ref)
 
606
        if ref_chain[-1] == b'HEAD':
 
607
            controldir = self
 
608
        else:
 
609
            controldir = self._find_commondir()
 
610
        return LocalGitBranch(controldir, repo, ref_chain[-1])
194
611
 
195
612
    def destroy_branch(self, name=None):
196
 
        refname = self._branch_name_to_ref(name)
197
 
        if not refname in self._git.refs:
198
 
            raise bzr_errors.NotBranchError(self.root_transport.base,
199
 
                    bzrdir=self)
200
 
        del self._git.refs[refname]
 
613
        refname = self._get_selected_ref(name)
 
614
        if refname == b'HEAD':
 
615
            # HEAD can't be removed
 
616
            raise brz_errors.UnsupportedOperation(
 
617
                self.destroy_branch, self)
 
618
        try:
 
619
            del self._git.refs[refname]
 
620
        except KeyError:
 
621
            raise brz_errors.NotBranchError(
 
622
                self.root_transport.base, controldir=self)
201
623
 
202
624
    def destroy_repository(self):
203
 
        raise bzr_errors.UnsupportedOperation(self.destroy_repository, self)
 
625
        raise brz_errors.UnsupportedOperation(self.destroy_repository, self)
204
626
 
205
627
    def destroy_workingtree(self):
206
 
        raise bzr_errors.UnsupportedOperation(self.destroy_workingtree, self)
 
628
        raise brz_errors.UnsupportedOperation(self.destroy_workingtree, self)
 
629
 
 
630
    def destroy_workingtree_metadata(self):
 
631
        raise brz_errors.UnsupportedOperation(
 
632
            self.destroy_workingtree_metadata, self)
207
633
 
208
634
    def needs_format_conversion(self, format=None):
209
635
        return not isinstance(self._format, format.__class__)
210
636
 
211
 
    def list_branches(self):
212
 
        ret = []
213
 
        for name in self._git.get_refs():
214
 
            if name.startswith("refs/heads/"):
215
 
                ret.append(self.open_branch(name=name))
216
 
        return ret
217
 
 
218
 
    def open_repository(self, shared=False):
 
637
    def open_repository(self):
219
638
        """'open' a repository for this dir."""
220
 
        return self._gitrepository_class(self, self._lockfiles)
221
 
 
222
 
    def open_workingtree(self, recommend_upgrade=True):
 
639
        if self.control_transport.has('commondir'):
 
640
            raise brz_errors.NoRepositoryPresent(self)
 
641
        return self._gitrepository_class(self)
 
642
 
 
643
    def has_workingtree(self):
 
644
        return not self._git.bare
 
645
 
 
646
    def open_workingtree(self, recommend_upgrade=True, unsupported=False):
223
647
        if not self._git.bare:
224
 
            from dulwich.errors import NoIndexPresent
225
 
            repo = self.open_repository()
226
 
            try:
227
 
                index = repo._git.open_index()
228
 
            except NoIndexPresent:
229
 
                pass
230
 
            else:
231
 
                from bzrlib.plugins.git.workingtree import GitWorkingTree
232
 
                try:
233
 
                    branch = self.open_branch()
234
 
                except bzr_errors.NotBranchError:
235
 
                    pass
236
 
                else:
237
 
                    return GitWorkingTree(self, repo, branch, index)
 
648
            repo = self.find_repository()
 
649
            from .workingtree import GitWorkingTree
 
650
            branch = self.open_branch(ref=b'HEAD', nascent_ok=True)
 
651
            return GitWorkingTree(self, repo, branch)
238
652
        loc = urlutils.unescape_for_display(self.root_transport.base, 'ascii')
239
 
        raise bzr_errors.NoWorkingTree(loc)
 
653
        raise brz_errors.NoWorkingTree(loc)
240
654
 
241
655
    def create_repository(self, shared=False):
242
 
        return self.open_repository()
 
656
        from .repository import GitRepositoryFormat
 
657
        if shared:
 
658
            raise brz_errors.IncompatibleFormat(
 
659
                GitRepositoryFormat(), self._format)
 
660
        return self.find_repository()
243
661
 
244
 
    def create_branch(self, name=None):
245
 
        refname = self._branch_name_to_ref(name)
246
 
        from dulwich.protocol import ZERO_SHA
247
 
        self._git.refs[refname or "HEAD"] = ZERO_SHA
248
 
        return self.open_branch(name)
 
662
    def create_branch(self, name=None, repository=None,
 
663
                      append_revisions_only=None, ref=None):
 
664
        refname = self._get_selected_ref(name, ref)
 
665
        if refname != b'HEAD' and refname in self._git.refs:
 
666
            raise brz_errors.AlreadyBranchError(self.user_url)
 
667
        repo = self.open_repository()
 
668
        if refname in self._git.refs:
 
669
            ref_chain, unused_sha = self._git.refs.follow(
 
670
                self._get_selected_ref(None))
 
671
            if ref_chain[0] == b'HEAD':
 
672
                refname = ref_chain[1]
 
673
        from .branch import LocalGitBranch
 
674
        branch = LocalGitBranch(self, repo, refname)
 
675
        if append_revisions_only:
 
676
            branch.set_append_revisions_only(append_revisions_only)
 
677
        return branch
249
678
 
250
679
    def backup_bzrdir(self):
251
 
        if self._git.bare:
 
680
        if not self._git.bare:
252
681
            self.root_transport.copy_tree(".git", ".git.backup")
253
682
            return (self.root_transport.abspath(".git"),
254
683
                    self.root_transport.abspath(".git.backup"))
255
684
        else:
256
 
            raise bzr_errors.BzrError("Unable to backup bare repositories")
 
685
            basename = urlutils.basename(self.root_transport.base)
 
686
            parent = self.root_transport.clone('..')
 
687
            parent.copy_tree(basename, basename + ".backup")
257
688
 
258
689
    def create_workingtree(self, revision_id=None, from_branch=None,
259
 
        accelerator_tree=None, hardlink=False):
 
690
                           accelerator_tree=None, hardlink=False):
260
691
        if self._git.bare:
261
 
            raise bzr_errors.BzrError("Can't create working tree in a bare repo")
262
 
        from dulwich.index import write_index
263
 
        from dulwich.pack import SHA1Writer
264
 
        f = open(self.transport.local_abspath("index"), 'w+')
265
 
        try:
266
 
            f = SHA1Writer(f)
267
 
            write_index(f, [])
268
 
        finally:
269
 
            f.close()
270
 
        return self.open_workingtree()
271
 
 
272
 
    def find_repository(self):
273
 
        """Find the repository that should be used.
274
 
 
275
 
        This does not require a branch as we use it to find the repo for
276
 
        new branches as well as to hook existing branches up to their
277
 
        repository.
278
 
        """
279
 
        return self.open_repository()
 
692
            raise brz_errors.UnsupportedOperation(
 
693
                self.create_workingtree, self)
 
694
        if from_branch is None:
 
695
            from_branch = self.open_branch(nascent_ok=True)
 
696
        if revision_id is None:
 
697
            revision_id = from_branch.last_revision()
 
698
        repo = self.find_repository()
 
699
        from .workingtree import GitWorkingTree
 
700
        wt = GitWorkingTree(self, repo, from_branch)
 
701
        wt.set_last_revision(revision_id)
 
702
        wt._build_checkout_with_index()
 
703
        return wt
 
704
 
 
705
    def _find_or_create_repository(self, force_new_repo=None):
 
706
        return self.create_repository(shared=False)
280
707
 
281
708
    def _find_creation_modes(self):
282
709
        """Determine the appropriate modes for files and directories.
291
718
        self._mode_check_done = True
292
719
        try:
293
720
            st = self.transport.stat('.')
294
 
        except TransportNotPossible:
 
721
        except brz_errors.TransportNotPossible:
295
722
            self._dir_mode = None
296
723
            self._file_mode = None
297
724
        else:
299
726
            # directories and files are read-write for this user. This is
300
727
            # mostly a workaround for filesystems which lie about being able to
301
728
            # write to a directory (cygwin & win32)
302
 
            if (st.st_mode & 07777 == 00000):
 
729
            if (st.st_mode & 0o7777 == 0o0000):
303
730
                # FTP allows stat but does not return dir/file modes
304
731
                self._dir_mode = None
305
732
                self._file_mode = None
306
733
            else:
307
 
                self._dir_mode = (st.st_mode & 07777) | 00700
 
734
                self._dir_mode = (st.st_mode & 0o7777) | 0o0700
308
735
                # Remove the sticky and execute bits for files
309
 
                self._file_mode = self._dir_mode & ~07111
 
736
                self._file_mode = self._dir_mode & ~0o7111
310
737
 
311
738
    def _get_file_mode(self):
312
739
        """Return Unix mode for newly created files, or None.
322
749
            self._find_creation_modes()
323
750
        return self._dir_mode
324
751
 
325
 
 
 
752
    def get_refs_container(self):
 
753
        return self._git.refs
 
754
 
 
755
    def get_peeled(self, ref):
 
756
        return self._git.get_peeled(ref)
 
757
 
 
758
    def _find_commondir(self):
 
759
        try:
 
760
            commondir = self.control_transport.get_bytes('commondir')
 
761
        except brz_errors.NoSuchFile:
 
762
            return self
 
763
        else:
 
764
            commondir = commondir.rstrip(b'/.git/').decode(osutils._fs_enc)
 
765
            return ControlDir.open_from_transport(
 
766
                get_transport_from_path(commondir))