/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.1613 by Jelmer Vernooij
Handle encoding better in working tree iter changes.
1
# Copyright (C) 2010-2012 Jelmer Vernooij <jelmer@samba.org>
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
2
#
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.
7
#
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.
12
#
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""A Git repository implementation that uses a Bazaar transport."""
18
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
19
from __future__ import absolute_import
20
0.200.952 by Jelmer Vernooij
Write git pack files rather than loose objects.
21
from cStringIO import StringIO
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
22
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
23
import os
0.200.1576 by Jelmer Vernooij
Merge a bunch of fixes from store-roundtrip-info.
24
import urllib
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
25
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
26
from dulwich.errors import (
27
    NotGitRepository,
0.246.7 by Jelmer Vernooij
more work.
28
    NoIndexPresent,
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
29
    )
0.246.4 by Jelmer Vernooij
more work on transportgit.
30
from dulwich.objects import (
31
    ShaFile,
32
    )
33
from dulwich.object_store import (
34
    PackBasedObjectStore,
35
    PACKDIR,
36
    )
37
from dulwich.pack import (
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
38
    MemoryPackIndex,
0.246.7 by Jelmer Vernooij
more work.
39
    PackData,
0.246.4 by Jelmer Vernooij
more work on transportgit.
40
    Pack,
0.200.936 by Jelmer Vernooij
Test transportgit.
41
    iter_sha1,
0.246.7 by Jelmer Vernooij
more work.
42
    load_pack_index_file,
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
43
    write_pack_data,
0.200.936 by Jelmer Vernooij
Test transportgit.
44
    write_pack_index_v2,
0.246.4 by Jelmer Vernooij
more work on transportgit.
45
    )
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
46
from dulwich.repo import (
47
    BaseRepo,
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
48
    RefsContainer,
0.200.1119 by Jelmer Vernooij
Refactor repository initialization.
49
    BASE_DIRECTORIES,
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
50
    INDEX_FILENAME,
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
51
    OBJECTDIR,
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
52
    REFSDIR,
53
    SYMREF,
54
    check_ref_format,
55
    read_packed_refs_with_peeled,
56
    read_packed_refs,
57
    write_packed_refs,
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
58
    )
59
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
60
from bzrlib import (
61
    transport as _mod_transport,
62
    )
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
63
from bzrlib.errors import (
0.200.933 by Jelmer Vernooij
Allow directories to already exist :-)
64
    FileExists,
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
65
    NoSuchFile,
0.200.946 by Jelmer Vernooij
Fix reading pack files over http.
66
    TransportNotPossible,
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
67
    )
68
69
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
70
class TransportRefsContainer(RefsContainer):
71
    """Refs container that reads refs from a transport."""
72
73
    def __init__(self, transport):
74
        self.transport = transport
75
        self._packed_refs = None
76
        self._peeled_refs = None
77
78
    def __repr__(self):
79
        return "%s(%r)" % (self.__class__.__name__, self.transport)
80
0.257.2 by Jelmer Vernooij
Fix transportgit.
81
    def _ensure_dir_exists(self, path):
82
        for n in range(path.count("/")):
83
            dirname = "/".join(path.split("/")[:n+1])
84
            try:
85
                self.transport.mkdir(dirname)
86
            except FileExists:
87
                pass
88
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
89
    def subkeys(self, base):
90
        keys = set()
91
        try:
92
            iter_files = self.transport.clone(base).iter_files_recursive()
0.200.1576 by Jelmer Vernooij
Merge a bunch of fixes from store-roundtrip-info.
93
            keys.update(("%s/%s" % (base, urllib.unquote(refname))).strip("/") for 
0.257.2 by Jelmer Vernooij
Fix transportgit.
94
                    refname in iter_files if check_ref_format("%s/%s" % (base, refname)))
95
        except (TransportNotPossible, NoSuchFile):
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
96
            pass
97
        for key in self.get_packed_refs():
98
            if key.startswith(base):
99
                keys.add(key[len(base):].strip("/"))
100
        return keys
101
102
    def allkeys(self):
103
        keys = set()
0.200.1387 by Jelmer Vernooij
Avoid using HEAD.
104
        try:
105
            self.transport.get_bytes("HEAD")
106
        except NoSuchFile:
107
            pass
108
        else:
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
109
            keys.add("HEAD")
110
        try:
0.257.2 by Jelmer Vernooij
Fix transportgit.
111
            iter_files = list(self.transport.clone("refs").iter_files_recursive())
112
            for filename in iter_files:
0.200.1576 by Jelmer Vernooij
Merge a bunch of fixes from store-roundtrip-info.
113
                refname = "refs/%s" % urllib.unquote(filename)
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
114
                if check_ref_format(refname):
115
                    keys.add(refname)
0.257.2 by Jelmer Vernooij
Fix transportgit.
116
        except (TransportNotPossible, NoSuchFile):
117
            pass
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
118
        keys.update(self.get_packed_refs())
119
        return keys
120
121
    def get_packed_refs(self):
122
        """Get contents of the packed-refs file.
123
124
        :return: Dictionary mapping ref names to SHA1s
125
126
        :note: Will return an empty dictionary when no packed-refs file is
127
            present.
128
        """
129
        # TODO: invalidate the cache on repacking
130
        if self._packed_refs is None:
131
            # set both to empty because we want _peeled_refs to be
132
            # None if and only if _packed_refs is also None.
133
            self._packed_refs = {}
134
            self._peeled_refs = {}
135
            try:
136
                f = self.transport.get("packed-refs")
137
            except NoSuchFile:
138
                return {}
139
            try:
140
                first_line = iter(f).next().rstrip()
141
                if (first_line.startswith("# pack-refs") and " peeled" in
142
                        first_line):
143
                    for sha, name, peeled in read_packed_refs_with_peeled(f):
144
                        self._packed_refs[name] = sha
145
                        if peeled:
146
                            self._peeled_refs[name] = peeled
147
                else:
148
                    f.seek(0)
149
                    for sha, name in read_packed_refs(f):
150
                        self._packed_refs[name] = sha
151
            finally:
152
                f.close()
153
        return self._packed_refs
154
155
    def get_peeled(self, name):
156
        """Return the cached peeled value of a ref, if available.
157
158
        :param name: Name of the ref to peel
159
        :return: The peeled value of the ref. If the ref is known not point to a
160
            tag, this will be the SHA the ref refers to. If the ref may point to
161
            a tag, but no cached information is available, None is returned.
162
        """
163
        self.get_packed_refs()
164
        if self._peeled_refs is None or name not in self._packed_refs:
165
            # No cache: no peeled refs were read, or this ref is loose
166
            return None
167
        if name in self._peeled_refs:
168
            return self._peeled_refs[name]
169
        else:
170
            # Known not peelable
171
            return self[name]
172
173
    def read_loose_ref(self, name):
174
        """Read a reference file and return its contents.
175
176
        If the reference file a symbolic reference, only read the first line of
177
        the file. Otherwise, only read the first 40 bytes.
178
179
        :param name: the refname to read, relative to refpath
180
        :return: The contents of the ref file, or None if the file does not
181
            exist.
182
        :raises IOError: if any other error occurs
183
        """
184
        try:
185
            f = self.transport.get(name)
186
        except NoSuchFile:
187
            return None
0.200.1572 by Jelmer Vernooij
Fix compatibility for fetching over dumb transport.
188
        f = StringIO(f.read())
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
189
        try:
190
            header = f.read(len(SYMREF))
191
            if header == SYMREF:
192
                # Read only the first line
193
                return header + iter(f).next().rstrip("\r\n")
194
            else:
195
                # Read only the first 40 bytes
196
                return header + f.read(40-len(SYMREF))
197
        finally:
198
            f.close()
199
200
    def _remove_packed_ref(self, name):
201
        if self._packed_refs is None:
202
            return
203
        # reread cached refs from disk, while holding the lock
204
205
        self._packed_refs = None
206
        self.get_packed_refs()
207
208
        if name not in self._packed_refs:
209
            return
210
211
        del self._packed_refs[name]
212
        if name in self._peeled_refs:
213
            del self._peeled_refs[name]
0.200.954 by Jelmer Vernooij
Avoid writing to memory first unless strictly necessary.
214
        f = self.transport.open_write_stream("packed-refs")
215
        try:
216
            write_packed_refs(f, self._packed_refs, self._peeled_refs)
217
        finally:
218
            f.close()
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
219
220
    def set_symbolic_ref(self, name, other):
221
        """Make a ref point at another ref.
222
223
        :param name: Name of the ref to set
224
        :param other: Name of the ref to point at
225
        """
226
        self._check_refname(name)
227
        self._check_refname(other)
0.257.2 by Jelmer Vernooij
Fix transportgit.
228
        self._ensure_dir_exists(name)
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
229
        self.transport.put_bytes(name, SYMREF + other + '\n')
230
231
    def set_if_equals(self, name, old_ref, new_ref):
232
        """Set a refname to new_ref only if it currently equals old_ref.
233
234
        This method follows all symbolic references, and can be used to perform
235
        an atomic compare-and-swap operation.
236
237
        :param name: The refname to set.
238
        :param old_ref: The old sha the refname must refer to, or None to set
239
            unconditionally.
240
        :param new_ref: The new sha the refname will refer to.
241
        :return: True if the set was successful, False otherwise.
242
        """
243
        try:
244
            realname, _ = self._follow(name)
245
        except KeyError:
246
            realname = name
0.257.2 by Jelmer Vernooij
Fix transportgit.
247
        self._ensure_dir_exists(realname)
248
        self.transport.put_bytes(realname, new_ref+"\n")
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
249
        return True
250
251
    def add_if_new(self, name, ref):
252
        """Add a new reference only if it does not already exist.
253
254
        This method follows symrefs, and only ensures that the last ref in the
255
        chain does not exist.
256
257
        :param name: The refname to set.
258
        :param ref: The new sha the refname will refer to.
259
        :return: True if the add was successful, False otherwise.
260
        """
261
        try:
262
            realname, contents = self._follow(name)
263
            if contents is not None:
264
                return False
265
        except KeyError:
266
            realname = name
267
        self._check_refname(realname)
0.257.2 by Jelmer Vernooij
Fix transportgit.
268
        self._ensure_dir_exists(realname)
269
        self.transport.put_bytes(realname, ref+"\n")
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
270
        return True
271
272
    def remove_if_equals(self, name, old_ref):
273
        """Remove a refname only if it currently equals old_ref.
274
275
        This method does not follow symbolic references. It can be used to
276
        perform an atomic compare-and-delete operation.
277
278
        :param name: The refname to delete.
279
        :param old_ref: The old sha the refname must refer to, or None to delete
280
            unconditionally.
281
        :return: True if the delete was successful, False otherwise.
282
        """
283
        self._check_refname(name)
284
        # may only be packed
285
        try:
0.257.2 by Jelmer Vernooij
Fix transportgit.
286
            self.transport.delete(name)
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
287
        except NoSuchFile:
288
            pass
289
        self._remove_packed_ref(name)
290
        return True
291
0.200.1459 by Jelmer Vernooij
Implement TransportRefsContainer.get.
292
    def get(self, name, default=None):
293
        try:
294
            return self[name]
295
        except KeyError:
296
            return default
297
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
298
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
299
class TransportRepo(BaseRepo):
300
0.200.1485 by Jelmer Vernooij
Keep track of refs text when opening bare repository.
301
    def __init__(self, transport, bare, refs_text=None):
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
302
        self.transport = transport
0.200.1387 by Jelmer Vernooij
Avoid using HEAD.
303
        self.bare = bare
304
        if self.bare:
305
            self._controltransport = self.transport
306
        else:
307
            self._controltransport = self.transport.clone('.git')
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
308
        object_store = TransportObjectStore(
309
            self._controltransport.clone(OBJECTDIR))
0.200.1485 by Jelmer Vernooij
Keep track of refs text when opening bare repository.
310
        if refs_text is not None:
311
            from dulwich.repo import InfoRefsContainer # dulwich >= 0.8.2
312
            refs_container = InfoRefsContainer(StringIO(refs_text))
0.200.1572 by Jelmer Vernooij
Fix compatibility for fetching over dumb transport.
313
            try:
314
                head = TransportRefsContainer(self._controltransport).read_loose_ref("HEAD")
315
            except KeyError:
316
                pass
317
            else:
318
                refs_container._refs["HEAD"] = head
0.200.1485 by Jelmer Vernooij
Keep track of refs text when opening bare repository.
319
        else:
320
            refs_container = TransportRefsContainer(self._controltransport)
0.246.8 by Jelmer Vernooij
simplify refs handling.
321
        super(TransportRepo, self).__init__(object_store, 
0.200.1485 by Jelmer Vernooij
Keep track of refs text when opening bare repository.
322
                refs_container)
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
323
324
    def get_named_file(self, path):
325
        """Get a file from the control dir with a specific name.
326
327
        Although the filename should be interpreted as a filename relative to
328
        the control dir in a disk-baked Repo, the object returned need not be
329
        pointing to a file in that location.
330
331
        :param path: The path to the file, relative to the control dir.
332
        :return: An open file object, or None if the file does not exist.
333
        """
334
        try:
335
            return self._controltransport.get(path.lstrip('/'))
336
        except NoSuchFile:
337
            return None
338
0.200.1119 by Jelmer Vernooij
Refactor repository initialization.
339
    def _put_named_file(self, relpath, contents):
340
        self._controltransport.put_bytes(relpath, contents)
341
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
342
    def index_path(self):
343
        """Return the path to the index file."""
344
        return self._controltransport.local_abspath(INDEX_FILENAME)
345
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
346
    def open_index(self):
347
        """Open the index for this repository."""
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
348
        from dulwich.index import Index
349
        if not self.has_index():
350
            raise NoIndexPresent()
351
        return Index(self.index_path())
352
353
    def has_index(self):
0.257.2 by Jelmer Vernooij
Fix transportgit.
354
        """Check if an index is present."""
355
        # Bare repos must never have index files; non-bare repos may have a
356
        # missing index file, which is treated as empty.
357
        return not self.bare
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
358
0.200.1546 by Jelmer Vernooij
Provide get_config.
359
    def get_config(self):
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
360
        from dulwich.config import ConfigFile
361
        try:
362
            return ConfigFile.from_file(self._controltransport.get('config'))
363
        except NoSuchFile:
364
            return ConfigFile()
365
366
    def get_config_stack(self):
367
        from dulwich.config import StackedConfig
0.200.1546 by Jelmer Vernooij
Provide get_config.
368
        backends = []
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
369
        p = self.get_config()
370
        if p is not None:
371
            backends.append(p)
372
            writable = p
373
        else:
374
            writable = None
0.200.1546 by Jelmer Vernooij
Provide get_config.
375
        backends.extend(StackedConfig.default_backends())
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
376
        return StackedConfig(backends, writable=writable)
0.200.1546 by Jelmer Vernooij
Provide get_config.
377
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
378
    def __repr__(self):
0.200.1031 by Jelmer Vernooij
Better __repr__.
379
        return "<%s for %r>" % (self.__class__.__name__, self.transport)
0.246.1 by Jelmer Vernooij
Add TransportRepo class.
380
0.200.1119 by Jelmer Vernooij
Refactor repository initialization.
381
    @classmethod
382
    def init(cls, transport, bare=False):
383
        if not bare:
384
            transport.mkdir(".git")
385
            control_transport = transport.clone(".git")
386
        else:
387
            control_transport = transport
388
        for d in BASE_DIRECTORIES:
389
            control_transport.mkdir("/".join(d))
390
        control_transport.mkdir(OBJECTDIR)
391
        TransportObjectStore.init(control_transport.clone(OBJECTDIR))
0.200.1387 by Jelmer Vernooij
Avoid using HEAD.
392
        ret = cls(transport, bare)
0.200.1119 by Jelmer Vernooij
Refactor repository initialization.
393
        ret.refs.set_symbolic_ref("HEAD", "refs/heads/master")
394
        ret._init_files(bare)
395
        return ret
396
0.246.4 by Jelmer Vernooij
more work on transportgit.
397
398
class TransportObjectStore(PackBasedObjectStore):
399
    """Git-style object store that exists on disk."""
400
401
    def __init__(self, transport):
402
        """Open an object store.
403
404
        :param transport: Transport to open data from
405
        """
406
        super(TransportObjectStore, self).__init__()
407
        self.transport = transport
408
        self.pack_transport = self.transport.clone(PACKDIR)
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
409
        self._alternates = None
0.200.1031 by Jelmer Vernooij
Better __repr__.
410
411
    def __repr__(self):
412
        return "%s(%r)" % (self.__class__.__name__, self.transport)
413
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
414
    @property
415
    def alternates(self):
416
        if self._alternates is not None:
417
            return self._alternates
418
        self._alternates = []
419
        for path in self._read_alternate_paths():
420
            # FIXME: Check path
0.200.1342 by Jelmer Vernooij
Add basic support for alternates.
421
            t = _mod_transport.get_transport_from_path(path)
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
422
            self._alternates.append(self.__class__(t))
423
        return self._alternates
424
425
    def _read_alternate_paths(self):
426
        try:
427
            f = self.transport.get("info/alternates")
428
        except NoSuchFile:
429
            return []
430
        ret = []
431
        try:
0.200.1572 by Jelmer Vernooij
Fix compatibility for fetching over dumb transport.
432
            for l in f.read().splitlines():
0.200.1340 by Jelmer Vernooij
Add basic support for alternates.
433
                if l[0] == "#":
434
                    continue
435
                if os.path.isabs(l):
436
                    continue
437
                ret.append(l)
438
            return ret
439
        finally:
440
            f.close()
441
0.281.2 by William Grant
Fix TransportObjectStore to actually have packs with the new cache dict.
442
    @property
443
    def packs(self):
444
        # FIXME: Never invalidates.
445
        if not self._pack_cache:
446
            self._update_pack_cache()
447
        return self._pack_cache.values()
448
449
    def _update_pack_cache(self):
450
        for pack in self._load_packs():
451
            self._pack_cache[pack._basename] = pack
452
0.256.1 by Jelmer Vernooij
Allow using manual listing for pack contents.
453
    def _pack_names(self):
454
        try:
455
            f = self.transport.get('info/packs')
456
        except NoSuchFile:
457
            return self.pack_transport.list_dir(".")
458
        else:
0.200.935 by Jelmer Vernooij
Allow using manual listing for pack contents.
459
            ret = []
0.200.1572 by Jelmer Vernooij
Fix compatibility for fetching over dumb transport.
460
            for line in f.read().splitlines():
0.256.1 by Jelmer Vernooij
Allow using manual listing for pack contents.
461
                if not line:
462
                    continue
463
                (kind, name) = line.split(" ", 1)
464
                if kind != "P":
465
                    continue
0.200.935 by Jelmer Vernooij
Allow using manual listing for pack contents.
466
                ret.append(name)
467
            return ret
0.256.1 by Jelmer Vernooij
Allow using manual listing for pack contents.
468
0.246.4 by Jelmer Vernooij
more work on transportgit.
469
    def _load_packs(self):
0.246.7 by Jelmer Vernooij
more work.
470
        ret = []
0.256.1 by Jelmer Vernooij
Allow using manual listing for pack contents.
471
        for name in self._pack_names():
0.246.9 by Jelmer Vernooij
Remove unused write code.
472
            if name.startswith("pack-") and name.endswith(".pack"):
0.200.946 by Jelmer Vernooij
Fix reading pack files over http.
473
                try:
474
                    size = self.pack_transport.stat(name).st_size
475
                except TransportNotPossible:
0.257.2 by Jelmer Vernooij
Fix transportgit.
476
                    # FIXME: This reads the whole pack file at once
477
                    f = self.pack_transport.get(name)
478
                    contents = f.read()
479
                    pd = PackData(name, StringIO(contents), size=len(contents))
0.200.946 by Jelmer Vernooij
Fix reading pack files over http.
480
                else:
0.257.2 by Jelmer Vernooij
Fix transportgit.
481
                    pd = PackData(name, self.pack_transport.get(name),
0.200.946 by Jelmer Vernooij
Fix reading pack files over http.
482
                            size=size)
0.246.9 by Jelmer Vernooij
Remove unused write code.
483
                idxname = name.replace(".pack", ".idx")
0.257.2 by Jelmer Vernooij
Fix transportgit.
484
                idx = load_pack_index_file(idxname, self.pack_transport.get(idxname))
485
                pack = Pack.from_objects(pd, idx)
0.281.3 by William Grant
Fix TransportObjectStore with multiple packs, and add test.
486
                pack._basename = idxname[:-5]
0.200.950 by Jelmer Vernooij
Load packs lazily.
487
                ret.append(pack)
0.246.7 by Jelmer Vernooij
more work.
488
        return ret
0.246.4 by Jelmer Vernooij
more work on transportgit.
489
490
    def _iter_loose_objects(self):
491
        for base in self.transport.list_dir('.'):
492
            if len(base) != 2:
493
                continue
494
            for rest in self.transport.list_dir(base):
495
                yield base+rest
496
497
    def _split_loose_object(self, sha):
498
        return (sha[:2], sha[2:])
499
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
500
    def _remove_loose_object(self, sha):
501
        path = '%s/%s' % self._split_loose_object(sha)
0.257.2 by Jelmer Vernooij
Fix transportgit.
502
        self.transport.delete(path)
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
503
0.246.4 by Jelmer Vernooij
more work on transportgit.
504
    def _get_loose_object(self, sha):
505
        path = '%s/%s' % self._split_loose_object(sha)
506
        try:
0.200.903 by Jelmer Vernooij
Fix compatibility with newer versions of Dulwich.
507
            return ShaFile.from_file(self.transport.get(path))
0.246.4 by Jelmer Vernooij
more work on transportgit.
508
        except NoSuchFile:
509
            return None
510
511
    def add_object(self, obj):
512
        """Add a single object to this object store.
513
514
        :param obj: Object to add
515
        """
516
        (dir, file) = self._split_loose_object(obj.id)
0.200.933 by Jelmer Vernooij
Allow directories to already exist :-)
517
        try:
518
            self.transport.mkdir(dir)
519
        except FileExists:
520
            pass
0.246.4 by Jelmer Vernooij
more work on transportgit.
521
        path = "%s/%s" % (dir, file)
522
        if self.transport.has(path):
523
            return # Already there, no need to write again
524
        self.transport.put_bytes(path, obj.as_legacy_object())
525
0.200.937 by Jelmer Vernooij
Avoid using os module in transportgit.
526
    def move_in_pack(self, f):
0.200.936 by Jelmer Vernooij
Test transportgit.
527
        """Move a specific file containing a pack into the pack directory.
528
529
        :note: The file should be on the same file system as the
530
            packs directory.
531
532
        :param path: Path to the pack file.
533
        """
0.200.937 by Jelmer Vernooij
Avoid using os module in transportgit.
534
        f.seek(0)
535
        p = PackData(None, f, len(f.getvalue()))
0.200.936 by Jelmer Vernooij
Test transportgit.
536
        entries = p.sorted_entries()
0.200.937 by Jelmer Vernooij
Avoid using os module in transportgit.
537
        basename = "pack-%s" % iter_sha1(entry[0] for entry in entries)
538
        f.seek(0)
539
        self.pack_transport.put_file(basename + ".pack", f)
0.200.954 by Jelmer Vernooij
Avoid writing to memory first unless strictly necessary.
540
        idxfile = self.pack_transport.open_write_stream(basename + ".idx")
541
        try:
542
            write_pack_index_v2(idxfile, entries, p.get_stored_checksum())
543
        finally:
544
            idxfile.close()
545
        idxfile = self.pack_transport.get(basename + ".idx")
0.200.952 by Jelmer Vernooij
Write git pack files rather than loose objects.
546
        idx = load_pack_index_file(basename+".idx", idxfile)
0.200.937 by Jelmer Vernooij
Avoid using os module in transportgit.
547
        final_pack = Pack.from_objects(p, idx)
0.281.1 by William Grant
Fix compatibility with at least dulwich 0.9.8. Depends on 0.9.6.
548
        self._add_known_pack(basename, final_pack)
0.200.936 by Jelmer Vernooij
Test transportgit.
549
        return final_pack
550
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
551
    def add_thin_pack(self):
552
        """Add a new thin pack to this object store.
553
554
        Thin packs are packs that contain deltas with parents that exist
555
        in a different pack.
556
        """
557
        from cStringIO import StringIO
558
        f = StringIO()
559
        def commit():
560
            if len(f.getvalue()) > 0:
561
                return self.move_in_thin_pack(f)
562
            else:
563
                return None
564
        return f, commit
565
566
    def move_in_thin_pack(self, f):
567
        """Move a specific file containing a pack into the pack directory.
568
569
        :note: The file should be on the same file system as the
570
            packs directory.
571
572
        :param path: Path to the pack file.
573
        """
574
        f.seek(0)
0.200.1298 by Jelmer Vernooij
Fix compatibility with newer versions of dulwich.
575
        data = PackData.from_file(self.get_raw, f, len(f.getvalue()))
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
576
        idx = MemoryPackIndex(data.sorted_entries(), data.get_stored_checksum())
577
        p = Pack.from_objects(data, idx)
578
579
        pack_sha = idx.objects_sha1()
580
0.200.1289 by Jelmer Vernooij
Switch to dulwich 0.8.0.
581
        datafile = self.pack_transport.open_write_stream(
582
                "pack-%s.pack" % pack_sha)
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
583
        try:
0.200.1289 by Jelmer Vernooij
Switch to dulwich 0.8.0.
584
            entries, data_sum = write_pack_data(datafile, p.pack_tuples())
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
585
        finally:
586
            datafile.close()
587
        entries.sort()
0.200.1289 by Jelmer Vernooij
Switch to dulwich 0.8.0.
588
        idxfile = self.pack_transport.open_write_stream(
589
            "pack-%s.idx" % pack_sha)
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
590
        try:
591
            write_pack_index_v2(idxfile, data.sorted_entries(), data_sum)
592
        finally:
593
            idxfile.close()
0.281.4 by William Grant
Update the other _add_known_pack callsite.
594
        basename = "pack-%s" % pack_sha
595
        final_pack = Pack(basename)
596
        self._add_known_pack(basename, final_pack)
0.200.1003 by Jelmer Vernooij
Initial work on supporting move_in_thin_pack.
597
        return final_pack
598
0.246.4 by Jelmer Vernooij
more work on transportgit.
599
    def add_pack(self):
600
        """Add a new pack to this object store. 
601
602
        :return: Fileobject to write to and a commit function to 
603
            call when the pack is finished.
604
        """
0.200.937 by Jelmer Vernooij
Avoid using os module in transportgit.
605
        from cStringIO import StringIO
606
        f = StringIO()
0.200.936 by Jelmer Vernooij
Test transportgit.
607
        def commit():
0.200.937 by Jelmer Vernooij
Avoid using os module in transportgit.
608
            if len(f.getvalue()) > 0:
609
                return self.move_in_pack(f)
0.200.936 by Jelmer Vernooij
Test transportgit.
610
            else:
611
                return None
0.200.1626 by Jelmer Vernooij
Fix compatibility with dulwich 0.9.1.
612
        def abort():
613
            return None
614
        return f, commit, abort
0.200.934 by Jelmer Vernooij
Add init function.
615
616
    @classmethod
617
    def init(cls, transport):
618
        transport.mkdir('info')
619
        transport.mkdir(PACKDIR)
620
        return cls(transport)