/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 dulwich/pack.py

  • Committer: Jelmer Vernooij
  • Date: 2008-12-11 07:30:52 UTC
  • mto: (0.215.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@samba.org-20081211073052-lq0ypg5h3vvyzp3j
Change project name to dulwich everywhere, add assertion.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# pack.py -- For dealing wih packed git objects.
 
2
# Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
 
3
# Copryight (C) 2008 Jelmer Vernooij <jelmer@samba.org>
 
4
# The code is loosely based on that in the sha1_file.c file from git itself,
 
5
# which is Copyright (C) Linus Torvalds, 2005 and distributed under the
 
6
# GPL version 2.
 
7
 
8
# This program is free software; you can redistribute it and/or
 
9
# modify it under the terms of the GNU General Public License
 
10
# as published by the Free Software Foundation; version 2
 
11
# of the License.
 
12
 
13
# This program is distributed in the hope that it will be useful,
 
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
# GNU General Public License for more details.
 
17
 
18
# You should have received a copy of the GNU General Public License
 
19
# along with this program; if not, write to the Free Software
 
20
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
21
# MA  02110-1301, USA.
 
22
 
 
23
"""Classes for dealing with packed git objects.
 
24
 
 
25
A pack is a compact representation of a bunch of objects, stored
 
26
using deltas where possible.
 
27
 
 
28
They have two parts, the pack file, which stores the data, and an index
 
29
that tells you where the data is.
 
30
 
 
31
To find an object you look in all of the index files 'til you find a
 
32
match for the object name. You then use the pointer got from this as
 
33
a pointer in to the corresponding packfile.
 
34
"""
 
35
 
 
36
import mmap
 
37
import os
 
38
import sys
 
39
 
 
40
supports_mmap_offset = (sys.version_info[0] >= 3 or 
 
41
        (sys.version_info[0] == 2 and sys.version_info[1] >= 6))
 
42
 
 
43
from objects import (ShaFile,
 
44
                     _decompress,
 
45
                     )
 
46
 
 
47
hex_to_sha = lambda hex: int(hex, 16)
 
48
 
 
49
MAX_MMAP_SIZE = 256 * 1024 * 1024
 
50
 
 
51
def simple_mmap(f, offset, size, access=mmap.ACCESS_READ):
 
52
    if offset+size > MAX_MMAP_SIZE and not supports_mmap_offset:
 
53
        raise AssertionError("%s is larger than 256 meg, and this version "
 
54
            "of Python does not support the offset argument to mmap().")
 
55
    if supports_mmap_offset:
 
56
        return mmap.mmap(f.fileno(), size, access=access, offset=offset)
 
57
    else:
 
58
        class ArraySkipper(object):
 
59
 
 
60
            def __init__(self, array, offset):
 
61
                self.array = array
 
62
                self.offset = offset
 
63
 
 
64
            def __getslice__(self, i, j):
 
65
                return self.array[i+self.offset:j+self.offset]
 
66
 
 
67
            def __getitem__(self, i):
 
68
                return self.array[i+self.offset]
 
69
 
 
70
        mem = mmap.mmap(f.fileno(), size, access=access)
 
71
        if offset == 0:
 
72
            return mem
 
73
        return ArraySkipper(mem, offset)
 
74
 
 
75
 
 
76
def multi_ord(map, start, count):
 
77
  value = 0
 
78
  for i in range(count):
 
79
    value = value * 0x100 + ord(map[start+i])
 
80
  return value
 
81
 
 
82
class PackIndex(object):
 
83
  """An index in to a packfile.
 
84
 
 
85
  Given a sha id of an object a pack index can tell you the location in the
 
86
  packfile of that object if it has it.
 
87
 
 
88
  To do the loop it opens the file, and indexes first 256 4 byte groups
 
89
  with the first byte of the sha id. The value in the four byte group indexed
 
90
  is the end of the group that shares the same starting byte. Subtract one
 
91
  from the starting byte and index again to find the start of the group.
 
92
  The values are sorted by sha id within the group, so do the math to find
 
93
  the start and end offset and then bisect in to find if the value is present.
 
94
  """
 
95
 
 
96
  header_record_size = 4
 
97
  header_size = 256 * header_record_size
 
98
  index_size = 4
 
99
  sha_bytes = 20
 
100
  record_size = sha_bytes + index_size
 
101
 
 
102
  def __init__(self, filename):
 
103
    """Create a pack index object.
 
104
 
 
105
    Provide it with the name of the index file to consider, and it will map
 
106
    it whenever required.
 
107
    """
 
108
    self._filename = filename
 
109
    assert os.path.exists(filename), "%s is not a pack index" % filename
 
110
    # Take the size now, so it can be checked each time we map the file to
 
111
    # ensure that it hasn't changed.
 
112
    self._size = os.path.getsize(filename)
 
113
    assert self._size > self.header_size, "%s is too small to be a packfile" % \
 
114
        filename
 
115
 
 
116
  def object_index(self, sha):
 
117
    """Return the index in to the corresponding packfile for the object.
 
118
 
 
119
    Given the name of an object it will return the offset that object lives
 
120
    at within the corresponding pack file. If the pack file doesn't have the
 
121
    object then None will be returned.
 
122
    """
 
123
    size = os.path.getsize(self._filename)
 
124
    assert size == self._size, "Pack index %s has changed size, I don't " \
 
125
         "like that" % self._filename
 
126
    f = open(self._filename, 'rb')
 
127
    try:
 
128
      map = simple_mmap(f, 0, size)
 
129
      return self._object_index(map, sha)
 
130
    finally:
 
131
      f.close()
 
132
 
 
133
  def _object_index(self, map, hexsha):
 
134
    """See object_index"""
 
135
    first_byte = hex_to_sha(hexsha[:2])
 
136
    header_offset = self.header_record_size * first_byte
 
137
    start = multi_ord(map, header_offset-self.header_record_size, self.header_record_size)
 
138
    end = multi_ord(map, header_offset, self.header_record_size)
 
139
    sha = hex_to_sha(hexsha)
 
140
    while start < end:
 
141
      i = (start + end)/2
 
142
      offset = self.header_size + (i * self.record_size)
 
143
      file_sha = multi_ord(map, offset + self.index_size, self.sha_bytes)
 
144
      if file_sha == sha:
 
145
        return multi_ord(map, offset, self.index_size)
 
146
      elif file_sha < sha:
 
147
        start = offset + 1
 
148
      else:
 
149
        end = offset - 1
 
150
    return None
 
151
 
 
152
 
 
153
class PackData(object):
 
154
  """The data contained in a packfile.
 
155
 
 
156
  Pack files can be accessed both sequentially for exploding a pack, and
 
157
  directly with the help of an index to retrieve a specific object.
 
158
 
 
159
  The objects within are either complete or a delta aginst another.
 
160
 
 
161
  The header is variable length. If the MSB of each byte is set then it
 
162
  indicates that the subsequent byte is still part of the header.
 
163
  For the first byte the next MS bits are the type, which tells you the type
 
164
  of object, and whether it is a delta. The LS byte is the lowest bits of the
 
165
  size. For each subsequent byte the LS 7 bits are the next MS bits of the
 
166
  size, i.e. the last byte of the header contains the MS bits of the size.
 
167
 
 
168
  For the complete objects the data is stored as zlib deflated data.
 
169
  The size in the header is the uncompressed object size, so to uncompress
 
170
  you need to just keep feeding data to zlib until you get an object back,
 
171
  or it errors on bad data. This is done here by just giving the complete
 
172
  buffer from the start of the deflated object on. This is bad, but until I
 
173
  get mmap sorted out it will have to do.
 
174
 
 
175
  Currently there are no integrity checks done. Also no attempt is made to try
 
176
  and detect the delta case, or a request for an object at the wrong position.
 
177
  It will all just throw a zlib or KeyError.
 
178
  """
 
179
 
 
180
  def __init__(self, filename):
 
181
    """Create a PackData object that represents the pack in the given filename.
 
182
 
 
183
    The file must exist and stay readable until the object is disposed of. It
 
184
    must also stay the same size. It will be mapped whenever needed.
 
185
 
 
186
    Currently there is a restriction on the size of the pack as the python
 
187
    mmap implementation is flawed.
 
188
    """
 
189
    self._filename = filename
 
190
    assert os.path.exists(filename), "%s is not a packfile" % filename
 
191
    self._size = os.path.getsize(filename)
 
192
 
 
193
  def get_object_at(self, offset):
 
194
    """Given an offset in to the packfile return the object that is there.
 
195
 
 
196
    Using the associated index the location of an object can be looked up, and
 
197
    then the packfile can be asked directly for that object using this
 
198
    function.
 
199
 
 
200
    Currently only non-delta objects are supported.
 
201
    """
 
202
    assert isinstance(offset, long) or isinstance(offset, int)
 
203
    size = os.path.getsize(self._filename)
 
204
    assert size == self._size, "Pack data %s has changed size, I don't " \
 
205
         "like that" % self._filename
 
206
    f = open(self._filename, 'rb')
 
207
    try:
 
208
      map = simple_mmap(f, offset, size)
 
209
      return self._get_object_at(map)
 
210
    finally:
 
211
      f.close()
 
212
 
 
213
  def _get_object_at(self, map):
 
214
    first_byte = ord(map[0])
 
215
    sign_extend = first_byte & 0x80
 
216
    type = (first_byte >> 4) & 0x07
 
217
    size = first_byte & 0x0f
 
218
    cur_offset = 0
 
219
    while sign_extend > 0:
 
220
      byte = ord(map[cur_offset+1])
 
221
      sign_extend = byte & 0x80
 
222
      size_part = byte & 0x7f
 
223
      size += size_part << ((cur_offset * 7) + 4)
 
224
      cur_offset += 1
 
225
    raw_base = cur_offset+1
 
226
    # The size is the inflated size, so we have no idea what the deflated size
 
227
    # is, so for now give it as much as we have. It should really iterate
 
228
    # feeding it more data if it doesn't decompress, but as we have the whole
 
229
    # thing then just use it.
 
230
    raw = map[raw_base:]
 
231
    uncomp = _decompress(raw)
 
232
    obj = ShaFile.from_raw_string(type, uncomp)
 
233
    return obj
 
234