objects.py 19 KB

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