/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 dir.py

More work on roundtrip push support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
"""An adapter between a Git control dir and a Bazaar ControlDir."""
19
19
 
20
 
import urllib
21
 
 
22
20
from bzrlib import (
23
21
    errors as bzr_errors,
24
22
    lockable_files,
25
 
    trace,
26
 
    osutils,
27
23
    urlutils,
 
24
    version_info as bzrlib_version,
28
25
    )
29
 
from bzrlib.bzrdir import CreateRepository
30
 
from bzrlib.transport import do_catching_redirections
31
26
 
32
27
LockWarner = getattr(lockable_files, "_LockWarner", None)
33
28
 
34
 
from bzrlib.controldir import (
35
 
    ControlDir,
36
 
    ControlDirFormat,
37
 
    format_registry,
 
29
from bzrlib.plugins.git import (
 
30
    BareLocalGitControlDirFormat,
 
31
    LocalGitControlDirFormat,
38
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
39
45
 
40
46
 
41
47
class GitLock(object):
42
48
    """A lock that thunks through to Git."""
43
49
 
44
 
    def __init__(self):
45
 
        self.lock_name = "git lock"
46
 
 
47
50
    def lock_write(self, token=None):
48
51
        pass
49
52
 
60
63
        pass
61
64
 
62
65
    def break_lock(self):
63
 
        raise NotImplementedError(self.break_lock)
64
 
 
65
 
    def dont_leave_in_place(self):
66
 
        raise NotImplementedError(self.dont_leave_in_place)
67
 
 
68
 
    def leave_in_place(self):
69
 
        raise NotImplementedError(self.leave_in_place)
 
66
        pass
70
67
 
71
68
 
72
69
class GitLockableFiles(lockable_files.LockableFiles):
93
90
        raise bzr_errors.BzrError("Cannot set configuration")
94
91
 
95
92
 
96
 
class GitControlDirFormat(ControlDirFormat):
97
 
 
98
 
    _lock_class = lockable_files.TransportLock
99
 
 
100
 
    colocated_branches = True
101
 
    fixed_components = True
102
 
 
103
 
    def __eq__(self, other):
104
 
        return type(self) == type(other)
105
 
 
106
 
    def is_supported(self):
107
 
        return True
108
 
 
109
 
    def network_name(self):
110
 
        return "git"
111
 
 
112
 
 
113
93
class GitDir(ControlDir):
114
94
    """An adapter to the '.git' dir used by git."""
115
95
 
125
105
    def cloning_metadir(self, stacked=False):
126
106
        return format_registry.make_bzrdir("default")
127
107
 
128
 
    def checkout_metadir(self, stacked=False):
129
 
        return format_registry.make_bzrdir("default")
 
108
    def _branch_name_to_ref(self, name):
 
109
        raise NotImplementedError(self._branch_name_to_ref)
130
110
 
131
 
    def _get_selected_ref(self, branch):
132
 
        if branch is None and getattr(self, "_get_selected_branch", False):
133
 
            branch = self._get_selected_branch()
134
 
        if branch is not None:
135
 
            from bzrlib.plugins.git.refs import branch_name_to_ref
136
 
            return branch_name_to_ref(branch, None)
137
 
        segment_parameters = getattr(
138
 
            self.user_transport, "get_segment_parameters", lambda: {})()
139
 
        ref = segment_parameters.get("ref")
140
 
        if ref is not None:
141
 
            ref = urlutils.unescape(ref)
142
 
        return ref
 
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)
143
120
 
144
121
    def get_config(self):
145
122
        return GitDirConfig()
146
123
 
147
 
    def _available_backup_name(self, base):
148
 
        return osutils.available_backup_name(base, self.root_transport.has)
149
 
 
150
 
    def sprout(self, url, revision_id=None, force_new_repo=False,
151
 
               recurse='down', possible_transports=None,
152
 
               accelerator_tree=None, hardlink=False, stacked=False,
153
 
               source_branch=None, create_tree_if_local=True):
154
 
        from bzrlib.repository import InterRepository
155
 
        from bzrlib.transport.local import LocalTransport
156
 
        from bzrlib.transport import get_transport
157
 
        target_transport = get_transport(url, possible_transports)
158
 
        target_transport.ensure_base()
159
 
        cloning_format = self.cloning_metadir()
160
 
        # Create/update the result branch
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 bzr_errors.NoRepositoryPresent:
167
 
            result_repo = result.create_repository()
168
 
            target_is_empty = True
169
 
        else:
170
 
            target_is_empty = None # Unknown
171
 
        if stacked:
172
 
            raise bzr_errors.IncompatibleRepositories(source_repository, result_repo)
173
 
        interrepo = InterRepository.get(source_repository, result_repo)
174
 
 
175
 
        if revision_id is not None:
176
 
            determine_wants = interrepo.get_determine_wants_revids(
177
 
                [revision_id], include_tags=True)
178
 
        else:
179
 
            determine_wants = interrepo.determine_wants_all
180
 
        interrepo.fetch_objects(determine_wants=determine_wants,
181
 
            mapping=source_branch.mapping)
182
 
        result_branch = source_branch.sprout(result,
183
 
            revision_id=revision_id, repository=result_repo)
184
 
        if (create_tree_if_local and isinstance(target_transport, LocalTransport)
185
 
            and (result_repo is None or result_repo.make_working_trees())):
186
 
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
187
 
                hardlink=hardlink, from_branch=result_branch)
188
 
            wt.lock_write()
189
 
            try:
190
 
                if wt.path2id('') is None:
191
 
                    try:
192
 
                        wt.set_root_id(self.open_workingtree.get_root_id())
193
 
                    except bzr_errors.NoWorkingTree:
194
 
                        pass
195
 
            finally:
196
 
                wt.unlock()
197
 
        return result
198
 
 
199
 
    def clone_on_transport(self, transport, revision_id=None,
200
 
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
201
 
        create_prefix=False, use_existing_dir=True, no_tree=False):
202
 
        """See ControlDir.clone_on_transport."""
203
 
        from bzrlib.repository import InterRepository
204
 
        from bzrlib.plugins.git.mapping import default_mapping
205
 
        if no_tree:
206
 
            format = BareLocalGitControlDirFormat()
207
 
        else:
208
 
            format = LocalGitControlDirFormat()
209
 
        (target_repo, target_controldir, stacking, repo_policy) = format.initialize_on_transport_ex(transport, use_existing_dir=use_existing_dir, create_prefix=create_prefix, force_new_repo=force_new_repo)
210
 
        target_git_repo = target_repo._git
211
 
        source_repo = self.open_repository()
212
 
        source_git_repo = source_repo._git
213
 
        interrepo = InterRepository.get(source_repo, target_repo)
214
 
        if revision_id is not None:
215
 
            determine_wants = interrepo.get_determine_wants_revids([revision_id], include_tags=True)
216
 
        else:
217
 
            determine_wants = interrepo.determine_wants_all
218
 
        (pack_hint, _, refs) = interrepo.fetch_objects(determine_wants,
219
 
            mapping=default_mapping)
220
 
        for name, val in refs.iteritems():
221
 
            target_git_repo.refs[name] = val
222
 
        lockfiles = GitLockableFiles(transport, GitLock())
223
 
        return self.__class__(transport, lockfiles, target_git_repo, format)
224
 
 
225
 
    def find_repository(self):
226
 
        """Find the repository that should be used.
227
 
 
228
 
        This does not require a branch as we use it to find the repo for
229
 
        new branches as well as to hook existing branches up to their
230
 
        repository.
231
 
        """
232
 
        return self.open_repository()
233
 
 
234
 
 
235
 
class LocalGitControlDirFormat(GitControlDirFormat):
236
 
    """The .git directory control format."""
237
 
 
238
 
    bare = False
239
 
 
240
 
    @classmethod
241
 
    def _known_formats(self):
242
 
        return set([LocalGitControlDirFormat()])
243
 
 
244
 
    @property
245
 
    def repository_format(self):
246
 
        from bzrlib.plugins.git.repository import GitRepositoryFormat
247
 
        return GitRepositoryFormat()
248
 
 
249
 
    def get_branch_format(self):
250
 
        from bzrlib.plugins.git.branch import GitBranchFormat
251
 
        return GitBranchFormat()
252
 
 
253
 
    def open(self, transport, _found=None):
254
 
        """Open this directory.
255
 
 
256
 
        """
257
 
        from bzrlib.plugins.git.transportgit import TransportRepo
258
 
        gitrepo = TransportRepo(transport)
259
 
        lockfiles = GitLockableFiles(transport, GitLock())
260
 
        return LocalGitDir(transport, lockfiles, gitrepo, self)
261
 
 
262
 
    def get_format_description(self):
263
 
        return "Local Git Repository"
264
 
 
265
 
    def initialize_on_transport(self, transport):
266
 
        from bzrlib.plugins.git.transportgit import TransportRepo
267
 
        TransportRepo.init(transport, bare=self.bare)
268
 
        return self.open(transport)
269
 
 
270
 
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
271
 
        create_prefix=False, force_new_repo=False, stacked_on=None,
272
 
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
273
 
        shared_repo=False, vfs_only=False):
274
 
        def make_directory(transport):
275
 
            transport.mkdir('.')
276
 
            return transport
277
 
        def redirected(transport, e, redirection_notice):
278
 
            trace.note(redirection_notice)
279
 
            return transport._redirected_to(e.source, e.target)
280
 
        try:
281
 
            transport = do_catching_redirections(make_directory, transport,
282
 
                redirected)
283
 
        except bzr_errors.FileExists:
284
 
            if not use_existing_dir:
285
 
                raise
286
 
        except bzr_errors.NoSuchFile:
287
 
            if not create_prefix:
288
 
                raise
289
 
            transport.create_prefix()
290
 
        controldir = self.initialize_on_transport(transport)
291
 
        repository = controldir.open_repository()
292
 
        repository.lock_write()
293
 
        return (repository, controldir, False, CreateRepository(controldir))
294
 
 
295
 
    def is_supported(self):
296
 
        return True
297
 
 
298
 
 
299
 
class BareLocalGitControlDirFormat(LocalGitControlDirFormat):
300
 
 
301
 
    bare = True
302
 
    supports_workingtrees = False
303
 
 
304
 
    def get_format_description(self):
305
 
        return "Local Git Repository (bare)"
306
 
 
307
124
 
308
125
class LocalGitDir(GitDir):
309
126
    """An adapter to the '.git' dir used by git."""
312
129
        from bzrlib.plugins.git.repository import LocalGitRepository
313
130
        return LocalGitRepository
314
131
 
315
 
    def __repr__(self):
316
 
        return "<%s at %r>" % (
317
 
            self.__class__.__name__, self.root_transport.base)
318
 
 
319
132
    _gitrepository_class = property(_get_gitrepository_class)
320
133
 
321
134
    @property
338
151
        self._lockfiles = lockfiles
339
152
        self._mode_check_done = None
340
153
 
 
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
 
341
164
    def is_control_filename(self, filename):
342
 
        return (filename == '.git' or filename.startswith('.git/'))
343
 
 
344
 
    def _get_symref(self, ref):
345
 
        from dulwich.repo import SYMREF
346
 
        refcontents = self._git.refs.read_ref(ref)
347
 
        if refcontents is None: # no such ref
348
 
            return None
349
 
        if refcontents.startswith(SYMREF):
350
 
            return refcontents[len(SYMREF):].rstrip("\n")
351
 
        return None
352
 
 
353
 
    def set_branch_reference(self, name, target):
354
 
        ref = self._get_selected_ref(name)
355
 
        if ref is None:
356
 
            ref = "HEAD"
357
 
        if not getattr(target, "ref", None):
358
 
            raise bzr_errors.BzrError("Can only set symrefs to Git refs")
359
 
        self._git.refs.set_symbolic_ref(ref, target.ref)
360
 
 
361
 
    def get_branch_reference(self, name=None):
362
 
        ref = self._get_selected_ref(name)
363
 
        if ref is None:
364
 
            ref = "HEAD"
365
 
        target_ref = self._get_symref(ref)
366
 
        if target_ref is not None:
367
 
            return ",ref=%s" % urllib.quote(target_ref)
368
 
        return None
369
 
 
370
 
    def find_branch_format(self, name=None):
371
 
        from bzrlib.plugins.git.branch import (
372
 
            GitBranchFormat,
373
 
            GitSymrefBranchFormat,
374
 
            )
375
 
        ref = self._get_selected_ref(name)
376
 
        if ref is None:
377
 
            ref = "HEAD"
378
 
        if self._get_symref(ref) is not None:
379
 
            return GitSymrefBranchFormat()
380
 
        else:
381
 
            return GitBranchFormat()
 
165
        return filename == '.git' or filename.startswith('.git/')
382
166
 
383
167
    def get_branch_transport(self, branch_format, name=None):
384
168
        if branch_format is None:
401
185
            return self.transport
402
186
        raise bzr_errors.IncompatibleFormat(format, self._format)
403
187
 
404
 
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=None):
 
188
    def _open_branch(self, name=None, ignore_fallbacks=None, unsupported=False):
405
189
        """'create' a branch for this dir."""
406
190
        repo = self.open_repository()
407
191
        from bzrlib.plugins.git.branch import LocalGitBranch
408
 
        ref = self._get_selected_ref(name)
409
 
        if ref is None:
410
 
            ref = "HEAD"
411
 
        ref, sha = self._git.refs._follow(ref)
412
 
        if not ref in self._git.refs:
413
 
            raise bzr_errors.NotBranchError(self.root_transport.base,
414
 
                    bzrdir=self)
415
 
        return LocalGitBranch(self, repo, ref, self._lockfiles)
 
192
        return LocalGitBranch(self, repo, self._branch_name_to_ref(name),
 
193
            self._lockfiles)
416
194
 
417
195
    def destroy_branch(self, name=None):
418
 
        refname = self._get_selected_ref(name)
 
196
        refname = self._branch_name_to_ref(name)
419
197
        if not refname in self._git.refs:
420
198
            raise bzr_errors.NotBranchError(self.root_transport.base,
421
199
                    bzrdir=self)
432
210
 
433
211
    def list_branches(self):
434
212
        ret = []
435
 
        for name in self._git.refs.keys():
 
213
        for name in self._git.get_refs():
436
214
            if name.startswith("refs/heads/"):
437
215
                ret.append(self.open_branch(name=name))
438
216
        return ret
439
217
 
440
 
    def open_repository(self):
 
218
    def open_repository(self, shared=False):
441
219
        """'open' a repository for this dir."""
442
220
        return self._gitrepository_class(self, self._lockfiles)
443
221
 
461
239
        raise bzr_errors.NoWorkingTree(loc)
462
240
 
463
241
    def create_repository(self, shared=False):
464
 
        from bzrlib.plugins.git.repository import GitRepositoryFormat
465
 
        if shared:
466
 
            raise bzr_errors.IncompatibleFormat(GitRepositoryFormat(), self._format)
467
242
        return self.open_repository()
468
243
 
469
 
    def create_branch(self, name=None, repository=None):
470
 
        refname = self._get_selected_ref(name)
 
244
    def create_branch(self, name=None):
 
245
        refname = self._branch_name_to_ref(name)
471
246
        from dulwich.protocol import ZERO_SHA
472
 
        # FIXME: This is a bit awkward. Perhaps we should have a
473
 
        # a separate method for changing the default branch?
474
 
        if refname is None:
475
 
            refname = "refs/heads/master"
476
 
            self._git.refs.set_symbolic_ref("HEAD", refname)
477
 
        self._git.refs[refname] = ZERO_SHA
 
247
        self._git.refs[refname or "HEAD"] = ZERO_SHA
478
248
        return self.open_branch(name)
479
249
 
480
250
    def backup_bzrdir(self):
488
258
    def create_workingtree(self, revision_id=None, from_branch=None,
489
259
        accelerator_tree=None, hardlink=False):
490
260
        if self._git.bare:
491
 
            raise bzr_errors.UnsupportedOperation(self.create_workingtree, self)
 
261
            raise bzr_errors.BzrError("Can't create working tree in a bare repo")
492
262
        from dulwich.index import write_index
493
263
        from dulwich.pack import SHA1Writer
494
264
        f = open(self.transport.local_abspath("index"), 'w+')
499
269
            f.close()
500
270
        return self.open_workingtree()
501
271
 
502
 
    def _find_or_create_repository(self, force_new_repo=None):
503
 
        return self.create_repository(shared=False)
 
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()
504
280
 
505
281
    def _find_creation_modes(self):
506
282
        """Determine the appropriate modes for files and directories.
515
291
        self._mode_check_done = True
516
292
        try:
517
293
            st = self.transport.stat('.')
518
 
        except bzr_errors.TransportNotPossible:
 
294
        except TransportNotPossible:
519
295
            self._dir_mode = None
520
296
            self._file_mode = None
521
297
        else:
546
322
            self._find_creation_modes()
547
323
        return self._dir_mode
548
324
 
 
325