objects.py 17 KB

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