/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

ImproveĀ errorĀ message.

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
 
    lockable_files,
 
24
    trace,
 
25
    osutils,
23
26
    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))
 
27
    )
 
28
from bzrlib.bzrdir import CreateRepository
 
29
from bzrlib.transport import do_catching_redirections
 
30
 
 
31
from bzrlib.controldir import (
 
32
    ControlDir,
 
33
    ControlDirFormat,
 
34
    format_registry,
 
35
    )
82
36
 
83
37
 
84
38
class GitDirConfig(object):
90
44
        raise bzr_errors.BzrError("Cannot set configuration")
91
45
 
92
46
 
 
47
class GitControlDirFormat(ControlDirFormat):
 
48
 
 
49
    colocated_branches = True
 
50
    fixed_components = True
 
51
 
 
52
    def __eq__(self, other):
 
53
        return type(self) == type(other)
 
54
 
 
55
    def is_supported(self):
 
56
        return True
 
57
 
 
58
    def network_name(self):
 
59
        return "git"
 
60
 
 
61
 
93
62
class GitDir(ControlDir):
94
63
    """An adapter to the '.git' dir used by git."""
95
64
 
105
74
    def cloning_metadir(self, stacked=False):
106
75
        return format_registry.make_bzrdir("default")
107
76
 
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)
 
77
    def checkout_metadir(self, stacked=False):
 
78
        return format_registry.make_bzrdir("default")
 
79
 
 
80
    def _get_default_ref(self):
 
81
        return "HEAD"
 
82
 
 
83
    def _get_selected_ref(self, branch, ref=None):
 
84
        if ref is not None and branch is not None:
 
85
            raise bzr_errors.BzrError("can't specify both ref and branch")
 
86
        if ref is not None:
 
87
            return ref
 
88
        segment_parameters = getattr(
 
89
            self.user_transport, "get_segment_parameters", lambda: {})()
 
90
        ref = segment_parameters.get("ref")
 
91
        if ref is not None:
 
92
            return urlutils.unescape(ref)
 
93
        if branch is None and getattr(self, "_get_selected_branch", False):
 
94
            branch = self._get_selected_branch()
 
95
        if branch is not None:
 
96
            from bzrlib.plugins.git.refs import branch_name_to_ref
 
97
            return branch_name_to_ref(branch)
 
98
        return self._get_default_ref()
120
99
 
121
100
    def get_config(self):
122
101
        return GitDirConfig()
123
102
 
 
103
    def _available_backup_name(self, base):
 
104
        return osutils.available_backup_name(base, self.root_transport.has)
 
105
 
 
106
    def sprout(self, url, revision_id=None, force_new_repo=False,
 
107
               recurse='down', possible_transports=None,
 
108
               accelerator_tree=None, hardlink=False, stacked=False,
 
109
               source_branch=None, create_tree_if_local=True):
 
110
        from bzrlib.repository import InterRepository
 
111
        from bzrlib.transport.local import LocalTransport
 
112
        from bzrlib.transport import get_transport
 
113
        target_transport = get_transport(url, possible_transports)
 
114
        target_transport.ensure_base()
 
115
        cloning_format = self.cloning_metadir()
 
116
        # Create/update the result branch
 
117
        result = cloning_format.initialize_on_transport(target_transport)
 
118
        source_branch = self.open_branch()
 
119
        source_repository = self.find_repository()
 
120
        try:
 
121
            result_repo = result.find_repository()
 
122
        except bzr_errors.NoRepositoryPresent:
 
123
            result_repo = result.create_repository()
 
124
            target_is_empty = True
 
125
        else:
 
126
            target_is_empty = None # Unknown
 
127
        if stacked:
 
128
            raise bzr_errors.IncompatibleRepositories(source_repository, result_repo)
 
129
        interrepo = InterRepository.get(source_repository, result_repo)
 
130
 
 
131
        if revision_id is not None:
 
132
            determine_wants = interrepo.get_determine_wants_revids(
 
133
                [revision_id], include_tags=False)
 
134
        else:
 
135
            determine_wants = interrepo.determine_wants_all
 
136
        interrepo.fetch_objects(determine_wants=determine_wants,
 
137
            mapping=source_branch.mapping)
 
138
        result_branch = source_branch.sprout(result,
 
139
            revision_id=revision_id, repository=result_repo)
 
140
        if (create_tree_if_local
 
141
            and isinstance(target_transport, LocalTransport)
 
142
            and (result_repo is None or result_repo.make_working_trees())):
 
143
            wt = result.create_workingtree(accelerator_tree=accelerator_tree,
 
144
                hardlink=hardlink, from_branch=result_branch)
 
145
            wt.lock_write()
 
146
            try:
 
147
                if wt.path2id('') is None:
 
148
                    try:
 
149
                        wt.set_root_id(self.open_workingtree.get_root_id())
 
150
                    except bzr_errors.NoWorkingTree:
 
151
                        pass
 
152
            finally:
 
153
                wt.unlock()
 
154
        return result
 
155
 
 
156
    def clone_on_transport(self, transport, revision_id=None,
 
157
        force_new_repo=False, preserve_stacking=False, stacked_on=None,
 
158
        create_prefix=False, use_existing_dir=True, no_tree=False):
 
159
        """See ControlDir.clone_on_transport."""
 
160
        from bzrlib.repository import InterRepository
 
161
        from bzrlib.plugins.git.mapping import default_mapping
 
162
        if no_tree:
 
163
            format = BareLocalGitControlDirFormat()
 
164
        else:
 
165
            format = LocalGitControlDirFormat()
 
166
        (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)
 
167
        target_git_repo = target_repo._git
 
168
        source_repo = self.open_repository()
 
169
        source_git_repo = source_repo._git
 
170
        interrepo = InterRepository.get(source_repo, target_repo)
 
171
        if revision_id is not None:
 
172
            determine_wants = interrepo.get_determine_wants_revids([revision_id], include_tags=True)
 
173
        else:
 
174
            determine_wants = interrepo.determine_wants_all
 
175
        (pack_hint, _, refs) = interrepo.fetch_objects(determine_wants,
 
176
            mapping=default_mapping)
 
177
        for name, val in refs.iteritems():
 
178
            target_git_repo.refs[name] = val
 
179
        return self.__class__(transport, target_git_repo, format)
 
180
 
 
181
    def find_repository(self):
 
182
        """Find the repository that should be used.
 
183
 
 
184
        This does not require a branch as we use it to find the repo for
 
185
        new branches as well as to hook existing branches up to their
 
186
        repository.
 
187
        """
 
188
        return self.open_repository()
 
189
 
 
190
    def get_refs_container(self):
 
191
        """Retrieve the refs container.
 
192
        """
 
193
        raise NotImplementedError(self.get_refs_container)
 
194
 
 
195
 
 
196
class LocalGitControlDirFormat(GitControlDirFormat):
 
197
    """The .git directory control format."""
 
198
 
 
199
    bare = False
 
200
 
 
201
    @classmethod
 
202
    def _known_formats(self):
 
203
        return set([LocalGitControlDirFormat()])
 
204
 
 
205
    @property
 
206
    def repository_format(self):
 
207
        from bzrlib.plugins.git.repository import GitRepositoryFormat
 
208
        return GitRepositoryFormat()
 
209
 
 
210
    def get_branch_format(self):
 
211
        from bzrlib.plugins.git.branch import GitBranchFormat
 
212
        return GitBranchFormat()
 
213
 
 
214
    def open(self, transport, _found=None):
 
215
        """Open this directory.
 
216
 
 
217
        """
 
218
        from bzrlib.plugins.git.transportgit import TransportRepo
 
219
        gitrepo = TransportRepo(transport, self.bare,
 
220
                refs_text=getattr(self, "_refs_text", None))
 
221
        return LocalGitDir(transport, gitrepo, self)
 
222
 
 
223
    def get_format_description(self):
 
224
        return "Local Git Repository"
 
225
 
 
226
    def initialize_on_transport(self, transport):
 
227
        from bzrlib.plugins.git.transportgit import TransportRepo
 
228
        repo = TransportRepo.init(transport, bare=self.bare)
 
229
        del repo.refs["HEAD"]
 
230
        return self.open(transport)
 
231
 
 
232
    def initialize_on_transport_ex(self, transport, use_existing_dir=False,
 
233
        create_prefix=False, force_new_repo=False, stacked_on=None,
 
234
        stack_on_pwd=None, repo_format_name=None, make_working_trees=None,
 
235
        shared_repo=False, vfs_only=False):
 
236
        def make_directory(transport):
 
237
            transport.mkdir('.')
 
238
            return transport
 
239
        def redirected(transport, e, redirection_notice):
 
240
            trace.note(redirection_notice)
 
241
            return transport._redirected_to(e.source, e.target)
 
242
        try:
 
243
            transport = do_catching_redirections(make_directory, transport,
 
244
                redirected)
 
245
        except bzr_errors.FileExists:
 
246
            if not use_existing_dir:
 
247
                raise
 
248
        except bzr_errors.NoSuchFile:
 
249
            if not create_prefix:
 
250
                raise
 
251
            transport.create_prefix()
 
252
        controldir = self.initialize_on_transport(transport)
 
253
        repository = controldir.open_repository()
 
254
        repository.lock_write()
 
255
        return (repository, controldir, False, CreateRepository(controldir))
 
256
 
 
257
    def is_supported(self):
 
258
        return True
 
259
 
 
260
    def supports_transport(self, transport):
 
261
        try:
 
262
            external_url = transport.external_url()
 
263
        except bzr_errors.InProcessTransport:
 
264
            raise bzr_errors.NotBranchError(path=transport.base)
 
265
        return (external_url.startswith("http:") or
 
266
                external_url.startswith("https:") or
 
267
                external_url.startswith("file:"))
 
268
 
 
269
 
 
270
class BareLocalGitControlDirFormat(LocalGitControlDirFormat):
 
271
 
 
272
    bare = True
 
273
    supports_workingtrees = False
 
274
 
 
275
    def get_format_description(self):
 
276
        return "Local Git Repository (bare)"
 
277
 
124
278
 
125
279
class LocalGitDir(GitDir):
126
280
    """An adapter to the '.git' dir used by git."""
129
283
        from bzrlib.plugins.git.repository import LocalGitRepository
130
284
        return LocalGitRepository
131
285
 
 
286
    def __repr__(self):
 
287
        return "<%s at %r>" % (
 
288
            self.__class__.__name__, self.root_transport.base)
 
289
 
132
290
    _gitrepository_class = property(_get_gitrepository_class)
133
291
 
134
292
    @property
139
297
    def control_transport(self):
140
298
        return self.transport
141
299
 
142
 
    def __init__(self, transport, lockfiles, gitrepo, format):
 
300
    def __init__(self, transport, gitrepo, format):
143
301
        self._format = format
144
302
        self.root_transport = transport
145
303
        self._mode_check_done = False
148
306
            self.transport = transport
149
307
        else:
150
308
            self.transport = transport.clone('.git')
151
 
        self._lockfiles = lockfiles
152
309
        self._mode_check_done = None
153
310
 
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
311
    def is_control_filename(self, filename):
165
 
        return filename == '.git' or filename.startswith('.git/')
 
312
        return (filename == '.git' or filename.startswith('.git/'))
 
313
 
 
314
    def _get_symref(self, ref):
 
315
        from dulwich.repo import SYMREF
 
316
        refcontents = self._git.refs.read_ref(ref)
 
317
        if refcontents is None: # no such ref
 
318
            return None
 
319
        if refcontents.startswith(SYMREF):
 
320
            return refcontents[len(SYMREF):].rstrip("\n")
 
321
        return None
 
322
 
 
323
    def set_branch_reference(self, target, name=None):
 
324
        if self.control_transport.base != target.bzrdir.control_transport.base:
 
325
            raise bzr_errors.IncompatibleFormat(target._format, self._format)
 
326
        ref = self._get_selected_ref(name)
 
327
        self._git.refs.set_symbolic_ref(ref, target.ref)
 
328
 
 
329
    def get_branch_reference(self, name=None):
 
330
        ref = self._get_selected_ref(name)
 
331
        target_ref = self._get_symref(ref)
 
332
        if target_ref is not None:
 
333
            return urlutils.join_segment_parameters(
 
334
                self.user_url.rstrip("/"), {"ref": urllib.quote(target_ref, '')})
 
335
        return None
 
336
 
 
337
    def find_branch_format(self, name=None):
 
338
        from bzrlib.plugins.git.branch import (
 
339
            GitBranchFormat,
 
340
            GitSymrefBranchFormat,
 
341
            )
 
342
        ref = self._get_selected_ref(name)
 
343
        if self._get_symref(ref) is not None:
 
344
            return GitSymrefBranchFormat()
 
345
        else:
 
346
            return GitBranchFormat()
166
347
 
167
348
    def get_branch_transport(self, branch_format, name=None):
168
349
        if branch_format is None:
185
366
            return self.transport
186
367
        raise bzr_errors.IncompatibleFormat(format, self._format)
187
368
 
188
 
    def _open_branch(self, name=None, ignore_fallbacks=None, unsupported=False):
 
369
    def open_branch(self, name=None, unsupported=False, ignore_fallbacks=None,
 
370
            ref=None, possible_transports=None):
189
371
        """'create' a branch for this dir."""
190
372
        repo = self.open_repository()
191
373
        from bzrlib.plugins.git.branch import LocalGitBranch
192
 
        return LocalGitBranch(self, repo, self._branch_name_to_ref(name),
193
 
            self._lockfiles)
 
374
        ref = self._get_selected_ref(name, ref)
 
375
        ref, sha = self._git.refs._follow(ref)
 
376
        if not ref in self._git.refs:
 
377
            raise bzr_errors.NotBranchError(self.root_transport.base,
 
378
                    bzrdir=self)
 
379
        return LocalGitBranch(self, repo, ref)
194
380
 
195
381
    def destroy_branch(self, name=None):
196
 
        refname = self._branch_name_to_ref(name)
197
 
        if not refname in self._git.refs:
 
382
        refname = self._get_selected_ref(name)
 
383
        try:
 
384
            del self._git.refs[refname]
 
385
        except KeyError:
198
386
            raise bzr_errors.NotBranchError(self.root_transport.base,
199
387
                    bzrdir=self)
200
 
        del self._git.refs[refname]
201
388
 
202
389
    def destroy_repository(self):
203
390
        raise bzr_errors.UnsupportedOperation(self.destroy_repository, self)
209
396
        return not isinstance(self._format, format.__class__)
210
397
 
211
398
    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))
 
399
        return self.get_branches().values()
 
400
 
 
401
    def get_branches(self):
 
402
        from bzrlib.plugins.git.refs import ref_to_branch_name
 
403
        ret = {}
 
404
        for ref in self._git.refs.keys():
 
405
            try:
 
406
                branch_name = ref_to_branch_name(ref)
 
407
            except ValueError:
 
408
                continue
 
409
            except UnicodeDecodeError:
 
410
                trace.warning("Ignoring branch %r with unicode error ref", ref)
 
411
                continue
 
412
            ret[branch_name] = self.open_branch(ref=ref)
216
413
        return ret
217
414
 
218
 
    def open_repository(self, shared=False):
 
415
    def open_repository(self):
219
416
        """'open' a repository for this dir."""
220
 
        return self._gitrepository_class(self, self._lockfiles)
 
417
        return self._gitrepository_class(self)
221
418
 
222
 
    def open_workingtree(self, recommend_upgrade=True):
 
419
    def open_workingtree(self, recommend_upgrade=True, unsupported=False):
223
420
        if not self._git.bare:
224
421
            from dulwich.errors import NoIndexPresent
225
422
            repo = self.open_repository()
239
436
        raise bzr_errors.NoWorkingTree(loc)
240
437
 
241
438
    def create_repository(self, shared=False):
 
439
        from bzrlib.plugins.git.repository import GitRepositoryFormat
 
440
        if shared:
 
441
            raise bzr_errors.IncompatibleFormat(GitRepositoryFormat(), self._format)
242
442
        return self.open_repository()
243
443
 
244
 
    def create_branch(self, name=None):
245
 
        refname = self._branch_name_to_ref(name)
 
444
    def create_branch(self, name=None, repository=None,
 
445
                      append_revisions_only=None, ref=None):
 
446
        refname = self._get_selected_ref(name, ref)
246
447
        from dulwich.protocol import ZERO_SHA
247
 
        self._git.refs[refname or "HEAD"] = ZERO_SHA
248
 
        return self.open_branch(name)
 
448
        if refname in self._git.refs:
 
449
            raise bzr_errors.AlreadyBranchError(self.user_url)
 
450
        self._git.refs[refname] = ZERO_SHA
 
451
        branch = self.open_branch(name)
 
452
        if append_revisions_only:
 
453
            branch.set_append_revisions_only(append_revisions_only)
 
454
        return branch
249
455
 
250
456
    def backup_bzrdir(self):
251
 
        if self._git.bare:
 
457
        if not self._git.bare:
252
458
            self.root_transport.copy_tree(".git", ".git.backup")
253
459
            return (self.root_transport.abspath(".git"),
254
460
                    self.root_transport.abspath(".git.backup"))
255
461
        else:
256
 
            raise bzr_errors.BzrError("Unable to backup bare repositories")
 
462
            basename = urlutils.basename(self.root_transport.base)
 
463
            parent = self.root_transport.clone('..')
 
464
            parent.copy_tree(basename, basename + ".backup")
257
465
 
258
466
    def create_workingtree(self, revision_id=None, from_branch=None,
259
467
        accelerator_tree=None, hardlink=False):
260
468
        if self._git.bare:
261
 
            raise bzr_errors.BzrError("Can't create working tree in a bare repo")
 
469
            raise bzr_errors.UnsupportedOperation(self.create_workingtree, self)
262
470
        from dulwich.index import write_index
263
471
        from dulwich.pack import SHA1Writer
264
472
        f = open(self.transport.local_abspath("index"), 'w+')
269
477
            f.close()
270
478
        return self.open_workingtree()
271
479
 
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()
 
480
    def _find_or_create_repository(self, force_new_repo=None):
 
481
        return self.create_repository(shared=False)
280
482
 
281
483
    def _find_creation_modes(self):
282
484
        """Determine the appropriate modes for files and directories.
291
493
        self._mode_check_done = True
292
494
        try:
293
495
            st = self.transport.stat('.')
294
 
        except TransportNotPossible:
 
496
        except bzr_errors.TransportNotPossible:
295
497
            self._dir_mode = None
296
498
            self._file_mode = None
297
499
        else:
322
524
            self._find_creation_modes()
323
525
        return self._dir_mode
324
526
 
 
527
    def get_refs_container(self):
 
528
        return self._git.refs
325
529
 
 
530
    def get_peeled(self, ref):
 
531
        return self._git.get_peeled(ref)