2
0

objects.py 20 KB

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