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 (
63
read_packed_refs_with_peeled,
70
transport as _mod_transport,
73
from ...sixish import (
77
from ...errors import (
78
AlreadyControlDirError,
89
from ...lock import LogicalLockResult
92
class TransportRefsContainer(RefsContainer):
93
"""Refs container that reads refs from a transport."""
95
def __init__(self, transport, worktree_transport=None):
96
self.transport = transport
97
if worktree_transport is None:
98
worktree_transport = transport
99
self.worktree_transport = worktree_transport
100
self._packed_refs = None
101
self._peeled_refs = None
104
return "%s(%r)" % (self.__class__.__name__, self.transport)
106
def _ensure_dir_exists(self, path):
107
for n in range(path.count(b"/")):
108
dirname = b"/".join(path.split(b"/")[:n+1])
110
self.transport.mkdir(dirname)
114
def subkeys(self, base):
115
"""Refs present in this container under a base.
117
:param base: The base to return refs under.
118
:return: A set of valid refs in this container under the base; the base
119
prefix is stripped from the ref names returned.
122
base_len = len(base) + 1
123
for refname in self.allkeys():
124
if refname.startswith(base):
125
keys.add(refname[base_len:])
131
self.worktree_transport.get_bytes("HEAD")
137
iter_files = list(self.transport.clone("refs").iter_files_recursive())
138
for filename in iter_files:
139
unquoted_filename = urlutils.unquote(filename)
141
# JRV: Work around unquote returning a text_type string on
143
unquoted_filename = unquoted_filename.encode('utf-8')
144
refname = osutils.pathjoin(b"refs", unquoted_filename)
145
if check_ref_format(refname):
147
except (TransportNotPossible, NoSuchFile):
149
keys.update(self.get_packed_refs())
152
def get_packed_refs(self):
153
"""Get contents of the packed-refs file.
155
:return: Dictionary mapping ref names to SHA1s
157
:note: Will return an empty dictionary when no packed-refs file is
160
# TODO: invalidate the cache on repacking
161
if self._packed_refs is None:
162
# set both to empty because we want _peeled_refs to be
163
# None if and only if _packed_refs is also None.
164
self._packed_refs = {}
165
self._peeled_refs = {}
167
f = self.transport.get("packed-refs")
171
first_line = next(iter(f)).rstrip()
172
if (first_line.startswith("# pack-refs") and " peeled" in
174
for sha, name, peeled in read_packed_refs_with_peeled(f):
175
self._packed_refs[name] = sha
177
self._peeled_refs[name] = peeled
180
for sha, name in read_packed_refs(f):
181
self._packed_refs[name] = sha
184
return self._packed_refs
186
def get_peeled(self, name):
187
"""Return the cached peeled value of a ref, if available.
189
:param name: Name of the ref to peel
190
:return: The peeled value of the ref. If the ref is known not point to a
191
tag, this will be the SHA the ref refers to. If the ref may point to
192
a tag, but no cached information is available, None is returned.
194
self.get_packed_refs()
195
if self._peeled_refs is None or name not in self._packed_refs:
196
# No cache: no peeled refs were read, or this ref is loose
198
if name in self._peeled_refs:
199
return self._peeled_refs[name]
204
def read_loose_ref(self, name):
205
"""Read a reference file and return its contents.
207
If the reference file a symbolic reference, only read the first line of
208
the file. Otherwise, only read the first 40 bytes.
210
:param name: the refname to read, relative to refpath
211
:return: The contents of the ref file, or None if the file does not
213
:raises IOError: if any other error occurs
216
transport = self.worktree_transport
218
transport = self.transport
220
f = transport.get(name)
224
header = f.read(len(SYMREF))
226
# Read only the first line
227
return header + next(iter(f)).rstrip(b"\r\n")
229
# Read only the first 40 bytes
230
return header + f.read(40-len(SYMREF))
234
def _remove_packed_ref(self, name):
235
if self._packed_refs is None:
237
# reread cached refs from disk, while holding the lock
239
self._packed_refs = None
240
self.get_packed_refs()
242
if name not in self._packed_refs:
245
del self._packed_refs[name]
246
if name in self._peeled_refs:
247
del self._peeled_refs[name]
248
f = self.transport.open_write_stream("packed-refs")
250
write_packed_refs(f, self._packed_refs, self._peeled_refs)
254
def set_symbolic_ref(self, name, other):
255
"""Make a ref point at another ref.
257
:param name: Name of the ref to set
258
:param other: Name of the ref to point at
260
self._check_refname(name)
261
self._check_refname(other)
263
transport = self.transport
264
self._ensure_dir_exists(name)
266
transport = self.worktree_transport
267
transport.put_bytes(name, SYMREF + other + b'\n')
269
def set_if_equals(self, name, old_ref, new_ref):
270
"""Set a refname to new_ref only if it currently equals old_ref.
272
This method follows all symbolic references, and can be used to perform
273
an atomic compare-and-swap operation.
275
:param name: The refname to set.
276
:param old_ref: The old sha the refname must refer to, or None to set
278
:param new_ref: The new sha the refname will refer to.
279
:return: True if the set was successful, False otherwise.
282
realnames, _ = self.follow(name)
283
realname = realnames[-1]
284
except (KeyError, IndexError):
286
if realname == b'HEAD':
287
transport = self.worktree_transport
289
transport = self.transport
290
self._ensure_dir_exists(realname)
291
transport.put_bytes(realname, new_ref+b"\n")
294
def add_if_new(self, name, ref):
295
"""Add a new reference only if it does not already exist.
297
This method follows symrefs, and only ensures that the last ref in the
298
chain does not exist.
300
:param name: The refname to set.
301
:param ref: The new sha the refname will refer to.
302
:return: True if the add was successful, False otherwise.
305
realnames, contents = self.follow(name)
306
if contents is not None:
308
realname = realnames[-1]
309
except (KeyError, IndexError):
311
self._check_refname(realname)
312
if realname == b'HEAD':
313
transport = self.worktree_transport
315
transport = self.transport
316
self._ensure_dir_exists(realname)
317
transport.put_bytes(realname, ref+b"\n")
320
def remove_if_equals(self, name, old_ref):
321
"""Remove a refname only if it currently equals old_ref.
323
This method does not follow symbolic references. It can be used to
324
perform an atomic compare-and-delete operation.
326
:param name: The refname to delete.
327
:param old_ref: The old sha the refname must refer to, or None to delete
329
:return: True if the delete was successful, False otherwise.
331
self._check_refname(name)
334
transport = self.worktree_transport
336
transport = self.transport
338
transport.delete(name)
341
self._remove_packed_ref(name)
344
def get(self, name, default=None):
350
def unlock_ref(self, name):
352
transport = self.worktree_transport
354
transport = self.transport
355
lockname = name + b".lock"
357
self.transport.delete(lockname)
361
def lock_ref(self, name):
363
transport = self.worktree_transport
365
transport = self.transport
366
self._ensure_dir_exists(name)
367
lockname = name + b".lock"
369
local_path = self.transport.local_abspath(name)
371
# This is racy, but what can we do?
372
if self.transport.has(lockname):
373
raise LockContention(name)
374
lock_result = self.transport.put_bytes(lockname, b'Locked by brz-git')
375
return LogicalLockResult(lambda: self.transport.delete(lockname))
378
gf = GitFile(local_path, 'wb')
379
except FileLocked as e:
380
raise LockContention(name, e)
384
self.transport.delete(lockname)
386
raise LockBroken(lockname)
387
# GitFile.abort doesn't care if the lock has already disappeared
389
return LogicalLockResult(unlock)
392
class TransportRepo(BaseRepo):
394
def __init__(self, transport, bare, refs_text=None):
395
self.transport = transport
398
with transport.get(CONTROLDIR) as f:
399
path = read_gitfile(f)
400
except (ReadError, NoSuchFile):
402
self._controltransport = self.transport
404
self._controltransport = self.transport.clone('.git')
406
self._controltransport = self.transport.clone(path)
407
commondir = self.get_named_file(COMMONDIR)
408
if commondir is not None:
410
commondir = os.path.join(
412
commondir.read().rstrip(b"\r\n").decode(
413
sys.getfilesystemencoding()))
414
self._commontransport = \
415
_mod_transport.get_transport_from_path(commondir)
417
self._commontransport = self._controltransport
418
object_store = TransportObjectStore(
419
self._commontransport.clone(OBJECTDIR))
420
if refs_text is not None:
421
refs_container = InfoRefsContainer(BytesIO(refs_text))
423
head = TransportRefsContainer(self._commontransport).read_loose_ref("HEAD")
427
refs_container._refs["HEAD"] = head
429
refs_container = TransportRefsContainer(
430
self._commontransport, self._controltransport)
431
super(TransportRepo, self).__init__(object_store,
434
def controldir(self):
435
return self._controltransport.local_abspath('.')
438
return self._commontransport.local_abspath('.')
442
return self.transport.local_abspath('.')
444
def _determine_file_mode(self):
445
# Be consistent with bzr
446
if sys.platform == 'win32':
450
def get_named_file(self, path):
451
"""Get a file from the control dir with a specific name.
453
Although the filename should be interpreted as a filename relative to
454
the control dir in a disk-baked Repo, the object returned need not be
455
pointing to a file in that location.
457
:param path: The path to the file, relative to the control dir.
458
:return: An open file object, or None if the file does not exist.
461
return self._controltransport.get(path.lstrip('/'))
465
def _put_named_file(self, relpath, contents):
466
self._controltransport.put_bytes(relpath, contents)
468
def index_path(self):
469
"""Return the path to the index file."""
470
return self._controltransport.local_abspath(INDEX_FILENAME)
472
def open_index(self):
473
"""Open the index for this repository."""
474
from dulwich.index import Index
475
if not self.has_index():
476
raise NoIndexPresent()
477
return Index(self.index_path())
480
"""Check if an index is present."""
481
# Bare repos must never have index files; non-bare repos may have a
482
# missing index file, which is treated as empty.
485
def get_config(self):
486
from dulwich.config import ConfigFile
488
return ConfigFile.from_file(self._controltransport.get('config'))
492
def get_config_stack(self):
493
from dulwich.config import StackedConfig
495
p = self.get_config()
501
backends.extend(StackedConfig.default_backends())
502
return StackedConfig(backends, writable=writable)
505
return "<%s for %r>" % (self.__class__.__name__, self.transport)
508
def init(cls, transport, bare=False):
511
transport.mkdir(".git")
513
raise AlreadyControlDirError(transport.base)
514
control_transport = transport.clone(".git")
516
control_transport = transport
517
for d in BASE_DIRECTORIES:
519
control_transport.mkdir("/".join(d))
523
control_transport.mkdir(OBJECTDIR)
525
raise AlreadyControlDirError(transport.base)
526
TransportObjectStore.init(control_transport.clone(OBJECTDIR))
527
ret = cls(transport, bare)
528
ret.refs.set_symbolic_ref(b"HEAD", b"refs/heads/master")
529
ret._init_files(bare)
533
class TransportObjectStore(PackBasedObjectStore):
534
"""Git-style object store that exists on disk."""
536
def __init__(self, transport):
537
"""Open an object store.
539
:param transport: Transport to open data from
541
super(TransportObjectStore, self).__init__()
542
self.transport = transport
543
self.pack_transport = self.transport.clone(PACKDIR)
544
self._alternates = None
546
def __eq__(self, other):
547
if not isinstance(other, TransportObjectStore):
549
return self.transport == other.transport
552
return "%s(%r)" % (self.__class__.__name__, self.transport)
555
def alternates(self):
556
if self._alternates is not None:
557
return self._alternates
558
self._alternates = []
559
for path in self._read_alternate_paths():
561
t = _mod_transport.get_transport_from_path(path)
562
self._alternates.append(self.__class__(t))
563
return self._alternates
565
def _read_alternate_paths(self):
567
f = self.transport.get("info/alternates")
572
for l in f.read().splitlines():
584
# FIXME: Never invalidates.
585
if not self._pack_cache:
586
self._update_pack_cache()
587
return self._pack_cache.values()
589
def _update_pack_cache(self):
590
for pack in self._load_packs():
591
self._pack_cache[pack._basename] = pack
593
def _pack_names(self):
595
f = self.transport.get('info/packs')
597
return self.pack_transport.list_dir(".")
600
for line in f.read().splitlines():
603
(kind, name) = line.split(" ", 1)
609
def _remove_pack(self, pack):
610
self.pack_transport.delete(os.path.basename(pack.index.path))
611
self.pack_transport.delete(pack.data.filename)
613
def _load_packs(self):
615
for name in self._pack_names():
616
if name.startswith("pack-") and name.endswith(".pack"):
618
size = self.pack_transport.stat(name).st_size
619
except TransportNotPossible:
620
f = self.pack_transport.get(name)
621
pd = PackData(name, f, size=len(contents))
623
pd = PackData(name, self.pack_transport.get(name),
625
idxname = name.replace(".pack", ".idx")
626
idx = load_pack_index_file(idxname, self.pack_transport.get(idxname))
627
pack = Pack.from_objects(pd, idx)
628
pack._basename = idxname[:-4]
632
def _iter_loose_objects(self):
633
for base in self.transport.list_dir('.'):
636
for rest in self.transport.list_dir(base):
639
def _split_loose_object(self, sha):
640
return (sha[:2], sha[2:])
642
def _remove_loose_object(self, sha):
643
path = osutils.joinpath(self._split_loose_object(sha))
644
self.transport.delete(path)
646
def _get_loose_object(self, sha):
647
path = osutils.joinpath(self._split_loose_object(sha))
649
return ShaFile.from_file(self.transport.get(path))
653
def add_object(self, obj):
654
"""Add a single object to this object store.
656
:param obj: Object to add
658
(dir, file) = self._split_loose_object(obj.id)
660
self.transport.mkdir(dir)
663
path = osutils.pathjoin(dir, file)
664
if self.transport.has(path):
665
return # Already there, no need to write again
666
self.transport.put_bytes(path, obj.as_legacy_object())
668
def move_in_pack(self, f):
669
"""Move a specific file containing a pack into the pack directory.
671
:note: The file should be on the same file system as the
674
:param path: Path to the pack file.
677
p = PackData("", f, len(f.getvalue()))
678
entries = p.sorted_entries()
679
basename = "pack-%s" % iter_sha1(entry[0] for entry in entries)
680
p._filename = basename + ".pack"
682
self.pack_transport.put_file(basename + ".pack", f)
683
idxfile = self.pack_transport.open_write_stream(basename + ".idx")
685
write_pack_index_v2(idxfile, entries, p.get_stored_checksum())
688
idxfile = self.pack_transport.get(basename + ".idx")
689
idx = load_pack_index_file(basename+".idx", idxfile)
690
final_pack = Pack.from_objects(p, idx)
691
final_pack._basename = basename
692
self._add_known_pack(basename, final_pack)
695
def move_in_thin_pack(self, f):
696
"""Move a specific file containing a pack into the pack directory.
698
:note: The file should be on the same file system as the
701
:param path: Path to the pack file.
704
p = Pack('', resolve_ext_ref=self.get_raw)
705
p._data = PackData.from_file(f, len(f.getvalue()))
707
p._idx_load = lambda: MemoryPackIndex(p.data.sorted_entries(), p.data.get_stored_checksum())
709
pack_sha = p.index.objects_sha1()
711
datafile = self.pack_transport.open_write_stream(
712
"pack-%s.pack" % pack_sha)
714
entries, data_sum = write_pack_objects(datafile, p.pack_tuples())
717
entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
718
idxfile = self.pack_transport.open_write_stream(
719
"pack-%s.idx" % pack_sha)
721
write_pack_index_v2(idxfile, entries, data_sum)
724
# TODO(jelmer): Just add new pack to the cache
725
self._flush_pack_cache()
728
"""Add a new pack to this object store.
730
:return: Fileobject to write to and a commit function to
731
call when the pack is finished.
735
if len(f.getvalue()) > 0:
736
return self.move_in_pack(f)
741
return f, commit, abort
744
def init(cls, transport):
746
transport.mkdir('info')
750
transport.mkdir(PACKDIR)
753
return cls(transport)