102
113
def break_lock(self):
114
# There are no global locks, so nothing to break.
115
raise NotImplementedError(self.break_lock)
105
117
def cloning_metadir(self, stacked=False):
106
return format_registry.make_bzrdir("default")
108
def _branch_name_to_ref(self, name):
109
raise NotImplementedError(self._branch_name_to_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)
117
def open_branch(self, ignore_fallbacks=None, unsupported=False):
118
return self._open_branch(name=None,
119
ignore_fallbacks=ignore_fallbacks, unsupported=unsupported)
118
return format_registry.make_controldir("git")
120
def checkout_metadir(self, stacked=False):
121
return format_registry.make_controldir("git")
123
def _get_selected_ref(self, branch, ref=None):
124
if ref is not None and branch is not None:
125
raise brz_errors.BzrError("can't specify both ref and branch")
128
if branch is not None:
129
from .refs import branch_name_to_ref
130
return branch_name_to_ref(branch)
131
segment_parameters = getattr(
132
self.user_transport, "get_segment_parameters", lambda: {})()
133
ref = segment_parameters.get("ref")
135
return urlutils.unquote_to_bytes(ref)
136
if branch is None and getattr(self, "_get_selected_branch", False):
137
branch = self._get_selected_branch()
138
if branch is not None:
139
from .refs import branch_name_to_ref
140
return branch_name_to_ref(branch)
121
143
def get_config(self):
122
144
return GitDirConfig()
146
def _available_backup_name(self, base):
147
return osutils.available_backup_name(base, self.root_transport.has)
149
def sprout(self, url, revision_id=None, force_new_repo=False,
150
recurse='down', possible_transports=None,
151
accelerator_tree=None, hardlink=False, stacked=False,
152
source_branch=None, create_tree_if_local=True):
153
from ..repository import InterRepository
154
from ..transport.local import LocalTransport
155
from ..transport import get_transport
156
target_transport = get_transport(url, possible_transports)
157
target_transport.ensure_base()
158
cloning_format = self.cloning_metadir()
159
# Create/update the result branch
161
result = ControlDir.open_from_transport(target_transport)
162
except brz_errors.NotBranchError:
163
result = cloning_format.initialize_on_transport(target_transport)
164
source_branch = self.open_branch()
165
source_repository = self.find_repository()
167
result_repo = result.find_repository()
168
except brz_errors.NoRepositoryPresent:
169
result_repo = result.create_repository()
171
raise _mod_branch.UnstackableBranchFormat(
172
self._format, self.user_url)
173
interrepo = InterRepository.get(source_repository, result_repo)
175
if revision_id is not None:
176
determine_wants = interrepo.get_determine_wants_revids(
177
[revision_id], include_tags=True)
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(
183
result, revision_id=revision_id, repository=result_repo)
184
if (create_tree_if_local and
185
result.open_branch(name="").name == result_branch.name and
186
isinstance(target_transport, LocalTransport) and
187
(result_repo is None or result_repo.make_working_trees())):
188
wt = result.create_workingtree(
189
accelerator_tree=accelerator_tree,
190
hardlink=hardlink, from_branch=result_branch)
193
if recurse == 'down':
194
with contextlib.ExitStack() as stack:
197
basis = wt.basis_tree()
198
elif result_branch is not None:
199
basis = result_branch.basis_tree()
200
elif source_branch is not None:
201
basis = source_branch.basis_tree()
202
if basis is not None:
203
stack.enter_context(basis.lock_read())
204
subtrees = basis.iter_references()
207
for path in subtrees:
208
target = urlutils.join(url, urlutils.escape(path))
209
sublocation = wt.reference_parent(
210
path, possible_transports=possible_transports)
211
if sublocation is None:
213
'Ignoring nested tree %s, parent location unknown.',
216
sublocation.controldir.sprout(
217
target, basis.get_reference_revision(path),
218
force_new_repo=force_new_repo, recurse=recurse,
222
def clone_on_transport(self, transport, revision_id=None,
223
force_new_repo=False, preserve_stacking=False,
224
stacked_on=None, create_prefix=False,
225
use_existing_dir=True, no_tree=False,
227
"""See ControlDir.clone_on_transport."""
228
from ..repository import InterRepository
229
from .mapping import default_mapping
230
from ..transport.local import LocalTransport
231
if stacked_on is not None:
232
raise _mod_branch.UnstackableBranchFormat(
233
self._format, self.user_url)
235
format = BareLocalGitControlDirFormat()
237
format = LocalGitControlDirFormat()
238
(target_repo, target_controldir, stacking,
239
repo_policy) = format.initialize_on_transport_ex(
240
transport, use_existing_dir=use_existing_dir,
241
create_prefix=create_prefix,
242
force_new_repo=force_new_repo)
243
target_repo = target_controldir.find_repository()
244
target_git_repo = target_repo._git
245
source_repo = self.find_repository()
246
interrepo = InterRepository.get(source_repo, target_repo)
247
if revision_id is not None:
248
determine_wants = interrepo.get_determine_wants_revids(
249
[revision_id], include_tags=True, tag_selector=tag_selector)
251
determine_wants = interrepo.determine_wants_all
252
(pack_hint, _, refs) = interrepo.fetch_objects(determine_wants,
253
mapping=default_mapping)
254
for name, val in refs.items():
255
target_git_repo.refs[name] = val
256
result_dir = LocalGitDir(transport, target_git_repo, format)
257
if revision_id is not None:
258
result_dir.open_branch().set_last_revision(revision_id)
259
if not no_tree and isinstance(result_dir.root_transport, LocalTransport):
260
if result_dir.open_repository().make_working_trees():
262
local_wt = self.open_workingtree()
263
except brz_errors.NoWorkingTree:
265
except brz_errors.NotLocalUrl:
266
result_dir.create_workingtree(revision_id=revision_id)
268
local_wt.clone(result_dir, revision_id=revision_id)
272
def find_repository(self):
273
"""Find the repository that should be used.
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
279
return self._gitrepository_class(self._find_commondir())
281
def get_refs_container(self):
282
"""Retrieve the refs container.
284
raise NotImplementedError(self.get_refs_container)
286
def determine_repository_policy(self, force_new_repo=False, stack_on=None,
287
stack_on_pwd=None, require_stacking=False):
288
"""Return an object representing a policy to use.
290
This controls whether a new repository is created, and the format of
291
that repository, or some existing shared repository used instead.
293
If stack_on is supplied, will not seek a containing shared repo.
295
:param force_new_repo: If True, require a new repository to be created.
296
:param stack_on: If supplied, the location to stack on. If not
297
supplied, a default_stack_on location may be used.
298
:param stack_on_pwd: If stack_on is relative, the location it is
301
return UseExistingRepository(self.find_repository())
303
def branch_names(self):
304
from .refs import ref_to_branch_name
306
for ref in self.get_refs_container().keys():
308
branch_name = ref_to_branch_name(ref)
309
except UnicodeDecodeError:
310
trace.warning("Ignoring branch %r with unicode error ref", ref)
314
ret.append(branch_name)
317
def get_branches(self):
318
from .refs import ref_to_branch_name
320
for ref in self.get_refs_container().keys():
322
branch_name = ref_to_branch_name(ref)
323
except UnicodeDecodeError:
324
trace.warning("Ignoring branch %r with unicode error ref", ref)
328
ret[branch_name] = self.open_branch(ref=ref)
331
def list_branches(self):
332
return list(self.get_branches().values())
334
def push_branch(self, source, revision_id=None, overwrite=False,
335
remember=False, create_prefix=False, lossy=False,
336
name=None, tag_selector=None):
337
"""Push the source branch into this ControlDir."""
338
push_result = GitPushResult()
339
push_result.workingtree_updated = None
340
push_result.master_branch = None
341
push_result.source_branch = source
342
push_result.stacked_on = None
343
from .branch import GitBranch
344
if isinstance(source, GitBranch) and lossy:
345
raise brz_errors.LossyPushToSameVCS(source.controldir, self)
346
target = self.open_branch(name, nascent_ok=True)
347
push_result.branch_push_result = source.push(
348
target, overwrite=overwrite, stop_revision=revision_id,
349
lossy=lossy, tag_selector=tag_selector)
350
push_result.new_revid = push_result.branch_push_result.new_revid
351
push_result.old_revid = push_result.branch_push_result.old_revid
353
wt = self.open_workingtree()
354
except brz_errors.NoWorkingTree:
355
push_result.workingtree_updated = None
357
if self.open_branch(name="").name == target.name:
359
old_revision=push_result.old_revid,
360
new_revision=push_result.new_revid)
361
push_result.workingtree_updated = True
363
push_result.workingtree_updated = False
364
push_result.target_branch = target
365
if source.get_push_location() is None or remember:
366
source.set_push_location(push_result.target_branch.base)
370
class LocalGitControlDirFormat(GitControlDirFormat):
371
"""The .git directory control format."""
376
def _known_formats(self):
377
return set([LocalGitControlDirFormat()])
380
def repository_format(self):
381
from .repository import GitRepositoryFormat
382
return GitRepositoryFormat()
385
def workingtree_format(self):
386
from .workingtree import GitWorkingTreeFormat
387
return GitWorkingTreeFormat()
389
def get_branch_format(self):
390
from .branch import LocalGitBranchFormat
391
return LocalGitBranchFormat()
393
def open(self, transport, _found=None):
394
"""Open this directory.
397
from .transportgit import TransportRepo
399
def _open(transport):
401
return TransportRepo(transport, self.bare,
402
refs_text=getattr(self, "_refs_text", None))
403
except ValueError as e:
404
if e.args == ('Expected file to start with \'gitdir: \'', ):
405
raise brz_errors.NotBranchError(path=transport.base)
408
def redirected(transport, e, redirection_notice):
409
trace.note(redirection_notice)
410
return transport._redirected_to(e.source, e.target)
411
gitrepo = do_catching_redirections(_open, transport, redirected)
412
if not _found and not gitrepo._controltransport.has('objects'):
413
raise brz_errors.NotBranchError(path=transport.base)
414
return LocalGitDir(transport, gitrepo, self)
416
def get_format_description(self):
417
return "Local Git Repository"
419
def initialize_on_transport(self, transport):
420
from .transportgit import TransportRepo
421
git_repo = TransportRepo.init(transport, bare=self.bare)
422
return LocalGitDir(transport, git_repo, self)
424
def initialize_on_transport_ex(self, transport, use_existing_dir=False,
425
create_prefix=False, force_new_repo=False,
427
stack_on_pwd=None, repo_format_name=None,
428
make_working_trees=None,
429
shared_repo=False, vfs_only=False):
431
raise brz_errors.SharedRepositoriesUnsupported(self)
433
def make_directory(transport):
437
def redirected(transport, e, redirection_notice):
438
trace.note(redirection_notice)
439
return transport._redirected_to(e.source, e.target)
441
transport = do_catching_redirections(
442
make_directory, transport, redirected)
443
except brz_errors.FileExists:
444
if not use_existing_dir:
446
except brz_errors.NoSuchFile:
447
if not create_prefix:
449
transport.create_prefix()
450
controldir = self.initialize_on_transport(transport)
452
result_repo = controldir.find_repository()
453
repository_policy = UseExistingRepository(result_repo)
454
result_repo.lock_write()
457
repository_policy = None
458
return (result_repo, controldir, False,
461
def is_supported(self):
464
def supports_transport(self, transport):
466
external_url = transport.external_url()
467
except brz_errors.InProcessTransport:
468
raise brz_errors.NotBranchError(path=transport.base)
469
return external_url.startswith("file:")
471
def is_control_filename(self, filename):
472
return (filename == '.git'
473
or filename.startswith('.git/')
474
or filename.startswith('.git\\'))
477
class BareLocalGitControlDirFormat(LocalGitControlDirFormat):
480
supports_workingtrees = False
482
def get_format_description(self):
483
return "Local Git Repository (bare)"
485
def is_control_filename(self, filename):
125
489
class LocalGitDir(GitDir):
126
490
"""An adapter to the '.git' dir used by git."""
128
492
def _get_gitrepository_class(self):
129
from bzrlib.plugins.git.repository import LocalGitRepository
493
from .repository import LocalGitRepository
130
494
return LocalGitRepository
497
return "<%s at %r>" % (
498
self.__class__.__name__, self.root_transport.base)
132
500
_gitrepository_class = property(_get_gitrepository_class)
148
516
self.transport = transport
150
518
self.transport = transport.clone('.git')
151
self._lockfiles = lockfiles
152
519
self._mode_check_done = None
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)
158
from dulwich.repo import SYMREF
159
refcontents = self._git.refs.read_ref(ref)
160
if refcontents.startswith(SYMREF):
161
ref = refcontents[len(SYMREF):]
164
def is_control_filename(self, filename):
165
return filename == '.git' or filename.startswith('.git/')
521
def _get_symref(self, ref):
522
ref_chain, unused_sha = self._git.refs.follow(ref)
523
if len(ref_chain) == 1:
527
def set_branch_reference(self, target_branch, name=None):
528
ref = self._get_selected_ref(name)
529
target_transport = target_branch.controldir.control_transport
530
if self.control_transport.base == target_transport.base:
531
if ref == target_branch.ref:
532
raise BranchReferenceLoop(target_branch)
533
self._git.refs.set_symbolic_ref(ref, target_branch.ref)
537
target_branch.controldir.control_transport.local_abspath(
539
except brz_errors.NotLocalUrl:
540
raise brz_errors.IncompatibleFormat(
541
target_branch._format, self._format)
542
# TODO(jelmer): Do some consistency checking across branches..
543
self.control_transport.put_bytes(
544
'commondir', encode_git_path(target_path))
545
# TODO(jelmer): Urgh, avoid mucking about with internals.
546
self._git._commontransport = (
547
target_branch.repository._git._commontransport.clone())
548
self._git.object_store = TransportObjectStore(
549
self._git._commontransport.clone(OBJECTDIR))
550
self._git.refs.transport = self._git._commontransport
551
target_ref_chain, unused_sha = (
552
target_branch.controldir._git.refs.follow(target_branch.ref))
553
for target_ref in target_ref_chain:
554
if target_ref == b'HEAD':
558
# Can't create a reference to something that is not a in a repository.
559
raise brz_errors.IncompatibleFormat(
560
self.set_branch_reference, self)
561
self._git.refs.set_symbolic_ref(ref, target_ref)
563
def get_branch_reference(self, name=None):
564
ref = self._get_selected_ref(name)
565
target_ref = self._get_symref(ref)
566
if target_ref is not None:
567
from .refs import ref_to_branch_name
569
branch_name = ref_to_branch_name(target_ref)
571
params = {'ref': urlutils.quote(
572
target_ref.decode('utf-8'), '')}
574
if branch_name != '':
575
params = {'branch': urlutils.quote(branch_name, '')}
579
commondir = self.control_transport.get_bytes('commondir')
580
except brz_errors.NoSuchFile:
581
base_url = self.user_url.rstrip('/')
583
base_url = urlutils.local_path_to_url(
584
decode_git_path(commondir)).rstrip('/.git/') + '/'
585
return urlutils.join_segment_parameters(base_url, params)
588
def find_branch_format(self, name=None):
589
from .branch import (
590
LocalGitBranchFormat,
592
return LocalGitBranchFormat()
167
594
def get_branch_transport(self, branch_format, name=None):
168
595
if branch_format is None:
169
596
return self.transport
170
597
if isinstance(branch_format, LocalGitControlDirFormat):
171
598
return self.transport
172
raise bzr_errors.IncompatibleFormat(branch_format, self._format)
599
raise brz_errors.IncompatibleFormat(branch_format, self._format)
174
601
def get_repository_transport(self, format):
175
602
if format is None:
176
603
return self.transport
177
604
if isinstance(format, LocalGitControlDirFormat):
178
605
return self.transport
179
raise bzr_errors.IncompatibleFormat(format, self._format)
606
raise brz_errors.IncompatibleFormat(format, self._format)
181
608
def get_workingtree_transport(self, format):
182
609
if format is None:
183
610
return self.transport
184
611
if isinstance(format, LocalGitControlDirFormat):
185
612
return self.transport
186
raise bzr_errors.IncompatibleFormat(format, self._format)
613
raise brz_errors.IncompatibleFormat(format, self._format)
188
def _open_branch(self, name=None, ignore_fallbacks=None, unsupported=False):
615
def open_branch(self, name=None, unsupported=False, ignore_fallbacks=None,
616
ref=None, possible_transports=None, nascent_ok=False):
189
617
"""'create' a branch for this dir."""
190
repo = self.open_repository()
191
from bzrlib.plugins.git.branch import LocalGitBranch
192
return LocalGitBranch(self, repo, self._branch_name_to_ref(name),
618
repo = self.find_repository()
619
from .branch import LocalGitBranch
620
ref = self._get_selected_ref(name, ref)
621
if not nascent_ok and ref not in self._git.refs:
622
raise brz_errors.NotBranchError(
623
self.root_transport.base, controldir=self)
624
ref_chain, unused_sha = self._git.refs.follow(ref)
625
if ref_chain[-1] == b'HEAD':
628
controldir = self._find_commondir()
629
return LocalGitBranch(controldir, repo, ref_chain[-1])
195
631
def destroy_branch(self, name=None):
196
refname = self._branch_name_to_ref(name)
197
if not refname in self._git.refs:
198
raise bzr_errors.NotBranchError(self.root_transport.base,
200
del self._git.refs[refname]
632
refname = self._get_selected_ref(name)
633
if refname == b'HEAD':
634
# HEAD can't be removed
635
raise brz_errors.UnsupportedOperation(
636
self.destroy_branch, self)
638
del self._git.refs[refname]
640
raise brz_errors.NotBranchError(
641
self.root_transport.base, controldir=self)
202
643
def destroy_repository(self):
203
raise bzr_errors.UnsupportedOperation(self.destroy_repository, self)
644
raise brz_errors.UnsupportedOperation(self.destroy_repository, self)
205
646
def destroy_workingtree(self):
206
raise bzr_errors.UnsupportedOperation(self.destroy_workingtree, self)
647
raise brz_errors.UnsupportedOperation(self.destroy_workingtree, self)
649
def destroy_workingtree_metadata(self):
650
raise brz_errors.UnsupportedOperation(
651
self.destroy_workingtree_metadata, self)
208
653
def needs_format_conversion(self, format=None):
209
654
return not isinstance(self._format, format.__class__)
211
def list_branches(self):
213
for name in self._git.get_refs():
214
if name.startswith("refs/heads/"):
215
ret.append(self.open_branch(name=name))
218
def open_repository(self, shared=False):
656
def open_repository(self):
219
657
"""'open' a repository for this dir."""
220
return self._gitrepository_class(self, self._lockfiles)
222
def open_workingtree(self, recommend_upgrade=True):
658
if self.control_transport.has('commondir'):
659
raise brz_errors.NoRepositoryPresent(self)
660
return self._gitrepository_class(self)
662
def has_workingtree(self):
663
return not self._git.bare
665
def open_workingtree(self, recommend_upgrade=True, unsupported=False):
223
666
if not self._git.bare:
224
from dulwich.errors import NoIndexPresent
225
repo = self.open_repository()
227
index = repo._git.open_index()
228
except NoIndexPresent:
231
from bzrlib.plugins.git.workingtree import GitWorkingTree
233
branch = self.open_branch()
234
except bzr_errors.NotBranchError:
237
return GitWorkingTree(self, repo, branch, index)
667
repo = self.find_repository()
668
from .workingtree import GitWorkingTree
669
branch = self.open_branch(ref=b'HEAD', nascent_ok=True)
670
return GitWorkingTree(self, repo, branch)
238
671
loc = urlutils.unescape_for_display(self.root_transport.base, 'ascii')
239
raise bzr_errors.NoWorkingTree(loc)
672
raise brz_errors.NoWorkingTree(loc)
241
674
def create_repository(self, shared=False):
242
return self.open_repository()
675
from .repository import GitRepositoryFormat
677
raise brz_errors.IncompatibleFormat(
678
GitRepositoryFormat(), self._format)
679
return self.find_repository()
244
def create_branch(self, name=None):
245
refname = self._branch_name_to_ref(name)
246
from dulwich.protocol import ZERO_SHA
247
self._git.refs[refname or "HEAD"] = ZERO_SHA
248
return self.open_branch(name)
681
def create_branch(self, name=None, repository=None,
682
append_revisions_only=None, ref=None):
683
refname = self._get_selected_ref(name, ref)
684
if refname != b'HEAD' and refname in self._git.refs:
685
raise brz_errors.AlreadyBranchError(self.user_url)
686
repo = self.open_repository()
687
if refname in self._git.refs:
688
ref_chain, unused_sha = self._git.refs.follow(
689
self._get_selected_ref(None))
690
if ref_chain[0] == b'HEAD':
691
refname = ref_chain[1]
692
from .branch import LocalGitBranch
693
branch = LocalGitBranch(self, repo, refname)
694
if append_revisions_only:
695
branch.set_append_revisions_only(append_revisions_only)
250
698
def backup_bzrdir(self):
699
if not self._git.bare:
252
700
self.root_transport.copy_tree(".git", ".git.backup")
253
701
return (self.root_transport.abspath(".git"),
254
702
self.root_transport.abspath(".git.backup"))
256
raise bzr_errors.BzrError("Unable to backup bare repositories")
704
basename = urlutils.basename(self.root_transport.base)
705
parent = self.root_transport.clone('..')
706
parent.copy_tree(basename, basename + ".backup")
258
708
def create_workingtree(self, revision_id=None, from_branch=None,
259
accelerator_tree=None, hardlink=False):
709
accelerator_tree=None, hardlink=False):
260
710
if self._git.bare:
261
raise bzr_errors.BzrError("Can't create working tree in a bare repo")
262
from dulwich.index import write_index
263
from dulwich.pack import SHA1Writer
264
f = open(self.transport.local_abspath("index"), 'w+')
270
return self.open_workingtree()
272
def find_repository(self):
273
"""Find the repository that should be used.
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
279
return self.open_repository()
711
raise brz_errors.UnsupportedOperation(
712
self.create_workingtree, self)
713
if from_branch is None:
714
from_branch = self.open_branch(nascent_ok=True)
715
if revision_id is None:
716
revision_id = from_branch.last_revision()
717
repo = self.find_repository()
718
from .workingtree import GitWorkingTree
719
wt = GitWorkingTree(self, repo, from_branch)
720
wt.set_last_revision(revision_id)
721
wt._build_checkout_with_index()
724
def _find_or_create_repository(self, force_new_repo=None):
725
return self.create_repository(shared=False)
281
727
def _find_creation_modes(self):
282
728
"""Determine the appropriate modes for files and directories.