1
# Copyright (C) 2010-2018 Jelmer Vernooij <jelmer@jelmer.uk>
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""A Git repository implementation that uses a Bazaar transport."""
19
from __future__ import absolute_import
21
from io import BytesIO
26
from dulwich.errors import (
30
from dulwich.file import (
34
from dulwich.objects import (
37
from dulwich.object_store import (
41
from dulwich.pack import (
50
from dulwich.repo import (
62
read_packed_refs_with_peeled,
69
transport as _mod_transport,
72
from ..sixish import (
76
from ..errors import (
77
AlreadyControlDirError,
88
from ..lock import LogicalLockResult
91
class TransportRefsContainer(RefsContainer):
92
"""Refs container that reads refs from a transport."""
94
def __init__(self, transport, worktree_transport=None):
95
self.transport = transport
96
if worktree_transport is None:
97
worktree_transport = transport
98
self.worktree_transport = worktree_transport
99
self._packed_refs = None
100
self._peeled_refs = None
103
return "%s(%r)" % (self.__class__.__name__, self.transport)
105
def _ensure_dir_exists(self, path):
106
for n in range(path.count("/")):
107
dirname = "/".join(path.split("/")[:n+1])
109
self.transport.mkdir(dirname)
113
def subkeys(self, base):
114
"""Refs present in this container under a base.
116
:param base: The base to return refs under.
117
:return: A set of valid refs in this container under the base; the base
118
prefix is stripped from the ref names returned.
121
base_len = len(base) + 1
122
for refname in self.allkeys():
123
if refname.startswith(base):
124
keys.add(refname[base_len:])
130
self.worktree_transport.get_bytes("HEAD")
136
iter_files = list(self.transport.clone("refs").iter_files_recursive())
137
for filename in iter_files:
138
unquoted_filename = urlutils.unquote_to_bytes(filename)
139
refname = osutils.pathjoin(b"refs", unquoted_filename)
140
if check_ref_format(refname):
142
except (TransportNotPossible, NoSuchFile):
144
keys.update(self.get_packed_refs())
147
def get_packed_refs(self):
148
"""Get contents of the packed-refs file.
150
:return: Dictionary mapping ref names to SHA1s
152
:note: Will return an empty dictionary when no packed-refs file is
155
# TODO: invalidate the cache on repacking
156
if self._packed_refs is None:
157
# set both to empty because we want _peeled_refs to be
158
# None if and only if _packed_refs is also None.
159
self._packed_refs = {}
160
self._peeled_refs = {}
162
f = self.transport.get("packed-refs")
166
first_line = next(iter(f)).rstrip()
167
if (first_line.startswith("# pack-refs") and " peeled" in
169
for sha, name, peeled in read_packed_refs_with_peeled(f):
170
self._packed_refs[name] = sha
172
self._peeled_refs[name] = peeled
175
for sha, name in read_packed_refs(f):
176
self._packed_refs[name] = sha
179
return self._packed_refs
181
def get_peeled(self, name):
182
"""Return the cached peeled value of a ref, if available.
184
:param name: Name of the ref to peel
185
:return: The peeled value of the ref. If the ref is known not point to a
186
tag, this will be the SHA the ref refers to. If the ref may point to
187
a tag, but no cached information is available, None is returned.
189
self.get_packed_refs()
190
if self._peeled_refs is None or name not in self._packed_refs:
191
# No cache: no peeled refs were read, or this ref is loose
193
if name in self._peeled_refs:
194
return self._peeled_refs[name]
199
def read_loose_ref(self, name):
200
"""Read a reference file and return its contents.
202
If the reference file a symbolic reference, only read the first line of
203
the file. Otherwise, only read the first 40 bytes.
205
:param name: the refname to read, relative to refpath
206
:return: The contents of the ref file, or None if the file does not
208
:raises IOError: if any other error occurs
211
transport = self.worktree_transport
213
transport = self.transport
215
f = transport.get(urlutils.quote_from_bytes(name))
219
header = f.read(len(SYMREF))
221
# Read only the first line
222
return header + next(iter(f)).rstrip(b"\r\n")
224
# Read only the first 40 bytes
225
return header + f.read(40-len(SYMREF))
227
def _remove_packed_ref(self, name):
228
if self._packed_refs is None:
230
# reread cached refs from disk, while holding the lock
232
self._packed_refs = None
233
self.get_packed_refs()
235
if name not in self._packed_refs:
238
del self._packed_refs[name]
239
if name in self._peeled_refs:
240
del self._peeled_refs[name]
241
f = self.transport.open_write_stream("packed-refs")
243
write_packed_refs(f, self._packed_refs, self._peeled_refs)
247
def set_symbolic_ref(self, name, other):
248
"""Make a ref point at another ref.
250
:param name: Name of the ref to set
251
:param other: Name of the ref to point at
253
self._check_refname(name)
254
self._check_refname(other)
256
transport = self.transport
257
self._ensure_dir_exists(urlutils.quote_from_bytes(name))
259
transport = self.worktree_transport
260
transport.put_bytes(urlutils.quote_from_bytes(name), SYMREF + other + b'\n')
262
def set_if_equals(self, name, old_ref, new_ref):
263
"""Set a refname to new_ref only if it currently equals old_ref.
265
This method follows all symbolic references, and can be used to perform
266
an atomic compare-and-swap operation.
268
:param name: The refname to set.
269
:param old_ref: The old sha the refname must refer to, or None to set
271
:param new_ref: The new sha the refname will refer to.
272
:return: True if the set was successful, False otherwise.
275
realnames, _ = self.follow(name)
276
realname = realnames[-1]
277
except (KeyError, IndexError):
279
if realname == b'HEAD':
280
transport = self.worktree_transport
282
transport = self.transport
283
self._ensure_dir_exists(urlutils.quote_from_bytes(realname))
284
transport.put_bytes(urlutils.quote_from_bytes(realname), new_ref+b"\n")
287
def add_if_new(self, name, ref):
288
"""Add a new reference only if it does not already exist.
290
This method follows symrefs, and only ensures that the last ref in the
291
chain does not exist.
293
:param name: The refname to set.
294
:param ref: The new sha the refname will refer to.
295
:return: True if the add was successful, False otherwise.
298
realnames, contents = self.follow(name)
299
if contents is not None:
301
realname = realnames[-1]
302
except (KeyError, IndexError):
304
self._check_refname(realname)
305
if realname == b'HEAD':
306
transport = self.worktree_transport
308
transport = self.transport
309
self._ensure_dir_exists(urlutils.quote_from_bytes(realname))
310
transport.put_bytes(urlutils.quote_from_bytes(realname), ref+b"\n")
313
def remove_if_equals(self, name, old_ref):
314
"""Remove a refname only if it currently equals old_ref.
316
This method does not follow symbolic references. It can be used to
317
perform an atomic compare-and-delete operation.
319
:param name: The refname to delete.
320
:param old_ref: The old sha the refname must refer to, or None to delete
322
:return: True if the delete was successful, False otherwise.
324
self._check_refname(name)
327
transport = self.worktree_transport
329
transport = self.transport
331
transport.delete(urlutils.quote_from_bytes(name))
334
self._remove_packed_ref(name)
337
def get(self, name, default=None):
343
def unlock_ref(self, name):
345
transport = self.worktree_transport
347
transport = self.transport
348
lockname = name + b".lock"
350
self.transport.delete(urlutils.quote_from_bytes(lockname))
354
def lock_ref(self, name):
356
transport = self.worktree_transport
358
transport = self.transport
359
self._ensure_dir_exists(urlutils.quote_from_bytes(name))
360
lockname = urlutils.quote_from_bytes(name + b".lock")
362
local_path = self.transport.local_abspath(urlutils.quote_from_bytes(name))
364
# This is racy, but what can we do?
365
if self.transport.has(lockname):
366
raise LockContention(name)
367
lock_result = self.transport.put_bytes(lockname, b'Locked by brz-git')
368
return LogicalLockResult(lambda: self.transport.delete(lockname))
371
gf = GitFile(local_path, 'wb')
372
except FileLocked as e:
373
raise LockContention(name, e)
377
self.transport.delete(lockname)
379
raise LockBroken(lockname)
380
# GitFile.abort doesn't care if the lock has already disappeared
382
return LogicalLockResult(unlock)
385
# TODO(jelmer): Use upstream read_gitfile; unfortunately that expects strings
386
# rather than bytes..
388
"""Read a ``.git`` file.
390
The first line of the file should start with "gitdir: "
392
:param f: File-like object to read from
396
if not cs.startswith(b"gitdir: "):
397
raise ValueError("Expected file to start with 'gitdir: '")
398
return cs[len(b"gitdir: "):].rstrip(b"\n")
401
class TransportRepo(BaseRepo):
403
def __init__(self, transport, bare, refs_text=None):
404
self.transport = transport
407
with transport.get(CONTROLDIR) as f:
408
path = read_gitfile(f)
409
except (ReadError, NoSuchFile):
411
self._controltransport = self.transport
413
self._controltransport = self.transport.clone('.git')
415
self._controltransport = self.transport.clone(urlutils.quote_from_bytes(path))
416
commondir = self.get_named_file(COMMONDIR)
417
if commondir is not None:
419
commondir = os.path.join(
421
commondir.read().rstrip(b"\r\n").decode(
422
sys.getfilesystemencoding()))
423
self._commontransport = \
424
_mod_transport.get_transport_from_path(commondir)
426
self._commontransport = self._controltransport
427
object_store = TransportObjectStore(
428
self._commontransport.clone(OBJECTDIR))
429
if refs_text is not None:
430
refs_container = InfoRefsContainer(BytesIO(refs_text))
432
head = TransportRefsContainer(self._commontransport).read_loose_ref("HEAD")
436
refs_container._refs["HEAD"] = head
438
refs_container = TransportRefsContainer(
439
self._commontransport, self._controltransport)
440
super(TransportRepo, self).__init__(object_store,
443
def controldir(self):
444
return self._controltransport.local_abspath('.')
447
return self._commontransport.local_abspath('.')
451
return self.transport.local_abspath('.')
453
def _determine_file_mode(self):
454
# Be consistent with bzr
455
if sys.platform == 'win32':
459
def get_named_file(self, path):
460
"""Get a file from the control dir with a specific name.
462
Although the filename should be interpreted as a filename relative to
463
the control dir in a disk-baked Repo, the object returned need not be
464
pointing to a file in that location.
466
:param path: The path to the file, relative to the control dir.
467
:return: An open file object, or None if the file does not exist.
470
return self._controltransport.get(path.lstrip('/'))
474
def _put_named_file(self, relpath, contents):
475
self._controltransport.put_bytes(relpath, contents)
477
def index_path(self):
478
"""Return the path to the index file."""
479
return self._controltransport.local_abspath(INDEX_FILENAME)
481
def open_index(self):
482
"""Open the index for this repository."""
483
from dulwich.index import Index
484
if not self.has_index():
485
raise NoIndexPresent()
486
return Index(self.index_path())
489
"""Check if an index is present."""
490
# Bare repos must never have index files; non-bare repos may have a
491
# missing index file, which is treated as empty.
494
def get_config(self):
495
from dulwich.config import ConfigFile
497
with self._controltransport.get('config') as f:
498
return ConfigFile.from_file(f)
502
def get_config_stack(self):
503
from dulwich.config import StackedConfig
505
p = self.get_config()
511
backends.extend(StackedConfig.default_backends())
512
return StackedConfig(backends, writable=writable)
515
return "<%s for %r>" % (self.__class__.__name__, self.transport)
518
def init(cls, transport, bare=False):
521
transport.mkdir(".git")
523
raise AlreadyControlDirError(transport.base)
524
control_transport = transport.clone(".git")
526
control_transport = transport
527
for d in BASE_DIRECTORIES:
529
control_transport.mkdir("/".join(d))
533
control_transport.mkdir(OBJECTDIR)
535
raise AlreadyControlDirError(transport.base)
536
TransportObjectStore.init(control_transport.clone(OBJECTDIR))
537
ret = cls(transport, bare)
538
ret.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
539
ret._init_files(bare)
543
class TransportObjectStore(PackBasedObjectStore):
544
"""Git-style object store that exists on disk."""
546
def __init__(self, transport):
547
"""Open an object store.
549
:param transport: Transport to open data from
551
super(TransportObjectStore, self).__init__()
552
self.transport = transport
553
self.pack_transport = self.transport.clone(PACKDIR)
554
self._alternates = None
556
def __eq__(self, other):
557
if not isinstance(other, TransportObjectStore):
559
return self.transport == other.transport
562
return "%s(%r)" % (self.__class__.__name__, self.transport)
565
def alternates(self):
566
if self._alternates is not None:
567
return self._alternates
568
self._alternates = []
569
for path in self._read_alternate_paths():
571
t = _mod_transport.get_transport_from_path(path)
572
self._alternates.append(self.__class__(t))
573
return self._alternates
575
def _read_alternate_paths(self):
577
f = self.transport.get("info/alternates")
582
for l in f.read().splitlines():
592
# FIXME: Never invalidates.
593
if not self._pack_cache:
594
self._update_pack_cache()
595
return self._pack_cache.values()
597
def _update_pack_cache(self):
598
for pack in self._load_packs():
599
self._pack_cache[pack._basename] = pack
601
def _pack_names(self):
603
f = self.transport.get('info/packs')
605
return self.pack_transport.list_dir(".")
609
for line in f.read().splitlines():
612
(kind, name) = line.split(b" ", 1)
618
def _remove_pack(self, pack):
619
self.pack_transport.delete(os.path.basename(pack.index.path))
620
self.pack_transport.delete(pack.data.filename)
622
def _load_packs(self):
624
for name in self._pack_names():
625
if name.startswith("pack-") and name.endswith(".pack"):
627
size = self.pack_transport.stat(name).st_size
628
except TransportNotPossible:
629
f = self.pack_transport.get(name)
630
pd = PackData(name, f, size=len(contents))
632
pd = PackData(name, self.pack_transport.get(name),
634
idxname = name.replace(".pack", ".idx")
635
idx = load_pack_index_file(idxname, self.pack_transport.get(idxname))
636
pack = Pack.from_objects(pd, idx)
637
pack._basename = idxname[:-4]
641
def _iter_loose_objects(self):
642
for base in self.transport.list_dir('.'):
645
for rest in self.transport.list_dir(base):
646
yield (base+rest).encode(sys.getfilesystemencoding())
648
def _split_loose_object(self, sha):
649
return (sha[:2], sha[2:])
651
def _remove_loose_object(self, sha):
652
path = osutils.joinpath(self._split_loose_object(sha))
653
self.transport.delete(urlutils.quote_from_bytes(path))
655
def _get_loose_object(self, sha):
656
path = osutils.joinpath(self._split_loose_object(sha))
658
with self.transport.get(urlutils.quote_from_bytes(path)) as f:
659
return ShaFile.from_file(f)
663
def add_object(self, obj):
664
"""Add a single object to this object store.
666
:param obj: Object to add
668
(dir, file) = self._split_loose_object(obj.id)
670
self.transport.mkdir(urlutils.quote_from_bytes(dir))
673
path = urlutils.quote_from_bytes(osutils.pathjoin(dir, file))
674
if self.transport.has(path):
675
return # Already there, no need to write again
676
self.transport.put_bytes(path, obj.as_legacy_object())
678
def move_in_pack(self, f):
679
"""Move a specific file containing a pack into the pack directory.
681
:note: The file should be on the same file system as the
684
:param path: Path to the pack file.
687
p = PackData("", f, len(f.getvalue()))
688
entries = p.sorted_entries()
689
basename = "pack-%s" % iter_sha1(entry[0] for entry in entries).decode('ascii')
690
p._filename = basename + ".pack"
692
self.pack_transport.put_file(basename + ".pack", f)
693
idxfile = self.pack_transport.open_write_stream(basename + ".idx")
695
write_pack_index_v2(idxfile, entries, p.get_stored_checksum())
698
idxfile = self.pack_transport.get(basename + ".idx")
699
idx = load_pack_index_file(basename+".idx", idxfile)
700
final_pack = Pack.from_objects(p, idx)
701
final_pack._basename = basename
702
self._add_known_pack(basename, final_pack)
705
def move_in_thin_pack(self, f):
706
"""Move a specific file containing a pack into the pack directory.
708
:note: The file should be on the same file system as the
711
:param path: Path to the pack file.
714
p = Pack('', resolve_ext_ref=self.get_raw)
715
p._data = PackData.from_file(f, len(f.getvalue()))
717
p._idx_load = lambda: MemoryPackIndex(p.data.sorted_entries(), p.data.get_stored_checksum())
719
pack_sha = p.index.objects_sha1()
721
datafile = self.pack_transport.open_write_stream(
722
"pack-%s.pack" % pack_sha.decode('ascii'))
724
entries, data_sum = write_pack_objects(datafile, p.pack_tuples())
727
entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
728
idxfile = self.pack_transport.open_write_stream(
729
"pack-%s.idx" % pack_sha.decode('ascii'))
731
write_pack_index_v2(idxfile, entries, data_sum)
734
# TODO(jelmer): Just add new pack to the cache
735
self._flush_pack_cache()
738
"""Add a new pack to this object store.
740
:return: Fileobject to write to and a commit function to
741
call when the pack is finished.
745
if len(f.getvalue()) > 0:
746
return self.move_in_pack(f)
751
return f, commit, abort
754
def init(cls, transport):
756
transport.mkdir('info')
760
transport.mkdir(PACKDIR)
763
return cls(transport)