/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
1
# Copyright (C) 2007 Canonical Ltd
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
2
# Copyright (C) 2010-2018 Jelmer Vernooij
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
0.358.1 by Jelmer Vernooij
Fix FSF address.
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
17
0.200.1012 by Jelmer Vernooij
Rename BzrDir to ControlDir.
18
"""An adapter between a Git control dir and a Bazaar ControlDir."""
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
19
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
20
from __future__ import absolute_import
21
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
22
from ... import (
0.200.1688 by Jelmer Vernooij
Fix stacking tests.
23
    branch as _mod_branch,
0.239.13 by Jelmer Vernooij
Don't break "bzr info -v" when Dulwich is not installed.
24
    errors as bzr_errors,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
25
    trace,
0.200.1172 by Jelmer Vernooij
Provide GitDir._available_backup_name.
26
    osutils,
0.419.1 by Jelmer Vernooij
Simplify pushing to Git directories.
27
    repository as _mod_repository,
0.200.1566 by Jelmer Vernooij
Basic implementation of LocalGitDir.destroy_workingtree.
28
    revision as _mod_revision,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
29
    urlutils,
30
    )
7018.3.2 by Jelmer Vernooij
Fix some git tests.
31
from ...sixish import viewitems
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
32
from ...transport import (
33
    do_catching_redirections,
34
    get_transport_from_path,
35
    )
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
36
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
37
from ...controldir import (
0.416.1 by Jelmer Vernooij
Raise BranchReferenceLoop.
38
    BranchReferenceLoop,
0.200.1111 by Jelmer Vernooij
Drop support for Bazaar < 2.3.
39
    ControlDir,
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
40
    ControlDirFormat,
0.200.1111 by Jelmer Vernooij
Drop support for Bazaar < 2.3.
41
    format_registry,
0.200.1702 by Jelmer Vernooij
Implement GitDir.acquire_repository.
42
    RepositoryAcquisitionPolicy,
0.200.1111 by Jelmer Vernooij
Drop support for Bazaar < 2.3.
43
    )
0.401.4 by Jelmer Vernooij
Implement RemoteGitDir.push_branch.
44
from .object_store import (
45
    get_object_store,
46
    )
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
47
0.419.1 by Jelmer Vernooij
Simplify pushing to Git directories.
48
from .push import (
49
    GitPushResult,
50
    )
0.311.3 by Jelmer Vernooij
Fix handling of lightweight checkouts.
51
from .transportgit import (
52
    OBJECTDIR,
53
    TransportObjectStore,
54
    )
55
0.200.123 by Jelmer Vernooij
Use central git module.
56
0.200.1026 by Jelmer Vernooij
Fix typo.
57
class GitDirConfig(object):
0.200.1025 by Jelmer Vernooij
Implement GitDir.get_config().
58
59
    def get_default_stack_on(self):
60
        return None
61
62
    def set_default_stack_on(self, value):
63
        raise bzr_errors.BzrError("Cannot set configuration")
64
65
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
66
class GitControlDirFormat(ControlDirFormat):
67
68
    colocated_branches = True
69
    fixed_components = True
70
71
    def __eq__(self, other):
72
        return type(self) == type(other)
73
74
    def is_supported(self):
75
        return True
76
77
    def network_name(self):
7018.3.2 by Jelmer Vernooij
Fix some git tests.
78
        return b"git"
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
79
80
0.200.1702 by Jelmer Vernooij
Implement GitDir.acquire_repository.
81
class UseExistingRepository(RepositoryAcquisitionPolicy):
82
    """A policy of reusing an existing repository"""
83
84
    def __init__(self, repository, stack_on=None, stack_on_pwd=None,
85
                 require_stacking=False):
86
        """Constructor.
87
88
        :param repository: The repository to use.
89
        :param stack_on: A location to stack on
90
        :param stack_on_pwd: If stack_on is relative, the location it is
91
            relative to.
92
        """
93
        super(UseExistingRepository, self).__init__(
94
                stack_on, stack_on_pwd, require_stacking)
95
        self._repository = repository
96
97
    def acquire_repository(self, make_working_trees=None, shared=False,
98
            possible_transports=None):
99
        """Implementation of RepositoryAcquisitionPolicy.acquire_repository
100
101
        Returns an existing repository to use.
102
        """
103
        return self._repository, False
104
105
0.200.1012 by Jelmer Vernooij
Rename BzrDir to ControlDir.
106
class GitDir(ControlDir):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
107
    """An adapter to the '.git' dir used by git."""
108
0.200.148 by Jelmer Vernooij
Share more infrastructure between LocalGitDir and RemoteGitDir.
109
    def is_supported(self):
110
        return True
111
0.200.981 by Jelmer Vernooij
Mark git directories as not convertable (for now).
112
    def can_convert_format(self):
113
        return False
114
0.200.1025 by Jelmer Vernooij
Implement GitDir.get_config().
115
    def break_lock(self):
0.314.1 by Jelmer Vernooij
Mark ControlDir.break_lock as not implemented.
116
        # There are no global locks, so nothing to break.
117
        raise NotImplementedError(self.break_lock)
0.200.1025 by Jelmer Vernooij
Implement GitDir.get_config().
118
0.200.155 by Jelmer Vernooij
Fix formatting, remove catch-all for exceptions when opening local repositories.
119
    def cloning_metadir(self, stacked=False):
0.288.1 by Jelmer Vernooij
Use git format as default for clones.
120
        return format_registry.make_controldir("git")
0.200.155 by Jelmer Vernooij
Fix formatting, remove catch-all for exceptions when opening local repositories.
121
0.200.1165 by Jelmer Vernooij
Implement GitDir.checkout_metadir.
122
    def checkout_metadir(self, stacked=False):
0.288.1 by Jelmer Vernooij
Use git format as default for clones.
123
        return format_registry.make_controldir("git")
0.200.1165 by Jelmer Vernooij
Implement GitDir.checkout_metadir.
124
0.269.8 by Jelmer Vernooij
Support push in git-remote-bzr.
125
    def _get_selected_ref(self, branch, ref=None):
126
        if ref is not None and branch is not None:
127
            raise bzr_errors.BzrError("can't specify both ref and branch")
128
        if ref is not None:
129
            return ref
0.303.2 by Jelmer Vernooij
Fix resolution order for segment parameters.
130
        if branch is not None:
131
            from .refs import branch_name_to_ref
132
            return branch_name_to_ref(branch)
0.200.1559 by Jelmer Vernooij
Fix compatibility with bzr 2.5.
133
        segment_parameters = getattr(
134
            self.user_transport, "get_segment_parameters", lambda: {})()
135
        ref = segment_parameters.get("ref")
136
        if ref is not None:
137
            return urlutils.unescape(ref)
0.200.1310 by Jelmer Vernooij
Add _get_selected_ref method.
138
        if branch is None and getattr(self, "_get_selected_branch", False):
139
            branch = self._get_selected_branch()
0.303.2 by Jelmer Vernooij
Fix resolution order for segment parameters.
140
            if branch is not None:
141
                from .refs import branch_name_to_ref
142
                return branch_name_to_ref(branch)
0.303.1 by Jelmer Vernooij
Remove _get_default_ref.
143
        return b"HEAD"
0.200.1310 by Jelmer Vernooij
Add _get_selected_ref method.
144
0.200.1025 by Jelmer Vernooij
Implement GitDir.get_config().
145
    def get_config(self):
146
        return GitDirConfig()
147
0.200.1172 by Jelmer Vernooij
Provide GitDir._available_backup_name.
148
    def _available_backup_name(self, base):
149
        return osutils.available_backup_name(base, self.root_transport.has)
150
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
151
    def sprout(self, url, revision_id=None, force_new_repo=False,
152
               recurse='down', possible_transports=None,
153
               accelerator_tree=None, hardlink=False, stacked=False,
154
               source_branch=None, create_tree_if_local=True):
0.200.1644 by Jelmer Vernooij
More relative imports.
155
        from ...repository import InterRepository
156
        from ...transport.local import LocalTransport
157
        from ...transport import get_transport
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
158
        target_transport = get_transport(url, possible_transports)
159
        target_transport.ensure_base()
160
        cloning_format = self.cloning_metadir()
161
        # Create/update the result branch
0.310.15 by Jelmer Vernooij
Handle destroy_workingtree.
162
        try:
163
            result = ControlDir.open_from_transport(target_transport)
164
        except bzr_errors.NotBranchError:
165
            result = cloning_format.initialize_on_transport(target_transport)
0.200.1373 by Jelmer Vernooij
Prevent accidentally removing branch.
166
        source_branch = self.open_branch()
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
167
        source_repository = self.find_repository()
168
        try:
169
            result_repo = result.find_repository()
170
        except bzr_errors.NoRepositoryPresent:
171
            result_repo = result.create_repository()
172
            target_is_empty = True
173
        else:
174
            target_is_empty = None # Unknown
175
        if stacked:
0.200.1688 by Jelmer Vernooij
Fix stacking tests.
176
            raise _mod_branch.UnstackableBranchFormat(self._format, self.user_url)
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
177
        interrepo = InterRepository.get(source_repository, result_repo)
178
179
        if revision_id is not None:
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
180
            determine_wants = interrepo.get_determine_wants_revids(
0.200.1777 by Jelmer Vernooij
Copy tags.
181
                [revision_id], include_tags=True)
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
182
        else:
0.259.4 by Jelmer Vernooij
Put determine_wants methods on InterRepo.
183
            determine_wants = interrepo.determine_wants_all
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
184
        interrepo.fetch_objects(determine_wants=determine_wants,
185
            mapping=source_branch.mapping)
186
        result_branch = source_branch.sprout(result,
187
            revision_id=revision_id, repository=result_repo)
0.200.1372 by Jelmer Vernooij
Fix formatting.
188
        if (create_tree_if_local
189
            and isinstance(target_transport, LocalTransport)
0.259.1 by Jelmer Vernooij
Provide custom GitDir.sprout() for bzr 2.4 compatibility.
190
            and (result_repo is None or result_repo.make_working_trees())):
191
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
192
                hardlink=hardlink, from_branch=result_branch)
193
        return result
194
0.200.1117 by Jelmer Vernooij
Provide basic implementation of GitDir.clone_on_transport.
195
    def clone_on_transport(self, transport, revision_id=None,
196
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
197
        create_prefix=False, use_existing_dir=True, no_tree=False):
198
        """See ControlDir.clone_on_transport."""
0.200.1644 by Jelmer Vernooij
More relative imports.
199
        from ...repository import InterRepository
200
        from .mapping import default_mapping
0.285.3 by Jelmer Vernooij
Fix handling of stacking requests.
201
        if stacked_on is not None:
202
            raise _mod_branch.UnstackableBranchFormat(self._format, self.user_url)
0.200.1119 by Jelmer Vernooij
Refactor repository initialization.
203
        if no_tree:
204
            format = BareLocalGitControlDirFormat()
205
        else:
206
            format = LocalGitControlDirFormat()
0.200.1778 by Jelmer Vernooij
Fix cloning to non-last revision.
207
        (target_repo, target_controldir, stacking,
208
                repo_policy) = format.initialize_on_transport_ex(
209
                        transport, use_existing_dir=use_existing_dir,
210
                        create_prefix=create_prefix,
211
                        force_new_repo=force_new_repo)
0.330.1 by Jelmer Vernooij
Fix initialize_on_transport_ex without repo_format specified.
212
        target_repo = target_controldir.find_repository()
0.200.1119 by Jelmer Vernooij
Refactor repository initialization.
213
        target_git_repo = target_repo._git
0.302.1 by Jelmer Vernooij
Implement .find_repository.
214
        source_repo = self.find_repository()
0.200.1117 by Jelmer Vernooij
Provide basic implementation of GitDir.clone_on_transport.
215
        source_git_repo = source_repo._git
0.200.1171 by Jelmer Vernooij
Fix some more tests.
216
        interrepo = InterRepository.get(source_repo, target_repo)
0.200.1117 by Jelmer Vernooij
Provide basic implementation of GitDir.clone_on_transport.
217
        if revision_id is not None:
0.200.1171 by Jelmer Vernooij
Fix some more tests.
218
            determine_wants = interrepo.get_determine_wants_revids([revision_id], include_tags=True)
0.200.1117 by Jelmer Vernooij
Provide basic implementation of GitDir.clone_on_transport.
219
        else:
0.200.1171 by Jelmer Vernooij
Fix some more tests.
220
            determine_wants = interrepo.determine_wants_all
221
        (pack_hint, _, refs) = interrepo.fetch_objects(determine_wants,
222
            mapping=default_mapping)
7018.3.2 by Jelmer Vernooij
Fix some git tests.
223
        for name, val in viewitems(refs):
0.200.1117 by Jelmer Vernooij
Provide basic implementation of GitDir.clone_on_transport.
224
            target_git_repo.refs[name] = val
0.336.7 by Jelmer Vernooij
Fix remaining tests.
225
        result_dir = self.__class__(transport, target_git_repo, format)
226
        if revision_id is not None:
227
            result_dir.open_branch().set_last_revision(revision_id)
0.428.1 by Jelmer Vernooij
Fix clone_preserves_content test.
228
        try:
229
            # Cheaper to check if the target is not local, than to try making
230
            # the tree and fail.
231
            result_dir.root_transport.local_abspath('.')
232
            if result_dir.open_repository().make_working_trees():
233
                self.open_workingtree().clone(result_dir, revision_id=revision_id)
234
        except (bzr_errors.NoWorkingTree, bzr_errors.NotLocalUrl):
235
            pass
236
0.336.7 by Jelmer Vernooij
Fix remaining tests.
237
        return result_dir
0.200.1117 by Jelmer Vernooij
Provide basic implementation of GitDir.clone_on_transport.
238
0.259.2 by Jelmer Vernooij
Make sure RemoteGitDir.find_repository works.
239
    def find_repository(self):
240
        """Find the repository that should be used.
241
242
        This does not require a branch as we use it to find the repo for
243
        new branches as well as to hook existing branches up to their
244
        repository.
245
        """
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
246
        return self._gitrepository_class(self._find_commondir())
0.259.2 by Jelmer Vernooij
Make sure RemoteGitDir.find_repository works.
247
0.200.1487 by Jelmer Vernooij
Use peeling.
248
    def get_refs_container(self):
249
        """Retrieve the refs container.
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
250
        """
0.200.1487 by Jelmer Vernooij
Use peeling.
251
        raise NotImplementedError(self.get_refs_container)
0.200.1434 by Jelmer Vernooij
Move refs access to control dir.
252
0.200.1701 by Jelmer Vernooij
Fix a few tests.
253
    def determine_repository_policy(self, force_new_repo=False, stack_on=None,
254
                                    stack_on_pwd=None, require_stacking=False):
255
        """Return an object representing a policy to use.
256
257
        This controls whether a new repository is created, and the format of
258
        that repository, or some existing shared repository used instead.
259
260
        If stack_on is supplied, will not seek a containing shared repo.
261
262
        :param force_new_repo: If True, require a new repository to be created.
263
        :param stack_on: If supplied, the location to stack on.  If not
264
            supplied, a default_stack_on location may be used.
265
        :param stack_on_pwd: If stack_on is relative, the location it is
266
            relative to.
267
        """
0.302.1 by Jelmer Vernooij
Implement .find_repository.
268
        return UseExistingRepository(self.find_repository())
0.200.1701 by Jelmer Vernooij
Fix a few tests.
269
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
270
    def get_branches(self):
271
        from .refs import ref_to_branch_name
272
        ret = {}
273
        for ref in self.get_refs_container().keys():
274
            try:
275
                branch_name = ref_to_branch_name(ref)
276
            except ValueError:
277
                continue
278
            except UnicodeDecodeError:
279
                trace.warning("Ignoring branch %r with unicode error ref", ref)
280
                continue
281
            ret[branch_name] = self.open_branch(ref=ref)
282
        return ret
283
284
    def list_branches(self):
285
        return self.get_branches().values()
286
0.419.1 by Jelmer Vernooij
Simplify pushing to Git directories.
287
    def push_branch(self, source, revision_id=None, overwrite=False,
288
                    remember=False, create_prefix=False, lossy=False,
289
                    name=None):
290
        """Push the source branch into this ControlDir."""
291
        push_result = GitPushResult()
292
        push_result.workingtree_updated = None
293
        push_result.master_branch = None
294
        push_result.source_branch = source
295
        push_result.stacked_on = None
296
        repo = self.find_repository()
297
        refname = self._get_selected_ref(name)
298
        from .branch import GitBranch
299
        if isinstance(source, GitBranch) and lossy:
6883.23.22 by Jelmer Vernooij
Fix import.
300
            raise bzr_errors.LossyPushToSameVCS(source.controldir, self)
0.419.1 by Jelmer Vernooij
Simplify pushing to Git directories.
301
        target = self.open_branch(name, nascent_ok=True)
302
        push_result.branch_push_result = source.push(
303
                target, overwrite=overwrite, stop_revision=revision_id,
304
                lossy=lossy)
305
        push_result.new_revid = push_result.branch_push_result.new_revid
306
        push_result.old_revid = push_result.branch_push_result.old_revid
307
        push_result.target_branch = self.open_branch(name)
308
        if source.get_push_location() is None or remember:
309
            source.set_push_location(push_result.target_branch.base)
310
        return push_result
311
0.200.148 by Jelmer Vernooij
Share more infrastructure between LocalGitDir and RemoteGitDir.
312
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
313
class LocalGitControlDirFormat(GitControlDirFormat):
314
    """The .git directory control format."""
315
316
    bare = False
317
318
    @classmethod
319
    def _known_formats(self):
320
        return set([LocalGitControlDirFormat()])
321
322
    @property
323
    def repository_format(self):
0.200.1644 by Jelmer Vernooij
More relative imports.
324
        from .repository import GitRepositoryFormat
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
325
        return GitRepositoryFormat()
326
0.290.3 by Jelmer Vernooij
Set workingtree_format on LocalGitDirFormat.
327
    @property
328
    def workingtree_format(self):
329
        from .workingtree import GitWorkingTreeFormat
330
        return GitWorkingTreeFormat()
331
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
332
    def get_branch_format(self):
0.295.1 by Jelmer Vernooij
Split up branch formats.
333
        from .branch import LocalGitBranchFormat
334
        return LocalGitBranchFormat()
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
335
336
    def open(self, transport, _found=None):
337
        """Open this directory.
338
339
        """
0.200.1644 by Jelmer Vernooij
More relative imports.
340
        from .transportgit import TransportRepo
0.200.1485 by Jelmer Vernooij
Keep track of refs text when opening bare repository.
341
        gitrepo = TransportRepo(transport, self.bare,
342
                refs_text=getattr(self, "_refs_text", None))
0.310.10 by Jelmer Vernooij
Fix format opener fails on empty dir.
343
        if not gitrepo._controltransport.has('HEAD'):
344
            raise bzr_errors.NotBranchError(path=transport.base)
0.200.1411 by Jelmer Vernooij
Fix control files.
345
        return LocalGitDir(transport, gitrepo, self)
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
346
347
    def get_format_description(self):
348
        return "Local Git Repository"
349
350
    def initialize_on_transport(self, transport):
0.200.1644 by Jelmer Vernooij
More relative imports.
351
        from .transportgit import TransportRepo
0.200.1559 by Jelmer Vernooij
Fix compatibility with bzr 2.5.
352
        repo = TransportRepo.init(transport, bare=self.bare)
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
353
        return self.open(transport)
354
355
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
356
        create_prefix=False, force_new_repo=False, stacked_on=None,
357
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
358
        shared_repo=False, vfs_only=False):
359
        def make_directory(transport):
360
            transport.mkdir('.')
361
            return transport
362
        def redirected(transport, e, redirection_notice):
363
            trace.note(redirection_notice)
364
            return transport._redirected_to(e.source, e.target)
365
        try:
366
            transport = do_catching_redirections(make_directory, transport,
367
                redirected)
368
        except bzr_errors.FileExists:
369
            if not use_existing_dir:
370
                raise
371
        except bzr_errors.NoSuchFile:
372
            if not create_prefix:
373
                raise
374
            transport.create_prefix()
375
        controldir = self.initialize_on_transport(transport)
0.330.1 by Jelmer Vernooij
Fix initialize_on_transport_ex without repo_format specified.
376
        if repo_format_name:
377
            result_repo = controldir.find_repository()
378
            repository_policy = UseExistingRepository(result_repo)
379
            result_repo.lock_write()
380
        else:
381
            result_repo = None
382
            repository_policy = None
383
        return (result_repo, controldir, False,
384
                repository_policy)
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
385
386
    def is_supported(self):
387
        return True
388
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
389
    def supports_transport(self, transport):
390
        try:
391
            external_url = transport.external_url()
392
        except bzr_errors.InProcessTransport:
393
            raise bzr_errors.NotBranchError(path=transport.base)
0.332.1 by Jelmer Vernooij
Mark LocalGitControlDir as not supporting http.
394
        return external_url.startswith("file:")
0.200.1412 by Jelmer Vernooij
Implement GitControlDirFormat.supports_transport.
395
0.200.1137 by Jelmer Vernooij
Support BzrProber.known_formats().
396
397
class BareLocalGitControlDirFormat(LocalGitControlDirFormat):
398
399
    bare = True
400
    supports_workingtrees = False
401
402
    def get_format_description(self):
403
        return "Local Git Repository (bare)"
404
405
0.200.148 by Jelmer Vernooij
Share more infrastructure between LocalGitDir and RemoteGitDir.
406
class LocalGitDir(GitDir):
407
    """An adapter to the '.git' dir used by git."""
408
0.239.13 by Jelmer Vernooij
Don't break "bzr info -v" when Dulwich is not installed.
409
    def _get_gitrepository_class(self):
0.200.1644 by Jelmer Vernooij
More relative imports.
410
        from .repository import LocalGitRepository
0.239.13 by Jelmer Vernooij
Don't break "bzr info -v" when Dulwich is not installed.
411
        return LocalGitRepository
412
0.200.1313 by Jelmer Vernooij
Add __repr__
413
    def __repr__(self):
414
        return "<%s at %r>" % (
415
            self.__class__.__name__, self.root_transport.base)
416
0.239.13 by Jelmer Vernooij
Don't break "bzr info -v" when Dulwich is not installed.
417
    _gitrepository_class = property(_get_gitrepository_class)
0.202.2 by David Allouche
GitRepository.get_inventory and .revision_tree work for the null revision. Support for testing GitRepository without disk data.
418
0.200.1014 by Jelmer Vernooij
Fix tests.
419
    @property
420
    def user_transport(self):
421
        return self.root_transport
422
423
    @property
424
    def control_transport(self):
0.398.1 by Jelmer Vernooij
Support reading .git files.
425
        return self._git._controltransport
0.200.1014 by Jelmer Vernooij
Fix tests.
426
0.200.1411 by Jelmer Vernooij
Fix control files.
427
    def __init__(self, transport, gitrepo, format):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
428
        self._format = format
429
        self.root_transport = transport
0.200.1018 by Jelmer Vernooij
Fix use with new control dir API.
430
        self._mode_check_done = False
0.200.90 by Jelmer Vernooij
Basic support for opening working trees.
431
        self._git = gitrepo
432
        if gitrepo.bare:
433
            self.transport = transport
434
        else:
435
            self.transport = transport.clone('.git')
0.200.381 by Jelmer Vernooij
Support working trees properly, status and ls.
436
        self._mode_check_done = None
437
438
    def is_control_filename(self, filename):
0.200.1603 by Jelmer Vernooij
Ignore control directory filenames on Windows, too.
439
        return (filename == '.git' or
440
                filename.startswith('.git/') or
441
                filename.startswith('.git\\'))
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
442
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
443
    def _get_symref(self, ref):
444
        from dulwich.repo import SYMREF
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
445
        ref_chain, unused_sha = self._git.refs.follow(ref)
446
        if len(ref_chain) == 1:
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
447
            return None
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
448
        return ref_chain[1]
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
449
0.200.1773 by Jelmer Vernooij
Fix argument name.
450
    def set_branch_reference(self, target_branch, name=None):
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
451
        ref = self._get_selected_ref(name)
0.311.1 by Jelmer Vernooij
Support git lightweight checkouts.
452
        if self.control_transport.base == target_branch.controldir.control_transport.base:
0.416.1 by Jelmer Vernooij
Raise BranchReferenceLoop.
453
            if ref == target_branch.ref:
454
                raise BranchReferenceLoop(target_branch)
0.311.1 by Jelmer Vernooij
Support git lightweight checkouts.
455
            self._git.refs.set_symbolic_ref(ref, target_branch.ref)
456
        else:
457
            try:
458
                target_path = target_branch.controldir.control_transport.local_abspath('.')
459
            except bzr_errors.NotLocalUrl:
460
                raise bzr_errors.IncompatibleFormat(target_branch._format, self._format)
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
461
            # TODO(jelmer): Do some consistency checking across branches..
0.311.1 by Jelmer Vernooij
Support git lightweight checkouts.
462
            self.control_transport.put_bytes('commondir', target_path.encode('utf-8'))
0.311.3 by Jelmer Vernooij
Fix handling of lightweight checkouts.
463
            # TODO(jelmer): Urgh, avoid mucking about with internals.
464
            self._git._commontransport = target_branch.repository._git._commontransport.clone()
465
            self._git.object_store = TransportObjectStore(self._git._commontransport.clone(OBJECTDIR))
466
            self._git.refs.transport = self._git._commontransport
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
467
            target_ref_chain, unused_sha = target_branch.controldir._git.refs.follow(target_branch.ref)
468
            for target_ref in target_ref_chain:
469
                if target_ref == b'HEAD':
470
                    continue
471
                break
472
            else:
473
                # Can't create a reference to something that is not a in a repository.
474
                raise bzr_errors.IncompatibleFormat(self.set_branch_reference, self)
475
            self._git.refs.set_symbolic_ref(ref, target_ref)
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
476
477
    def get_branch_reference(self, name=None):
478
        ref = self._get_selected_ref(name)
479
        target_ref = self._get_symref(ref)
480
        if target_ref is not None:
0.303.3 by Jelmer Vernooij
Prefer using branch segment parameter in reference branch URLs.
481
            from .refs import ref_to_branch_name
482
            try:
483
                branch_name = ref_to_branch_name(target_ref)
484
            except ValueError:
7018.3.2 by Jelmer Vernooij
Fix some git tests.
485
                params = {'ref': urlutils.quote(target_ref.decode('utf-8'), '')}
0.303.3 by Jelmer Vernooij
Prefer using branch segment parameter in reference branch URLs.
486
            else:
487
                if branch_name != b'':
7018.3.2 by Jelmer Vernooij
Fix some git tests.
488
                    params = {'branch': urlutils.quote(branch_name, '')}
0.303.3 by Jelmer Vernooij
Prefer using branch segment parameter in reference branch URLs.
489
                else:
490
                    params = {}
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
491
            try:
492
                base_url = urlutils.local_path_to_url(self.control_transport.get_bytes('commondir')).rstrip('/.git/')+'/'
493
            except bzr_errors.NoSuchFile:
494
                base_url = self.user_url.rstrip('/')
495
            return urlutils.join_segment_parameters(base_url, params)
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
496
        return None
497
498
    def find_branch_format(self, name=None):
0.200.1644 by Jelmer Vernooij
More relative imports.
499
        from .branch import (
0.295.1 by Jelmer Vernooij
Split up branch formats.
500
            LocalGitBranchFormat,
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
501
            )
502
        ref = self._get_selected_ref(name)
0.321.1 by Jelmer Vernooij
Remove unused GitSymrefBranchFormat.
503
        return LocalGitBranchFormat()
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
504
0.200.978 by Jelmer Vernooij
Allow name argument to get_branch_transport to be missing.
505
    def get_branch_transport(self, branch_format, name=None):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
506
        if branch_format is None:
507
            return self.transport
0.200.1012 by Jelmer Vernooij
Rename BzrDir to ControlDir.
508
        if isinstance(branch_format, LocalGitControlDirFormat):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
509
            return self.transport
0.239.13 by Jelmer Vernooij
Don't break "bzr info -v" when Dulwich is not installed.
510
        raise bzr_errors.IncompatibleFormat(branch_format, self._format)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
511
0.200.887 by Jelmer Vernooij
get_branch_transport takes a name argument.
512
    def get_repository_transport(self, format):
513
        if format is None:
514
            return self.transport
0.200.1012 by Jelmer Vernooij
Rename BzrDir to ControlDir.
515
        if isinstance(format, LocalGitControlDirFormat):
0.200.887 by Jelmer Vernooij
get_branch_transport takes a name argument.
516
            return self.transport
517
        raise bzr_errors.IncompatibleFormat(format, self._format)
518
519
    def get_workingtree_transport(self, format):
520
        if format is None:
521
            return self.transport
0.200.1012 by Jelmer Vernooij
Rename BzrDir to ControlDir.
522
        if isinstance(format, LocalGitControlDirFormat):
0.200.887 by Jelmer Vernooij
get_branch_transport takes a name argument.
523
            return self.transport
524
        raise bzr_errors.IncompatibleFormat(format, self._format)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
525
0.269.8 by Jelmer Vernooij
Support push in git-remote-bzr.
526
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=None,
0.310.9 by Jelmer Vernooij
Some controldir fixes.
527
            ref=None, possible_transports=None, nascent_ok=False):
0.200.57 by Jelmer Vernooij
Fix more tests.
528
        """'create' a branch for this dir."""
0.302.1 by Jelmer Vernooij
Implement .find_repository.
529
        repo = self.find_repository()
0.200.1644 by Jelmer Vernooij
More relative imports.
530
        from .branch import LocalGitBranch
0.269.8 by Jelmer Vernooij
Support push in git-remote-bzr.
531
        ref = self._get_selected_ref(name, ref)
0.310.9 by Jelmer Vernooij
Some controldir fixes.
532
        if not nascent_ok and ref not in self._git.refs:
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
533
            raise bzr_errors.NotBranchError(self.root_transport.base,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
534
                    controldir=self)
0.310.9 by Jelmer Vernooij
Some controldir fixes.
535
        ref_chain, unused_sha = self._git.refs.follow(ref)
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
536
        if ref_chain[-1] == b'HEAD':
537
            controldir = self
538
        else:
539
            controldir = self._find_commondir()
540
        return LocalGitBranch(controldir, repo, ref_chain[-1])
0.200.722 by Jelmer Vernooij
Implement GitDir.list_branches() and support name argument to open_branch.
541
0.200.724 by Jelmer Vernooij
support destroy_branch
542
    def destroy_branch(self, name=None):
0.200.1310 by Jelmer Vernooij
Add _get_selected_ref method.
543
        refname = self._get_selected_ref(name)
0.310.2 by Jelmer Vernooij
Don't allow removing HEAD.
544
        if refname == b'HEAD':
545
            # HEAD can't be removed
546
            raise bzr_errors.UnsupportedOperation(
547
                self.destroy_branch, self)
0.200.1364 by Jelmer Vernooij
Fix .destroy_branch.
548
        try:
549
            del self._git.refs[refname]
550
        except KeyError:
0.200.997 by Jelmer Vernooij
Implement BzrDir.needs_format_conversion.
551
            raise bzr_errors.NotBranchError(self.root_transport.base,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
552
                    controldir=self)
0.200.724 by Jelmer Vernooij
support destroy_branch
553
0.200.980 by Jelmer Vernooij
Implement LocalGitBzrDir.destroy_repository().
554
    def destroy_repository(self):
555
        raise bzr_errors.UnsupportedOperation(self.destroy_repository, self)
556
0.200.986 by Jelmer Vernooij
Implement GitDir.destroy_workingtree.
557
    def destroy_workingtree(self):
0.310.15 by Jelmer Vernooij
Handle destroy_workingtree.
558
        raise bzr_errors.UnsupportedOperation(self.destroy_workingtree, self)
0.200.1566 by Jelmer Vernooij
Basic implementation of LocalGitDir.destroy_workingtree.
559
560
    def destroy_workingtree_metadata(self):
0.310.15 by Jelmer Vernooij
Handle destroy_workingtree.
561
        raise bzr_errors.UnsupportedOperation(self.destroy_workingtree_metadata, self)
0.200.986 by Jelmer Vernooij
Implement GitDir.destroy_workingtree.
562
0.200.997 by Jelmer Vernooij
Implement BzrDir.needs_format_conversion.
563
    def needs_format_conversion(self, format=None):
564
        return not isinstance(self._format, format.__class__)
565
0.200.1114 by Jelmer Vernooij
Properly raise exception when create_repository is called with shared=True
566
    def open_repository(self):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
567
        """'open' a repository for this dir."""
0.302.1 by Jelmer Vernooij
Implement .find_repository.
568
        if self.control_transport.has('commondir'):
569
            raise bzr_errors.NoRepositoryPresent(self)
0.200.1411 by Jelmer Vernooij
Fix control files.
570
        return self._gitrepository_class(self)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
571
0.310.3 by Jelmer Vernooij
Implement ControlDir.has_workingtree.
572
    def has_workingtree(self):
573
        return not self._git.bare
574
0.200.1537 by Jelmer Vernooij
Support unsupported= argument.
575
    def open_workingtree(self, recommend_upgrade=True, unsupported=False):
0.246.5 by Jelmer Vernooij
Cope with has_index not existing.
576
        if not self._git.bare:
577
            from dulwich.errors import NoIndexPresent
0.302.1 by Jelmer Vernooij
Implement .find_repository.
578
            repo = self.find_repository()
0.415.3 by Jelmer Vernooij
Open index on demand.
579
            from .workingtree import GitWorkingTree
580
            branch = self.open_branch(ref=b'HEAD', nascent_ok=True)
581
            return GitWorkingTree(self, repo, branch)
0.200.392 by Jelmer Vernooij
Fix some tests now that working trees are supported.
582
        loc = urlutils.unescape_for_display(self.root_transport.base, 'ascii')
0.239.13 by Jelmer Vernooij
Don't break "bzr info -v" when Dulwich is not installed.
583
        raise bzr_errors.NoWorkingTree(loc)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
584
0.200.108 by Jelmer Vernooij
Support bzr init --git.
585
    def create_repository(self, shared=False):
0.200.1644 by Jelmer Vernooij
More relative imports.
586
        from .repository import GitRepositoryFormat
0.200.1114 by Jelmer Vernooij
Properly raise exception when create_repository is called with shared=True
587
        if shared:
588
            raise bzr_errors.IncompatibleFormat(GitRepositoryFormat(), self._format)
0.302.1 by Jelmer Vernooij
Implement .find_repository.
589
        return self.find_repository()
0.200.288 by Jelmer Vernooij
Add test for init-repo.
590
0.200.1377 by Jelmer Vernooij
Fix get_branch_reference.
591
    def create_branch(self, name=None, repository=None,
0.269.8 by Jelmer Vernooij
Support push in git-remote-bzr.
592
                      append_revisions_only=None, ref=None):
593
        refname = self._get_selected_ref(name, ref)
0.310.1 by Jelmer Vernooij
Support from_branch, don't raise AlreadyBranchError for HEAD.
594
        if refname != b'HEAD' and refname in self._git.refs:
0.200.1559 by Jelmer Vernooij
Fix compatibility with bzr 2.5.
595
            raise bzr_errors.AlreadyBranchError(self.user_url)
0.310.9 by Jelmer Vernooij
Some controldir fixes.
596
        repo = self.open_repository()
597
        if refname in self._git.refs:
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
598
            ref_chain, unused_sha = self._git.refs.follow(self._get_selected_ref(None))
599
            if ref_chain[0] == b'HEAD':
600
                refname = ref_chain[1]
601
        from .branch import LocalGitBranch
602
        branch = LocalGitBranch(self, repo, refname)
0.200.1378 by Jelmer Vernooij
Fix branch.
603
        if append_revisions_only:
0.200.1377 by Jelmer Vernooij
Fix get_branch_reference.
604
            branch.set_append_revisions_only(append_revisions_only)
605
        return branch
0.200.535 by Jelmer Vernooij
use standard version to check for index.
606
607
    def backup_bzrdir(self):
0.200.1549 by Jelmer Vernooij
Support backing up bare repositories.
608
        if not self._git.bare:
0.200.535 by Jelmer Vernooij
use standard version to check for index.
609
            self.root_transport.copy_tree(".git", ".git.backup")
610
            return (self.root_transport.abspath(".git"),
611
                    self.root_transport.abspath(".git.backup"))
612
        else:
0.200.1549 by Jelmer Vernooij
Support backing up bare repositories.
613
            basename = urlutils.basename(self.root_transport.base)
614
            parent = self.root_transport.clone('..')
615
            parent.copy_tree(basename, basename + ".backup")
0.200.535 by Jelmer Vernooij
use standard version to check for index.
616
617
    def create_workingtree(self, revision_id=None, from_branch=None,
618
        accelerator_tree=None, hardlink=False):
619
        if self._git.bare:
0.200.1038 by Jelmer Vernooij
Raise UnsupportedOperation on create_workingtree.
620
            raise bzr_errors.UnsupportedOperation(self.create_workingtree, self)
0.310.1 by Jelmer Vernooij
Support from_branch, don't raise AlreadyBranchError for HEAD.
621
        if from_branch is None:
0.310.9 by Jelmer Vernooij
Some controldir fixes.
622
            from_branch = self.open_branch(nascent_ok=True)
0.288.5 by Jelmer Vernooij
Fix working tree contruction.
623
        if revision_id is None:
0.310.1 by Jelmer Vernooij
Support from_branch, don't raise AlreadyBranchError for HEAD.
624
            revision_id = from_branch.last_revision()
0.302.1 by Jelmer Vernooij
Implement .find_repository.
625
        repo = self.find_repository()
0.302.2 by Jelmer Vernooij
Use from_branch.
626
        from .workingtree import GitWorkingTree
0.415.3 by Jelmer Vernooij
Open index on demand.
627
        wt = GitWorkingTree(self, repo, from_branch)
0.373.1 by Jelmer Vernooij
Fix WorkingTree.reset_state().
628
        wt.set_last_revision(revision_id)
629
        wt._build_checkout_with_index()
0.200.1721 by Jelmer Vernooij
Support passing in last revision.
630
        return wt
0.200.1015 by Jelmer Vernooij
Fix GitControlDir.find_repository().
631
0.200.1114 by Jelmer Vernooij
Properly raise exception when create_repository is called with shared=True
632
    def _find_or_create_repository(self, force_new_repo=None):
633
        return self.create_repository(shared=False)
634
0.200.1018 by Jelmer Vernooij
Fix use with new control dir API.
635
    def _find_creation_modes(self):
636
        """Determine the appropriate modes for files and directories.
637
638
        They're always set to be consistent with the base directory,
639
        assuming that this transport allows setting modes.
640
        """
641
        # TODO: Do we need or want an option (maybe a config setting) to turn
642
        # this off or override it for particular locations? -- mbp 20080512
643
        if self._mode_check_done:
644
            return
645
        self._mode_check_done = True
646
        try:
647
            st = self.transport.stat('.')
0.200.1116 by Jelmer Vernooij
Fix missing import.
648
        except bzr_errors.TransportNotPossible:
0.200.1018 by Jelmer Vernooij
Fix use with new control dir API.
649
            self._dir_mode = None
650
            self._file_mode = None
651
        else:
652
            # Check the directory mode, but also make sure the created
653
            # directories and files are read-write for this user. This is
654
            # mostly a workaround for filesystems which lie about being able to
655
            # write to a directory (cygwin & win32)
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
656
            if (st.st_mode & 0o7777 == 0o0000):
0.200.1018 by Jelmer Vernooij
Fix use with new control dir API.
657
                # FTP allows stat but does not return dir/file modes
658
                self._dir_mode = None
659
                self._file_mode = None
660
            else:
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
661
                self._dir_mode = (st.st_mode & 0o7777) | 0o0700
0.200.1018 by Jelmer Vernooij
Fix use with new control dir API.
662
                # Remove the sticky and execute bits for files
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
663
                self._file_mode = self._dir_mode & ~0o7111
0.200.1018 by Jelmer Vernooij
Fix use with new control dir API.
664
665
    def _get_file_mode(self):
666
        """Return Unix mode for newly created files, or None.
667
        """
668
        if not self._mode_check_done:
669
            self._find_creation_modes()
670
        return self._file_mode
671
672
    def _get_dir_mode(self):
673
        """Return Unix mode for newly created directories, or None.
674
        """
675
        if not self._mode_check_done:
676
            self._find_creation_modes()
677
        return self._dir_mode
678
0.200.1487 by Jelmer Vernooij
Use peeling.
679
    def get_refs_container(self):
680
        return self._git.refs
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
681
682
    def get_peeled(self, ref):
683
        return self._git.get_peeled(ref)
0.409.1 by Jelmer Vernooij
Don't probe for commondir over remote transport.
684
685
    def _find_commondir(self):
686
        try:
687
            commondir = self.control_transport.get_bytes('commondir')
688
        except bzr_errors.NoSuchFile:
689
            return self
690
        else:
6973.6.2 by Jelmer Vernooij
Fix more tests.
691
            commondir = commondir.rstrip(b'/.git/')
0.409.1 by Jelmer Vernooij
Don't probe for commondir over remote transport.
692
            return ControlDir.open_from_transport(get_transport_from_path(commondir))