objects.py 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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 zlib
  28. from dulwich.errors import (
  29. ChecksumMismatch,
  30. NotBlobError,
  31. NotCommitError,
  32. NotTagError,
  33. NotTreeError,
  34. ObjectFormatException,
  35. )
  36. from dulwich.file import GitFile
  37. from dulwich.misc import (
  38. make_sha,
  39. )
  40. # Header fields for commits
  41. _TREE_HEADER = "tree"
  42. _PARENT_HEADER = "parent"
  43. _AUTHOR_HEADER = "author"
  44. _COMMITTER_HEADER = "committer"
  45. _ENCODING_HEADER = "encoding"
  46. # Header fields for objects
  47. _OBJECT_HEADER = "object"
  48. _TYPE_HEADER = "type"
  49. _TAG_HEADER = "tag"
  50. _TAGGER_HEADER = "tagger"
  51. S_IFGITLINK = 0160000
  52. def S_ISGITLINK(m):
  53. return (stat.S_IFMT(m) == S_IFGITLINK)
  54. def _decompress(string):
  55. dcomp = zlib.decompressobj()
  56. dcomped = dcomp.decompress(string)
  57. dcomped += dcomp.flush()
  58. return dcomped
  59. def sha_to_hex(sha):
  60. """Takes a string and returns the hex of the sha within"""
  61. hexsha = binascii.hexlify(sha)
  62. assert len(hexsha) == 40, "Incorrect length of sha1 string: %d" % hexsha
  63. return hexsha
  64. def hex_to_sha(hex):
  65. """Takes a hex sha and returns a binary sha"""
  66. assert len(hex) == 40, "Incorrent length of hexsha: %s" % hex
  67. return binascii.unhexlify(hex)
  68. def hex_to_filename(path, hex):
  69. """Takes a hex sha and returns its filename relative to the given path."""
  70. dir = hex[:2]
  71. file = hex[2:]
  72. # Check from object dir
  73. return os.path.join(path, dir, file)
  74. def filename_to_hex(filename):
  75. """Takes an object filename and returns its corresponding hex sha."""
  76. # grab the last (up to) two path components
  77. names = filename.rsplit(os.path.sep, 2)[-2:]
  78. errmsg = "Invalid object filename: %s" % filename
  79. assert len(names) == 2, errmsg
  80. base, rest = names
  81. assert len(base) == 2 and len(rest) == 38, errmsg
  82. hex = base + rest
  83. hex_to_sha(hex)
  84. return hex
  85. def object_header(num_type, length):
  86. """Return an object header for the given numeric type and text length."""
  87. return "%s %d\0" % (object_class(num_type).type_name, length)
  88. def serializable_property(name, docstring=None):
  89. def set(obj, value):
  90. obj._ensure_parsed()
  91. setattr(obj, "_"+name, value)
  92. obj._needs_serialization = True
  93. def get(obj):
  94. obj._ensure_parsed()
  95. return getattr(obj, "_"+name)
  96. return property(get, set, doc=docstring)
  97. def object_class(type):
  98. """Get the object class corresponding to the given type.
  99. :param type: Either a type name string or a numeric type.
  100. :return: The ShaFile subclass corresponding to the given type, or None if
  101. type is not a valid type name/number.
  102. """
  103. return _TYPE_MAP.get(type, None)
  104. def check_hexsha(hex, error_msg):
  105. try:
  106. hex_to_sha(hex)
  107. except (TypeError, AssertionError):
  108. raise ObjectFormatException("%s %s" % (error_msg, hex))
  109. def check_identity(identity, error_msg):
  110. """Check if the specified identity is valid.
  111. This will raise an exception if the identity is not valid.
  112. :param identity: Identity string
  113. :param error_msg: Error message to use in exception
  114. """
  115. email_start = identity.find("<")
  116. email_end = identity.find(">")
  117. if (email_start < 0 or email_end < 0 or email_end <= email_start
  118. or identity.find("<", email_start + 1) >= 0
  119. or identity.find(">", email_end + 1) >= 0
  120. or not identity.endswith(">")):
  121. raise ObjectFormatException(error_msg)
  122. class FixedSha(object):
  123. """SHA object that behaves like hashlib's but is given a fixed value."""
  124. def __init__(self, hexsha):
  125. self._hexsha = hexsha
  126. self._sha = hex_to_sha(hexsha)
  127. def digest(self):
  128. return self._sha
  129. def hexdigest(self):
  130. return self._hexsha
  131. class ShaFile(object):
  132. """A git SHA file."""
  133. @staticmethod
  134. def _parse_legacy_object_header(magic, f):
  135. """Parse a legacy object, creating it but not reading the file."""
  136. bufsize = 1024
  137. decomp = zlib.decompressobj()
  138. header = decomp.decompress(magic)
  139. start = 0
  140. end = -1
  141. while end < 0:
  142. header += decomp.decompress(f.read(bufsize))
  143. end = header.find("\0", start)
  144. start = len(header)
  145. header = header[:end]
  146. type_name, size = header.split(" ", 1)
  147. size = int(size) # sanity check
  148. obj_class = object_class(type_name)
  149. if not obj_class:
  150. raise ObjectFormatException("Not a known type: %s" % type_name)
  151. return obj_class()
  152. def _parse_legacy_object(self, f):
  153. """Parse a legacy object, setting the raw string."""
  154. size = os.path.getsize(f.name)
  155. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  156. try:
  157. text = _decompress(map)
  158. finally:
  159. map.close()
  160. header_end = text.find('\0')
  161. if header_end < 0:
  162. raise ObjectFormatException("Invalid object header")
  163. self.set_raw_string(text[header_end+1:])
  164. def as_legacy_object_chunks(self):
  165. compobj = zlib.compressobj()
  166. yield compobj.compress(self._header())
  167. for chunk in self.as_raw_chunks():
  168. yield compobj.compress(chunk)
  169. yield compobj.flush()
  170. def as_legacy_object(self):
  171. return "".join(self.as_legacy_object_chunks())
  172. def as_raw_chunks(self):
  173. if self._needs_parsing:
  174. self._ensure_parsed()
  175. elif self._needs_serialization:
  176. self._chunked_text = self._serialize()
  177. return self._chunked_text
  178. def as_raw_string(self):
  179. return "".join(self.as_raw_chunks())
  180. def __str__(self):
  181. return self.as_raw_string()
  182. def __hash__(self):
  183. return hash(self.id)
  184. def as_pretty_string(self):
  185. return self.as_raw_string()
  186. def _ensure_parsed(self):
  187. if self._needs_parsing:
  188. if not self._chunked_text:
  189. if self._file is not None:
  190. self._parse_file(self._file)
  191. elif self._path is not None:
  192. self._parse_path()
  193. else:
  194. raise AssertionError(
  195. "ShaFile needs either text or filename")
  196. self._deserialize(self._chunked_text)
  197. self._needs_parsing = False
  198. def set_raw_string(self, text):
  199. if type(text) != str:
  200. raise TypeError(text)
  201. self.set_raw_chunks([text])
  202. def set_raw_chunks(self, chunks):
  203. self._chunked_text = chunks
  204. self._deserialize(chunks)
  205. self._sha = None
  206. self._needs_parsing = False
  207. self._needs_serialization = False
  208. @staticmethod
  209. def _parse_object_header(magic, f):
  210. """Parse a new style object, creating it but not reading the file."""
  211. num_type = (ord(magic[0]) >> 4) & 7
  212. obj_class = object_class(num_type)
  213. if not obj_class:
  214. raise ObjectFormatException("Not a known type: %d" % num_type)
  215. return obj_class()
  216. def _parse_object(self, f):
  217. """Parse a new style object, setting self._text."""
  218. size = os.path.getsize(f.name)
  219. map = mmap.mmap(f.fileno(), size, access=mmap.ACCESS_READ)
  220. try:
  221. # skip type and size; type must have already been determined, and
  222. # we trust zlib to fail if it's otherwise corrupted
  223. byte = ord(map[0])
  224. used = 1
  225. while (byte & 0x80) != 0:
  226. byte = ord(map[used])
  227. used += 1
  228. raw = map[used:]
  229. self.set_raw_string(_decompress(raw))
  230. finally:
  231. map.close()
  232. @classmethod
  233. def _is_legacy_object(cls, magic):
  234. b0, b1 = map(ord, magic)
  235. word = (b0 << 8) + b1
  236. return b0 == 0x78 and (word % 31) == 0
  237. @classmethod
  238. def _parse_file_header(cls, f):
  239. magic = f.read(2)
  240. if cls._is_legacy_object(magic):
  241. return cls._parse_legacy_object_header(magic, f)
  242. else:
  243. return cls._parse_object_header(magic, f)
  244. def __init__(self):
  245. """Don't call this directly"""
  246. self._sha = None
  247. self._path = None
  248. self._file = None
  249. self._chunked_text = []
  250. self._needs_parsing = False
  251. self._needs_serialization = True
  252. def _deserialize(self, chunks):
  253. raise NotImplementedError(self._deserialize)
  254. def _serialize(self):
  255. raise NotImplementedError(self._serialize)
  256. def _parse_path(self):
  257. f = GitFile(self._path, 'rb')
  258. try:
  259. self._parse_file(f)
  260. finally:
  261. f.close()
  262. def _parse_file(self, f):
  263. magic = f.read(2)
  264. if self._is_legacy_object(magic):
  265. self._parse_legacy_object(f)
  266. else:
  267. self._parse_object(f)
  268. @classmethod
  269. def from_path(cls, path):
  270. f = GitFile(path, 'rb')
  271. try:
  272. obj = cls.from_file(f)
  273. obj._path = path
  274. obj._sha = FixedSha(filename_to_hex(path))
  275. obj._file = None
  276. return obj
  277. finally:
  278. f.close()
  279. @classmethod
  280. def from_file(cls, f):
  281. """Get the contents of a SHA file on disk."""
  282. try:
  283. obj = cls._parse_file_header(f)
  284. obj._sha = None
  285. obj._needs_parsing = True
  286. obj._needs_serialization = True
  287. obj._file = f
  288. return obj
  289. except (IndexError, ValueError), e:
  290. raise ObjectFormatException("invalid object header")
  291. @staticmethod
  292. def from_raw_string(type_num, string):
  293. """Creates an object of the indicated type from the raw string given.
  294. :param type_num: The numeric type of the object.
  295. :param string: The raw uncompressed contents.
  296. """
  297. obj = object_class(type_num)()
  298. obj.set_raw_string(string)
  299. return obj
  300. @staticmethod
  301. def from_raw_chunks(type_num, chunks):
  302. """Creates an object of the indicated type from the raw chunks given.
  303. :param type_num: The numeric type of the object.
  304. :param chunks: An iterable of the raw uncompressed contents.
  305. """
  306. obj = object_class(type_num)()
  307. obj.set_raw_chunks(chunks)
  308. return obj
  309. @classmethod
  310. def from_string(cls, string):
  311. """Create a ShaFile from a string."""
  312. obj = cls()
  313. obj.set_raw_string(string)
  314. return obj
  315. def _check_has_member(self, member, error_msg):
  316. """Check that the object has a given member variable.
  317. :param member: the member variable to check for
  318. :param error_msg: the message for an error if the member is missing
  319. :raise ObjectFormatException: with the given error_msg if member is
  320. missing or is None
  321. """
  322. if getattr(self, member, None) is None:
  323. raise ObjectFormatException(error_msg)
  324. def check(self):
  325. """Check this object for internal consistency.
  326. :raise ObjectFormatException: if the object is malformed in some way
  327. :raise ChecksumMismatch: if the object was created with a SHA that does
  328. not match its contents
  329. """
  330. # TODO: if we find that error-checking during object parsing is a
  331. # performance bottleneck, those checks should be moved to the class's
  332. # check() method during optimization so we can still check the object
  333. # when necessary.
  334. old_sha = self.id
  335. try:
  336. self._deserialize(self.as_raw_chunks())
  337. self._sha = None
  338. new_sha = self.id
  339. except Exception, e:
  340. raise ObjectFormatException(e)
  341. if old_sha != new_sha:
  342. raise ChecksumMismatch(new_sha, old_sha)
  343. def _header(self):
  344. return object_header(self.type, self.raw_length())
  345. def raw_length(self):
  346. """Returns the length of the raw string of this object."""
  347. ret = 0
  348. for chunk in self.as_raw_chunks():
  349. ret += len(chunk)
  350. return ret
  351. def _make_sha(self):
  352. ret = make_sha()
  353. ret.update(self._header())
  354. for chunk in self.as_raw_chunks():
  355. ret.update(chunk)
  356. return ret
  357. def sha(self):
  358. """The SHA1 object that is the name of this object."""
  359. if self._sha is None or self._needs_serialization:
  360. # this is a local because as_raw_chunks() overwrites self._sha
  361. new_sha = make_sha()
  362. new_sha.update(self._header())
  363. for chunk in self.as_raw_chunks():
  364. new_sha.update(chunk)
  365. self._sha = new_sha
  366. return self._sha
  367. @property
  368. def id(self):
  369. return self.sha().hexdigest()
  370. def get_type(self):
  371. return self.type_num
  372. def set_type(self, type):
  373. self.type_num = type
  374. # DEPRECATED: use type_num or type_name as needed.
  375. type = property(get_type, set_type)
  376. def __repr__(self):
  377. return "<%s %s>" % (self.__class__.__name__, self.id)
  378. def __ne__(self, other):
  379. return self.id != other.id
  380. def __eq__(self, other):
  381. """Return true if the sha of the two objects match.
  382. The __le__ etc methods aren't overriden as they make no sense,
  383. certainly at this level.
  384. """
  385. return self.id == other.id
  386. class Blob(ShaFile):
  387. """A Git Blob object."""
  388. type_name = 'blob'
  389. type_num = 3
  390. def __init__(self):
  391. super(Blob, self).__init__()
  392. self._chunked_text = []
  393. self._needs_parsing = False
  394. self._needs_serialization = False
  395. def _get_data(self):
  396. return self.as_raw_string()
  397. def _set_data(self, data):
  398. self.set_raw_string(data)
  399. data = property(_get_data, _set_data,
  400. "The text contained within the blob object.")
  401. def _get_chunked(self):
  402. self._ensure_parsed()
  403. return self._chunked_text
  404. def _set_chunked(self, chunks):
  405. self._chunked_text = chunks
  406. def _serialize(self):
  407. if not self._chunked_text:
  408. self._ensure_parsed()
  409. self._needs_serialization = False
  410. return self._chunked_text
  411. def _deserialize(self, chunks):
  412. self._chunked_text = chunks
  413. chunked = property(_get_chunked, _set_chunked,
  414. "The text within the blob object, as chunks (not necessarily lines).")
  415. @classmethod
  416. def from_path(cls, path):
  417. blob = ShaFile.from_path(path)
  418. if not isinstance(blob, cls):
  419. raise NotBlobError(path)
  420. return blob
  421. def check(self):
  422. """Check this object for internal consistency.
  423. :raise ObjectFormatException: if the object is malformed in some way
  424. """
  425. super(Blob, self).check()
  426. def _parse_tag_or_commit(text):
  427. """Parse tag or commit text.
  428. :param text: the raw text of the tag or commit object.
  429. :yield: tuples of (field, value), one per header line, in the order read
  430. from the text, possibly including duplicates. Includes a field named
  431. None for the freeform tag/commit text.
  432. """
  433. f = StringIO(text)
  434. for l in f:
  435. l = l.rstrip("\n")
  436. if l == "":
  437. # Empty line indicates end of headers
  438. break
  439. yield l.split(" ", 1)
  440. yield (None, f.read())
  441. f.close()
  442. def parse_tag(text):
  443. return _parse_tag_or_commit(text)
  444. class Tag(ShaFile):
  445. """A Git Tag object."""
  446. type_name = 'tag'
  447. type_num = 4
  448. def __init__(self):
  449. super(Tag, self).__init__()
  450. self._tag_timezone_neg_utc = False
  451. @classmethod
  452. def from_path(cls, filename):
  453. tag = ShaFile.from_path(filename)
  454. if not isinstance(tag, cls):
  455. raise NotTagError(filename)
  456. return tag
  457. def check(self):
  458. """Check this object for internal consistency.
  459. :raise ObjectFormatException: if the object is malformed in some way
  460. """
  461. super(Tag, self).check()
  462. self._check_has_member("_object_sha", "missing object sha")
  463. self._check_has_member("_object_class", "missing object type")
  464. self._check_has_member("_name", "missing tag name")
  465. if not self._name:
  466. raise ObjectFormatException("empty tag name")
  467. check_hexsha(self._object_sha, "invalid object sha")
  468. if getattr(self, "_tagger", None):
  469. check_identity(self._tagger, "invalid tagger")
  470. last = None
  471. for field, _ in parse_tag("".join(self._chunked_text)):
  472. if field == _OBJECT_HEADER and last is not None:
  473. raise ObjectFormatException("unexpected object")
  474. elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
  475. raise ObjectFormatException("unexpected type")
  476. elif field == _TAG_HEADER and last != _TYPE_HEADER:
  477. raise ObjectFormatException("unexpected tag name")
  478. elif field == _TAGGER_HEADER and last != _TAG_HEADER:
  479. raise ObjectFormatException("unexpected tagger")
  480. last = field
  481. def _serialize(self):
  482. chunks = []
  483. chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
  484. chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
  485. chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
  486. if self._tagger:
  487. if self._tag_time is None:
  488. chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
  489. else:
  490. chunks.append("%s %s %d %s\n" % (
  491. _TAGGER_HEADER, self._tagger, self._tag_time,
  492. format_timezone(self._tag_timezone,
  493. self._tag_timezone_neg_utc)))
  494. chunks.append("\n") # To close headers
  495. chunks.append(self._message)
  496. return chunks
  497. def _deserialize(self, chunks):
  498. """Grab the metadata attached to the tag"""
  499. self._tagger = None
  500. for field, value in parse_tag("".join(chunks)):
  501. if field == _OBJECT_HEADER:
  502. self._object_sha = value
  503. elif field == _TYPE_HEADER:
  504. obj_class = object_class(value)
  505. if not obj_class:
  506. raise ObjectFormatException("Not a known type: %s" % value)
  507. self._object_class = obj_class
  508. elif field == _TAG_HEADER:
  509. self._name = value
  510. elif field == _TAGGER_HEADER:
  511. try:
  512. sep = value.index("> ")
  513. except ValueError:
  514. self._tagger = value
  515. self._tag_time = None
  516. self._tag_timezone = None
  517. self._tag_timezone_neg_utc = False
  518. else:
  519. self._tagger = value[0:sep+1]
  520. try:
  521. (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
  522. self._tag_time = int(timetext)
  523. self._tag_timezone, self._tag_timezone_neg_utc = \
  524. parse_timezone(timezonetext)
  525. except ValueError, e:
  526. raise ObjectFormatException(e)
  527. elif field is None:
  528. self._message = value
  529. else:
  530. raise ObjectFormatException("Unknown field %s" % field)
  531. def _get_object(self):
  532. """Get the object pointed to by this tag.
  533. :return: tuple of (object class, sha).
  534. """
  535. self._ensure_parsed()
  536. return (self._object_class, self._object_sha)
  537. def _set_object(self, value):
  538. self._ensure_parsed()
  539. (self._object_class, self._object_sha) = value
  540. self._needs_serialization = True
  541. object = property(_get_object, _set_object)
  542. name = serializable_property("name", "The name of this tag")
  543. tagger = serializable_property("tagger",
  544. "Returns the name of the person who created this tag")
  545. tag_time = serializable_property("tag_time",
  546. "The creation timestamp of the tag. As the number of seconds since the epoch")
  547. tag_timezone = serializable_property("tag_timezone",
  548. "The timezone that tag_time is in.")
  549. message = serializable_property("message", "The message attached to this tag")
  550. def parse_tree(text):
  551. """Parse a tree text.
  552. :param text: Serialized text to parse
  553. :yields: tuples of (name, mode, sha)
  554. """
  555. count = 0
  556. l = len(text)
  557. while count < l:
  558. mode_end = text.index(' ', count)
  559. mode = int(text[count:mode_end], 8)
  560. name_end = text.index('\0', mode_end)
  561. name = text[mode_end+1:name_end]
  562. count = name_end+21
  563. sha = text[name_end+1:count]
  564. yield (name, mode, sha_to_hex(sha))
  565. def serialize_tree(items):
  566. """Serialize the items in a tree to a text.
  567. :param items: Sorted iterable over (name, mode, sha) tuples
  568. :return: Serialized tree text as chunks
  569. """
  570. for name, mode, hexsha in items:
  571. yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
  572. def sorted_tree_items(entries):
  573. """Iterate over a tree entries dictionary in the order in which
  574. the items would be serialized.
  575. :param entries: Dictionary mapping names to (mode, sha) tuples
  576. :return: Iterator over (name, mode, sha)
  577. """
  578. for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
  579. yield name, entry[0], entry[1]
  580. def cmp_entry((name1, value1), (name2, value2)):
  581. """Compare two tree entries."""
  582. if stat.S_ISDIR(value1[0]):
  583. name1 += "/"
  584. if stat.S_ISDIR(value2[0]):
  585. name2 += "/"
  586. return cmp(name1, name2)
  587. class Tree(ShaFile):
  588. """A Git tree object"""
  589. type_name = 'tree'
  590. type_num = 2
  591. def __init__(self):
  592. super(Tree, self).__init__()
  593. self._entries = {}
  594. @classmethod
  595. def from_path(cls, filename):
  596. tree = ShaFile.from_path(filename)
  597. if not isinstance(tree, cls):
  598. raise NotTreeError(filename)
  599. return tree
  600. def __contains__(self, name):
  601. self._ensure_parsed()
  602. return name in self._entries
  603. def __getitem__(self, name):
  604. self._ensure_parsed()
  605. return self._entries[name]
  606. def __setitem__(self, name, value):
  607. """Set a tree entry by name.
  608. :param name: The name of the entry, as a string.
  609. :param value: A tuple of (mode, hexsha), where mode is the mode of the
  610. entry as an integral type and hexsha is the hex SHA of the entry as
  611. a string.
  612. """
  613. mode, hexsha = value
  614. self._ensure_parsed()
  615. self._entries[name] = (mode, hexsha)
  616. self._needs_serialization = True
  617. def __delitem__(self, name):
  618. self._ensure_parsed()
  619. del self._entries[name]
  620. self._needs_serialization = True
  621. def __len__(self):
  622. self._ensure_parsed()
  623. return len(self._entries)
  624. def __iter__(self):
  625. self._ensure_parsed()
  626. return iter(self._entries)
  627. def add(self, mode, name, hexsha):
  628. """Add an entry to the tree.
  629. :param mode: The mode of the entry as an integral type. Not all possible
  630. modes are supported by git; see check() for details.
  631. :param name: The name of the entry, as a string.
  632. :param hexsha: The hex SHA of the entry as a string.
  633. """
  634. self._ensure_parsed()
  635. self._entries[name] = mode, hexsha
  636. self._needs_serialization = True
  637. def entries(self):
  638. """Return a list of tuples describing the tree entries"""
  639. self._ensure_parsed()
  640. # The order of this is different from iteritems() for historical
  641. # reasons
  642. return [
  643. (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
  644. def iteritems(self):
  645. """Iterate over entries in the order in which they would be serialized.
  646. :return: Iterator over (name, mode, sha) tuples
  647. """
  648. self._ensure_parsed()
  649. return sorted_tree_items(self._entries)
  650. def _deserialize(self, chunks):
  651. """Grab the entries in the tree"""
  652. try:
  653. parsed_entries = parse_tree("".join(chunks))
  654. except ValueError, e:
  655. raise ObjectFormatException(e)
  656. # TODO: list comprehension is for efficiency in the common (small) case;
  657. # if memory efficiency in the large case is a concern, use a genexp.
  658. self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries])
  659. def check(self):
  660. """Check this object for internal consistency.
  661. :raise ObjectFormatException: if the object is malformed in some way
  662. """
  663. super(Tree, self).check()
  664. last = None
  665. allowed_modes = (stat.S_IFREG | 0755, stat.S_IFREG | 0644,
  666. stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK,
  667. # TODO: optionally exclude as in git fsck --strict
  668. stat.S_IFREG | 0664)
  669. for name, mode, sha in parse_tree("".join(self._chunked_text)):
  670. check_hexsha(sha, 'invalid sha %s' % sha)
  671. if '/' in name or name in ('', '.', '..'):
  672. raise ObjectFormatException('invalid name %s' % name)
  673. if mode not in allowed_modes:
  674. raise ObjectFormatException('invalid mode %06o' % mode)
  675. entry = (name, (mode, sha))
  676. if last:
  677. if cmp_entry(last, entry) > 0:
  678. raise ObjectFormatException('entries not sorted')
  679. if name == last[0]:
  680. raise ObjectFormatException('duplicate entry %s' % name)
  681. last = entry
  682. def _serialize(self):
  683. return list(serialize_tree(self.iteritems()))
  684. def as_pretty_string(self):
  685. text = []
  686. for name, mode, hexsha in self.iteritems():
  687. if mode & stat.S_IFDIR:
  688. kind = "tree"
  689. else:
  690. kind = "blob"
  691. text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
  692. return "".join(text)
  693. def parse_timezone(text):
  694. offset = int(text)
  695. negative_utc = (offset == 0 and text[0] == '-')
  696. signum = (offset < 0) and -1 or 1
  697. offset = abs(offset)
  698. hours = int(offset / 100)
  699. minutes = (offset % 100)
  700. return signum * (hours * 3600 + minutes * 60), negative_utc
  701. def format_timezone(offset, negative_utc=False):
  702. if offset % 60 != 0:
  703. raise ValueError("Unable to handle non-minute offset.")
  704. if offset < 0 or (offset == 0 and negative_utc):
  705. sign = '-'
  706. else:
  707. sign = '+'
  708. offset = abs(offset)
  709. return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
  710. def parse_commit(text):
  711. return _parse_tag_or_commit(text)
  712. class Commit(ShaFile):
  713. """A git commit object"""
  714. type_name = 'commit'
  715. type_num = 1
  716. def __init__(self):
  717. super(Commit, self).__init__()
  718. self._parents = []
  719. self._encoding = None
  720. self._extra = {}
  721. self._author_timezone_neg_utc = False
  722. self._commit_timezone_neg_utc = False
  723. @classmethod
  724. def from_path(cls, path):
  725. commit = ShaFile.from_path(path)
  726. if not isinstance(commit, cls):
  727. raise NotCommitError(path)
  728. return commit
  729. def _deserialize(self, chunks):
  730. self._parents = []
  731. self._extra = []
  732. self._author = None
  733. for field, value in parse_commit("".join(self._chunked_text)):
  734. if field == _TREE_HEADER:
  735. self._tree = value
  736. elif field == _PARENT_HEADER:
  737. self._parents.append(value)
  738. elif field == _AUTHOR_HEADER:
  739. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  740. self._author_time = int(timetext)
  741. self._author_timezone, self._author_timezone_neg_utc =\
  742. parse_timezone(timezonetext)
  743. elif field == _COMMITTER_HEADER:
  744. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  745. self._commit_time = int(timetext)
  746. self._commit_timezone, self._commit_timezone_neg_utc =\
  747. parse_timezone(timezonetext)
  748. elif field == _ENCODING_HEADER:
  749. self._encoding = value
  750. elif field is None:
  751. self._message = value
  752. else:
  753. self._extra.append((field, value))
  754. def check(self):
  755. """Check this object for internal consistency.
  756. :raise ObjectFormatException: if the object is malformed in some way
  757. """
  758. super(Commit, self).check()
  759. self._check_has_member("_tree", "missing tree")
  760. self._check_has_member("_author", "missing author")
  761. self._check_has_member("_committer", "missing committer")
  762. # times are currently checked when set
  763. for parent in self._parents:
  764. check_hexsha(parent, "invalid parent sha")
  765. check_hexsha(self._tree, "invalid tree sha")
  766. check_identity(self._author, "invalid author")
  767. check_identity(self._committer, "invalid committer")
  768. last = None
  769. for field, _ in parse_commit("".join(self._chunked_text)):
  770. if field == _TREE_HEADER and last is not None:
  771. raise ObjectFormatException("unexpected tree")
  772. elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
  773. _TREE_HEADER):
  774. raise ObjectFormatException("unexpected parent")
  775. elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
  776. _PARENT_HEADER):
  777. raise ObjectFormatException("unexpected author")
  778. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  779. raise ObjectFormatException("unexpected committer")
  780. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  781. raise ObjectFormatException("unexpected encoding")
  782. last = field
  783. # TODO: optionally check for duplicate parents
  784. def _serialize(self):
  785. chunks = []
  786. chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
  787. for p in self._parents:
  788. chunks.append("%s %s\n" % (_PARENT_HEADER, p))
  789. chunks.append("%s %s %s %s\n" % (
  790. _AUTHOR_HEADER, self._author, str(self._author_time),
  791. format_timezone(self._author_timezone,
  792. self._author_timezone_neg_utc)))
  793. chunks.append("%s %s %s %s\n" % (
  794. _COMMITTER_HEADER, self._committer, str(self._commit_time),
  795. format_timezone(self._commit_timezone,
  796. self._commit_timezone_neg_utc)))
  797. if self.encoding:
  798. chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
  799. for k, v in self.extra:
  800. if "\n" in k or "\n" in v:
  801. raise AssertionError("newline in extra data: %r -> %r" % (k, v))
  802. chunks.append("%s %s\n" % (k, v))
  803. chunks.append("\n") # There must be a new line after the headers
  804. chunks.append(self._message)
  805. return chunks
  806. tree = serializable_property("tree", "Tree that is the state of this commit")
  807. def _get_parents(self):
  808. """Return a list of parents of this commit."""
  809. self._ensure_parsed()
  810. return self._parents
  811. def _set_parents(self, value):
  812. """Set a list of parents of this commit."""
  813. self._ensure_parsed()
  814. self._needs_serialization = True
  815. self._parents = value
  816. parents = property(_get_parents, _set_parents)
  817. def _get_extra(self):
  818. """Return extra settings of this commit."""
  819. self._ensure_parsed()
  820. return self._extra
  821. extra = property(_get_extra)
  822. author = serializable_property("author",
  823. "The name of the author of the commit")
  824. committer = serializable_property("committer",
  825. "The name of the committer of the commit")
  826. message = serializable_property("message",
  827. "The commit message")
  828. commit_time = serializable_property("commit_time",
  829. "The timestamp of the commit. As the number of seconds since the epoch.")
  830. commit_timezone = serializable_property("commit_timezone",
  831. "The zone the commit time is in")
  832. author_time = serializable_property("author_time",
  833. "The timestamp the commit was written. as the number of seconds since the epoch.")
  834. author_timezone = serializable_property("author_timezone",
  835. "Returns the zone the author time is in.")
  836. encoding = serializable_property("encoding",
  837. "Encoding of the commit message.")
  838. OBJECT_CLASSES = (
  839. Commit,
  840. Tree,
  841. Blob,
  842. Tag,
  843. )
  844. _TYPE_MAP = {}
  845. for cls in OBJECT_CLASSES:
  846. _TYPE_MAP[cls.type_name] = cls
  847. _TYPE_MAP[cls.type_num] = cls
  848. # Hold on to the pure-python implementations for testing
  849. _parse_tree_py = parse_tree
  850. _sorted_tree_items_py = sorted_tree_items
  851. try:
  852. # Try to import C versions
  853. from dulwich._objects import parse_tree, sorted_tree_items
  854. except ImportError:
  855. pass