/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

Import gettext.

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