objects.py 18 KB

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