objects.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. # objects.py -- Access to base git objects
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; version 2
  8. # of the License or (at your option) a later version of the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Access to base git objects."""
  20. from cStringIO import (
  21. StringIO,
  22. )
  23. import mmap
  24. import os
  25. import stat
  26. import time
  27. import zlib
  28. from dulwich.errors import (
  29. NotBlobError,
  30. NotCommitError,
  31. NotTreeError,
  32. )
  33. from dulwich.misc import (
  34. make_sha,
  35. )
  36. BLOB_ID = "blob"
  37. TAG_ID = "tag"
  38. TREE_ID = "tree"
  39. COMMIT_ID = "commit"
  40. PARENT_ID = "parent"
  41. AUTHOR_ID = "author"
  42. COMMITTER_ID = "committer"
  43. OBJECT_ID = "object"
  44. TYPE_ID = "type"
  45. TAGGER_ID = "tagger"
  46. def _decompress(string):
  47. dcomp = zlib.decompressobj()
  48. dcomped = dcomp.decompress(string)
  49. dcomped += dcomp.flush()
  50. return dcomped
  51. def sha_to_hex(sha):
  52. """Takes a string and returns the hex of the sha within"""
  53. hexsha = "".join(["%02x" % ord(c) for c in sha])
  54. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
  55. return hexsha
  56. def hex_to_sha(hex):
  57. """Takes a hex sha and returns a binary sha"""
  58. assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
  59. return ''.join([chr(int(hex[i:i+2], 16)) for i in xrange(0, len(hex), 2)])
  60. def serializable_property(name, docstring=None):
  61. def set(obj, value):
  62. obj._ensure_parsed()
  63. setattr(obj, "_"+name, value)
  64. obj._needs_serialization = True
  65. def get(obj):
  66. obj._ensure_parsed()
  67. return getattr(obj, "_"+name)
  68. return property(get, set, doc=docstring)
  69. class ShaFile(object):
  70. """A git SHA file."""
  71. @classmethod
  72. def _parse_legacy_object(cls, map):
  73. """Parse a legacy object, creating it and setting object._text"""
  74. text = _decompress(map)
  75. object = None
  76. for posstype in type_map.keys():
  77. if text.startswith(posstype):
  78. object = type_map[posstype]()
  79. text = text[len(posstype):]
  80. break
  81. assert object is not None, "%s is not a known object type" % text[:9]
  82. assert text[0] == ' ', "%s is not a space" % text[0]
  83. text = text[1:]
  84. size = 0
  85. i = 0
  86. while text[0] >= '0' and text[0] <= '9':
  87. if i > 0 and size == 0:
  88. assert False, "Size is not in canonical format"
  89. size = (size * 10) + int(text[0])
  90. text = text[1:]
  91. i += 1
  92. object._size = size
  93. assert text[0] == "\0", "Size not followed by null"
  94. text = text[1:]
  95. object.set_raw_string(text)
  96. return object
  97. def as_legacy_object(self):
  98. text = self.as_raw_string()
  99. return zlib.compress("%s %d\0%s" % (self._type, len(text), text))
  100. def as_raw_string(self):
  101. if self._needs_serialization:
  102. self.serialize()
  103. return self._text
  104. def __str__(self):
  105. return self.as_raw_string()
  106. def as_pretty_string(self):
  107. return self.as_raw_string()
  108. def _ensure_parsed(self):
  109. if self._needs_parsing:
  110. self._parse_text()
  111. def set_raw_string(self, text):
  112. if type(text) != str:
  113. raise TypeError(text)
  114. self._text = text
  115. self._sha = None
  116. self._needs_parsing = True
  117. self._needs_serialization = False
  118. @classmethod
  119. def _parse_object(cls, map):
  120. """Parse a new style object , creating it and setting object._text"""
  121. used = 0
  122. byte = ord(map[used])
  123. used += 1
  124. num_type = (byte >> 4) & 7
  125. try:
  126. object = num_type_map[num_type]()
  127. except KeyError:
  128. raise AssertionError("Not a known type: %d" % num_type)
  129. while (byte & 0x80) != 0:
  130. byte = ord(map[used])
  131. used += 1
  132. raw = map[used:]
  133. object.set_raw_string(_decompress(raw))
  134. return object
  135. @classmethod
  136. def _parse_file(cls, map):
  137. word = (ord(map[0]) << 8) + ord(map[1])
  138. if ord(map[0]) == 0x78 and (word % 31) == 0:
  139. return cls._parse_legacy_object(map)
  140. else:
  141. return cls._parse_object(map)
  142. def __init__(self):
  143. """Don't call this directly"""
  144. self._sha = None
  145. def _parse_text(self):
  146. """For subclasses to do initialisation time parsing"""
  147. @classmethod
  148. def from_file(cls, filename):
  149. """Get the contents of a SHA file on disk"""
  150. size = os.path.getsize(filename)
  151. f = open(filename, 'rb')
  152. try:
  153. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  154. shafile = cls._parse_file(map)
  155. return shafile
  156. finally:
  157. f.close()
  158. @classmethod
  159. def from_raw_string(cls, type, string):
  160. """Creates an object of the indicated type from the raw string given.
  161. Type is the numeric type of an object. String is the raw uncompressed
  162. contents.
  163. """
  164. real_class = num_type_map[type]
  165. obj = real_class()
  166. obj.type = type
  167. obj.set_raw_string(string)
  168. return obj
  169. def _header(self):
  170. return "%s %lu\0" % (self._type, len(self.as_raw_string()))
  171. def sha(self):
  172. """The SHA1 object that is the name of this object."""
  173. if self._needs_serialization or self._sha is None:
  174. self._sha = make_sha()
  175. self._sha.update(self._header())
  176. self._sha.update(self.as_raw_string())
  177. return self._sha
  178. @property
  179. def id(self):
  180. return self.sha().hexdigest()
  181. def get_type(self):
  182. return self._num_type
  183. def set_type(self, type):
  184. self._num_type = type
  185. type = property(get_type, set_type)
  186. def __repr__(self):
  187. return "<%s %s>" % (self.__class__.__name__, self.id)
  188. def __eq__(self, other):
  189. """Return true id the sha of the two objects match.
  190. The __le__ etc methods aren't overriden as they make no sense,
  191. certainly at this level.
  192. """
  193. return self.sha().digest() == other.sha().digest()
  194. class Blob(ShaFile):
  195. """A Git Blob object."""
  196. _type = BLOB_ID
  197. _num_type = 3
  198. _needs_serialization = False
  199. _needs_parsing = False
  200. def get_data(self):
  201. return self._text
  202. def set_data(self, data):
  203. self._text = data
  204. data = property(get_data, set_data,
  205. "The text contained within the blob object.")
  206. @classmethod
  207. def from_file(cls, filename):
  208. blob = ShaFile.from_file(filename)
  209. if blob._type != cls._type:
  210. raise NotBlobError(filename)
  211. return blob
  212. @classmethod
  213. def from_string(cls, string):
  214. """Create a blob from a string."""
  215. shafile = cls()
  216. shafile.set_raw_string(string)
  217. return shafile
  218. class Tag(ShaFile):
  219. """A Git Tag object."""
  220. _type = TAG_ID
  221. _num_type = 4
  222. @classmethod
  223. def from_file(cls, filename):
  224. blob = ShaFile.from_file(filename)
  225. if blob._type != cls._type:
  226. raise NotBlobError(filename)
  227. return blob
  228. @classmethod
  229. def from_string(cls, string):
  230. """Create a blob from a string."""
  231. shafile = cls()
  232. shafile.set_raw_string(string)
  233. return shafile
  234. def _parse_text(self):
  235. """Grab the metadata attached to the tag"""
  236. self._tagger = None
  237. f = StringIO(self._text)
  238. for l in f:
  239. l = l.rstrip("\n")
  240. if l == "":
  241. break # empty line indicates end of headers
  242. (field, value) = l.split(" ", 1)
  243. if field == OBJECT_ID:
  244. self._object_sha = value
  245. elif field == TYPE_ID:
  246. self._object_type = type_map[value]
  247. elif field == TAG_ID:
  248. self._name = value
  249. elif field == TAGGER_ID:
  250. sep = value.index("> ")
  251. self._tagger = value[0:sep+1]
  252. (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
  253. try:
  254. self._tag_time = int(timetext)
  255. except ValueError: #Not a unix timestamp
  256. self._tag_time = time.strptime(timetext)
  257. self._timezonetext = parse_timezone(timezonetext)
  258. else:
  259. raise AssertionError("Unknown field %s" % field)
  260. self._message = f.read()
  261. self._needs_parsing = False
  262. def get_object(self):
  263. """Returns the object pointed by this tag, represented as a tuple(type, sha)"""
  264. self._ensure_parsed()
  265. return (self._object_type, self._object_sha)
  266. object = property(get_object)
  267. name = serializable_property("name", "The name of this tag")
  268. tagger = serializable_property("tagger",
  269. "Returns the name of the person who created this tag")
  270. tag_time = serializable_property("tag_time",
  271. "The creation timestamp of the tag. As the number of seconds since the epoch")
  272. message = serializable_property("message", "The message attached to this tag")
  273. def parse_tree(text):
  274. ret = {}
  275. count = 0
  276. while count < len(text):
  277. mode = 0
  278. chr = text[count]
  279. while chr != ' ':
  280. assert chr >= '0' and chr <= '7', "%s is not a valid mode char" % chr
  281. mode = (mode << 3) + (ord(chr) - ord('0'))
  282. count += 1
  283. chr = text[count]
  284. count += 1
  285. chr = text[count]
  286. name = ''
  287. while chr != '\0':
  288. name += chr
  289. count += 1
  290. chr = text[count]
  291. count += 1
  292. chr = text[count]
  293. sha = text[count:count+20]
  294. hexsha = sha_to_hex(sha)
  295. ret[name] = (mode, hexsha)
  296. count = count + 20
  297. return ret
  298. class Tree(ShaFile):
  299. """A Git tree object"""
  300. _type = TREE_ID
  301. _num_type = 2
  302. def __init__(self):
  303. super(Tree, self).__init__()
  304. self._entries = {}
  305. self._needs_parsing = False
  306. self._needs_serialization = True
  307. @classmethod
  308. def from_file(cls, filename):
  309. tree = ShaFile.from_file(filename)
  310. if tree._type != cls._type:
  311. raise NotTreeError(filename)
  312. return tree
  313. def __contains__(self, name):
  314. self._ensure_parsed()
  315. return name in self._entries
  316. def __getitem__(self, name):
  317. self._ensure_parsed()
  318. return self._entries[name]
  319. def __setitem__(self, name, value):
  320. assert isinstance(value, tuple)
  321. assert len(value) == 2
  322. self._ensure_parsed()
  323. self._entries[name] = value
  324. self._needs_serialization = True
  325. def __delitem__(self, name):
  326. self._ensure_parsed()
  327. del self._entries[name]
  328. self._needs_serialization = True
  329. def add(self, mode, name, hexsha):
  330. assert type(mode) == int
  331. assert type(name) == str
  332. assert type(hexsha) == str
  333. self._ensure_parsed()
  334. self._entries[name] = mode, hexsha
  335. self._needs_serialization = True
  336. def entries(self):
  337. """Return a list of tuples describing the tree entries"""
  338. self._ensure_parsed()
  339. # The order of this is different from iteritems() for historical reasons
  340. return [(mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
  341. def iteritems(self):
  342. def cmp_entry((name1, value1), (name2, value2)):
  343. if stat.S_ISDIR(value1[0]):
  344. name1 += "/"
  345. if stat.S_ISDIR(value2[0]):
  346. name2 += "/"
  347. return cmp(name1, name2)
  348. self._ensure_parsed()
  349. for name, entry in sorted(self._entries.iteritems(), cmp=cmp_entry):
  350. yield name, entry[0], entry[1]
  351. def _parse_text(self):
  352. """Grab the entries in the tree"""
  353. self._entries = parse_tree(self._text)
  354. self._needs_parsing = False
  355. def serialize(self):
  356. f = StringIO()
  357. for name, mode, hexsha in self.iteritems():
  358. f.write("%04o %s\0%s" % (mode, name, hex_to_sha(hexsha)))
  359. self._text = f.getvalue()
  360. self._needs_serialization = False
  361. def as_pretty_string(self):
  362. text = ""
  363. for name, mode, hexsha in self.iteritems():
  364. if mode & stat.S_IFDIR:
  365. kind = "tree"
  366. else:
  367. kind = "blob"
  368. text += "%04o %s %s\t%s\n" % (mode, kind, hexsha, name)
  369. return text
  370. def parse_timezone(text):
  371. offset = int(text)
  372. hours = int(offset / 100)
  373. minutes = (offset % 100)
  374. return (hours * 3600) + (minutes * 60)
  375. def format_timezone(offset):
  376. if offset % 60 != 0:
  377. raise ValueError("Unable to handle non-minute offset.")
  378. return '%+03d%02d' % (offset / 3600, (offset / 60) % 60)
  379. class Commit(ShaFile):
  380. """A git commit object"""
  381. _type = COMMIT_ID
  382. _num_type = 1
  383. def __init__(self):
  384. super(Commit, self).__init__()
  385. self._parents = []
  386. self._needs_parsing = False
  387. self._needs_serialization = True
  388. @classmethod
  389. def from_file(cls, filename):
  390. commit = ShaFile.from_file(filename)
  391. if commit._type != cls._type:
  392. raise NotCommitError(filename)
  393. return commit
  394. def _parse_text(self):
  395. self._parents = []
  396. self._author = None
  397. f = StringIO(self._text)
  398. for l in f:
  399. l = l.rstrip("\n")
  400. if l == "":
  401. # Empty line indicates end of headers
  402. break
  403. (field, value) = l.split(" ", 1)
  404. if field == TREE_ID:
  405. self._tree = value
  406. elif field == PARENT_ID:
  407. self._parents.append(value)
  408. elif field == AUTHOR_ID:
  409. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  410. self._author_time = int(timetext)
  411. self._author_timezone = parse_timezone(timezonetext)
  412. elif field == COMMITTER_ID:
  413. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  414. self._commit_time = int(timetext)
  415. self._commit_timezone = parse_timezone(timezonetext)
  416. else:
  417. raise AssertionError("Unknown field %s" % field)
  418. self._message = f.read()
  419. self._needs_parsing = False
  420. def serialize(self):
  421. f = StringIO()
  422. f.write("%s %s\n" % (TREE_ID, self._tree))
  423. for p in self._parents:
  424. f.write("%s %s\n" % (PARENT_ID, p))
  425. f.write("%s %s %s %s\n" % (AUTHOR_ID, self._author, str(self._author_time), format_timezone(self._author_timezone)))
  426. f.write("%s %s %s %s\n" % (COMMITTER_ID, self._committer, str(self._commit_time), format_timezone(self._commit_timezone)))
  427. f.write("\n") # There must be a new line after the headers
  428. f.write(self._message)
  429. self._text = f.getvalue()
  430. self._needs_serialization = False
  431. tree = serializable_property("tree", "Tree that is the state of this commit")
  432. def get_parents(self):
  433. """Return a list of parents of this commit."""
  434. self._ensure_parsed()
  435. return self._parents
  436. def set_parents(self, value):
  437. """Return a list of parents of this commit."""
  438. self._ensure_parsed()
  439. self._needs_serialization = True
  440. self._parents = value
  441. parents = property(get_parents, set_parents)
  442. author = serializable_property("author",
  443. "The name of the author of the commit")
  444. committer = serializable_property("committer",
  445. "The name of the committer of the commit")
  446. message = serializable_property("message",
  447. "The commit message")
  448. commit_time = serializable_property("commit_time",
  449. "The timestamp of the commit. As the number of seconds since the epoch.")
  450. commit_timezone = serializable_property("commit_timezone",
  451. "The zone the commit time is in")
  452. author_time = serializable_property("author_time",
  453. "The timestamp the commit was written. as the number of seconds since the epoch.")
  454. author_timezone = serializable_property("author_timezone",
  455. "Returns the zone the author time is in.")
  456. type_map = {
  457. BLOB_ID : Blob,
  458. TREE_ID : Tree,
  459. COMMIT_ID : Commit,
  460. TAG_ID: Tag,
  461. }
  462. num_type_map = {
  463. 0: None,
  464. 1: Commit,
  465. 2: Tree,
  466. 3: Blob,
  467. 4: Tag,
  468. # 5 Is reserved for further expansion
  469. }
  470. try:
  471. # Try to import C versions
  472. from dulwich._objects import hex_to_sha, sha_to_hex, parse_tree
  473. except ImportError:
  474. pass