objects.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. raise AssertionError("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 __hash__(self):
  111. return hash(self.id)
  112. def as_pretty_string(self):
  113. return self.as_raw_string()
  114. def _ensure_parsed(self):
  115. if self._needs_parsing:
  116. self._parse_text()
  117. def set_raw_string(self, text):
  118. if type(text) != str:
  119. raise TypeError(text)
  120. self._text = text
  121. self._sha = None
  122. self._needs_parsing = True
  123. self._needs_serialization = False
  124. @classmethod
  125. def _parse_object(cls, map):
  126. """Parse a new style object , creating it and setting object._text"""
  127. used = 0
  128. byte = ord(map[used])
  129. used += 1
  130. num_type = (byte >> 4) & 7
  131. try:
  132. object = num_type_map[num_type]()
  133. except KeyError:
  134. raise AssertionError("Not a known type: %d" % num_type)
  135. while (byte & 0x80) != 0:
  136. byte = ord(map[used])
  137. used += 1
  138. raw = map[used:]
  139. object.set_raw_string(_decompress(raw))
  140. return object
  141. @classmethod
  142. def _parse_file(cls, map):
  143. word = (ord(map[0]) << 8) + ord(map[1])
  144. if ord(map[0]) == 0x78 and (word % 31) == 0:
  145. return cls._parse_legacy_object(map)
  146. else:
  147. return cls._parse_object(map)
  148. def __init__(self):
  149. """Don't call this directly"""
  150. self._sha = None
  151. def _parse_text(self):
  152. """For subclasses to do initialisation time parsing"""
  153. @classmethod
  154. def from_file(cls, filename):
  155. """Get the contents of a SHA file on disk"""
  156. size = os.path.getsize(filename)
  157. f = open(filename, 'rb')
  158. try:
  159. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  160. shafile = cls._parse_file(map)
  161. return shafile
  162. finally:
  163. f.close()
  164. @classmethod
  165. def from_raw_string(cls, type, string):
  166. """Creates an object of the indicated type from the raw string given.
  167. Type is the numeric type of an object. String is the raw uncompressed
  168. contents.
  169. """
  170. real_class = num_type_map[type]
  171. obj = real_class()
  172. obj.type = type
  173. obj.set_raw_string(string)
  174. return obj
  175. def _header(self):
  176. return "%s %lu\0" % (self._type, len(self.as_raw_string()))
  177. def sha(self):
  178. """The SHA1 object that is the name of this object."""
  179. if self._needs_serialization or self._sha is None:
  180. self._sha = make_sha()
  181. self._sha.update(self._header())
  182. self._sha.update(self.as_raw_string())
  183. return self._sha
  184. @property
  185. def id(self):
  186. return self.sha().hexdigest()
  187. def get_type(self):
  188. return self._num_type
  189. def set_type(self, type):
  190. self._num_type = type
  191. type = property(get_type, set_type)
  192. def __repr__(self):
  193. return "<%s %s>" % (self.__class__.__name__, self.id)
  194. def __ne__(self, other):
  195. return self.id != other.id
  196. def __eq__(self, other):
  197. """Return true id the sha of the two objects match.
  198. The __le__ etc methods aren't overriden as they make no sense,
  199. certainly at this level.
  200. """
  201. return self.id == other.id
  202. class Blob(ShaFile):
  203. """A Git Blob object."""
  204. _type = BLOB_ID
  205. _num_type = 3
  206. _needs_serialization = False
  207. _needs_parsing = False
  208. def get_data(self):
  209. return self._text
  210. def set_data(self, data):
  211. self._text = data
  212. data = property(get_data, set_data,
  213. "The text contained within the blob object.")
  214. @classmethod
  215. def from_file(cls, filename):
  216. blob = ShaFile.from_file(filename)
  217. if blob._type != cls._type:
  218. raise NotBlobError(filename)
  219. return blob
  220. @classmethod
  221. def from_string(cls, string):
  222. """Create a blob from a string."""
  223. shafile = cls()
  224. shafile.set_raw_string(string)
  225. return shafile
  226. class Tag(ShaFile):
  227. """A Git Tag object."""
  228. _type = TAG_ID
  229. _num_type = 4
  230. def __init__(self):
  231. super(Tag, self).__init__()
  232. self._needs_parsing = False
  233. self._needs_serialization = True
  234. @classmethod
  235. def from_file(cls, filename):
  236. blob = ShaFile.from_file(filename)
  237. if blob._type != cls._type:
  238. raise NotBlobError(filename)
  239. return blob
  240. @classmethod
  241. def from_string(cls, string):
  242. """Create a blob from a string."""
  243. shafile = cls()
  244. shafile.set_raw_string(string)
  245. return shafile
  246. def serialize(self):
  247. f = StringIO()
  248. f.write("%s %s\n" % (OBJECT_ID, self._object_sha))
  249. f.write("%s %s\n" % (TYPE_ID, num_type_map[self._object_type]._type))
  250. f.write("%s %s\n" % (TAG_ID, self._name))
  251. if self._tagger:
  252. f.write("%s %s %d %s\n" % (TAGGER_ID, self._tagger, self._tag_time, format_timezone(self._tag_timezone)))
  253. f.write("\n") # To close headers
  254. f.write(self._message)
  255. self._text = f.getvalue()
  256. self._needs_serialization = False
  257. def _parse_text(self):
  258. """Grab the metadata attached to the tag"""
  259. self._tagger = None
  260. f = StringIO(self._text)
  261. for l in f:
  262. l = l.rstrip("\n")
  263. if l == "":
  264. break # empty line indicates end of headers
  265. (field, value) = l.split(" ", 1)
  266. if field == OBJECT_ID:
  267. self._object_sha = value
  268. elif field == TYPE_ID:
  269. self._object_type = type_map[value]
  270. elif field == TAG_ID:
  271. self._name = value
  272. elif field == TAGGER_ID:
  273. sep = value.index("> ")
  274. self._tagger = value[0:sep+1]
  275. (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
  276. try:
  277. self._tag_time = int(timetext)
  278. except ValueError: #Not a unix timestamp
  279. self._tag_time = time.strptime(timetext)
  280. self._tag_timezone = parse_timezone(timezonetext)
  281. else:
  282. raise AssertionError("Unknown field %s" % field)
  283. self._message = f.read()
  284. self._needs_parsing = False
  285. def get_object(self):
  286. """Returns the object pointed by this tag, represented as a tuple(type, sha)"""
  287. self._ensure_parsed()
  288. return (self._object_type, self._object_sha)
  289. def set_object(self, value):
  290. self._ensure_parsed()
  291. (self._object_type, self._object_sha) = value
  292. self._needs_serialization = True
  293. object = property(get_object, set_object)
  294. name = serializable_property("name", "The name of this tag")
  295. tagger = serializable_property("tagger",
  296. "Returns the name of the person who created this tag")
  297. tag_time = serializable_property("tag_time",
  298. "The creation timestamp of the tag. As the number of seconds since the epoch")
  299. tag_timezone = serializable_property("tag_timezone",
  300. "The timezone that tag_time is in.")
  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. def cmp_entry((name1, value1), (name2, value2)):
  372. if stat.S_ISDIR(value1[0]):
  373. name1 += "/"
  374. if stat.S_ISDIR(value2[0]):
  375. name2 += "/"
  376. return cmp(name1, name2)
  377. self._ensure_parsed()
  378. for name, entry in sorted(self._entries.iteritems(), cmp=cmp_entry):
  379. yield name, entry[0], entry[1]
  380. def _parse_text(self):
  381. """Grab the entries in the tree"""
  382. self._entries = parse_tree(self._text)
  383. self._needs_parsing = False
  384. def serialize(self):
  385. f = StringIO()
  386. for name, mode, hexsha in self.iteritems():
  387. f.write("%04o %s\0%s" % (mode, name, hex_to_sha(hexsha)))
  388. self._text = f.getvalue()
  389. self._needs_serialization = False
  390. def as_pretty_string(self):
  391. text = ""
  392. for name, mode, hexsha in self.iteritems():
  393. if mode & stat.S_IFDIR:
  394. kind = "tree"
  395. else:
  396. kind = "blob"
  397. text += "%04o %s %s\t%s\n" % (mode, kind, hexsha, name)
  398. return text
  399. def parse_timezone(text):
  400. offset = int(text)
  401. signum = (offset < 0) and -1 or 1
  402. offset = abs(offset)
  403. hours = int(offset / 100)
  404. minutes = (offset % 100)
  405. return signum * (hours * 3600 + minutes * 60)
  406. def format_timezone(offset):
  407. if offset % 60 != 0:
  408. raise ValueError("Unable to handle non-minute offset.")
  409. sign = (offset < 0) and '-' or '+'
  410. offset = abs(offset)
  411. return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
  412. class Commit(ShaFile):
  413. """A git commit object"""
  414. _type = COMMIT_ID
  415. _num_type = 1
  416. def __init__(self):
  417. super(Commit, self).__init__()
  418. self._parents = []
  419. self._encoding = None
  420. self._needs_parsing = False
  421. self._needs_serialization = True
  422. @classmethod
  423. def from_file(cls, filename):
  424. commit = ShaFile.from_file(filename)
  425. if commit._type != cls._type:
  426. raise NotCommitError(filename)
  427. return commit
  428. def _parse_text(self):
  429. self._parents = []
  430. self._author = None
  431. f = StringIO(self._text)
  432. for l in f:
  433. l = l.rstrip("\n")
  434. if l == "":
  435. # Empty line indicates end of headers
  436. break
  437. (field, value) = l.split(" ", 1)
  438. if field == TREE_ID:
  439. self._tree = value
  440. elif field == PARENT_ID:
  441. self._parents.append(value)
  442. elif field == AUTHOR_ID:
  443. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  444. self._author_time = int(timetext)
  445. self._author_timezone = parse_timezone(timezonetext)
  446. elif field == COMMITTER_ID:
  447. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  448. self._commit_time = int(timetext)
  449. self._commit_timezone = parse_timezone(timezonetext)
  450. elif field == ENCODING_ID:
  451. self._encoding = value
  452. else:
  453. raise AssertionError("Unknown field %s" % field)
  454. self._message = f.read()
  455. self._needs_parsing = False
  456. def serialize(self):
  457. f = StringIO()
  458. f.write("%s %s\n" % (TREE_ID, self._tree))
  459. for p in self._parents:
  460. f.write("%s %s\n" % (PARENT_ID, p))
  461. f.write("%s %s %s %s\n" % (AUTHOR_ID, self._author, str(self._author_time), format_timezone(self._author_timezone)))
  462. f.write("%s %s %s %s\n" % (COMMITTER_ID, self._committer, str(self._commit_time), format_timezone(self._commit_timezone)))
  463. if self.encoding:
  464. f.write("%s %s\n" % (ENCODING_ID, self.encoding))
  465. f.write("\n") # There must be a new line after the headers
  466. f.write(self._message)
  467. self._text = f.getvalue()
  468. self._needs_serialization = False
  469. tree = serializable_property("tree", "Tree that is the state of this commit")
  470. def get_parents(self):
  471. """Return a list of parents of this commit."""
  472. self._ensure_parsed()
  473. return self._parents
  474. def set_parents(self, value):
  475. """Return a list of parents of this commit."""
  476. self._ensure_parsed()
  477. self._needs_serialization = True
  478. self._parents = value
  479. parents = property(get_parents, set_parents)
  480. author = serializable_property("author",
  481. "The name of the author of the commit")
  482. committer = serializable_property("committer",
  483. "The name of the committer of the commit")
  484. message = serializable_property("message",
  485. "The commit message")
  486. commit_time = serializable_property("commit_time",
  487. "The timestamp of the commit. As the number of seconds since the epoch.")
  488. commit_timezone = serializable_property("commit_timezone",
  489. "The zone the commit time is in")
  490. author_time = serializable_property("author_time",
  491. "The timestamp the commit was written. as the number of seconds since the epoch.")
  492. author_timezone = serializable_property("author_timezone",
  493. "Returns the zone the author time is in.")
  494. encoding = serializable_property("encoding",
  495. "Encoding of the commit message.")
  496. type_map = {
  497. BLOB_ID : Blob,
  498. TREE_ID : Tree,
  499. COMMIT_ID : Commit,
  500. TAG_ID: Tag,
  501. }
  502. num_type_map = {
  503. 0: None,
  504. 1: Commit,
  505. 2: Tree,
  506. 3: Blob,
  507. 4: Tag,
  508. # 5 Is reserved for further expansion
  509. }
  510. try:
  511. # Try to import C versions
  512. from dulwich._objects import hex_to_sha, sha_to_hex, parse_tree
  513. except ImportError:
  514. pass