objects.py 20 KB

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