objects.py 35 KB

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