objects.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084
  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. type_name = 'blob'
  393. type_num = 3
  394. def __init__(self):
  395. super(Blob, self).__init__()
  396. self._chunked_text = []
  397. self._needs_parsing = False
  398. self._needs_serialization = False
  399. def _get_data(self):
  400. return self.as_raw_string()
  401. def _set_data(self, data):
  402. self.set_raw_string(data)
  403. data = property(_get_data, _set_data,
  404. "The text contained within the blob object.")
  405. def _get_chunked(self):
  406. self._ensure_parsed()
  407. return self._chunked_text
  408. def _set_chunked(self, chunks):
  409. self._chunked_text = chunks
  410. def _serialize(self):
  411. if not self._chunked_text:
  412. self._ensure_parsed()
  413. self._needs_serialization = False
  414. return self._chunked_text
  415. def _deserialize(self, chunks):
  416. self._chunked_text = chunks
  417. chunked = property(_get_chunked, _set_chunked,
  418. "The text within the blob object, as chunks (not necessarily lines).")
  419. @classmethod
  420. def from_path(cls, path):
  421. blob = ShaFile.from_path(path)
  422. if not isinstance(blob, cls):
  423. raise NotBlobError(path)
  424. return blob
  425. def check(self):
  426. """Check this object for internal consistency.
  427. :raise ObjectFormatException: if the object is malformed in some way
  428. """
  429. super(Blob, self).check()
  430. def _parse_tag_or_commit(text):
  431. """Parse tag or commit text.
  432. :param text: the raw text of the tag or commit object.
  433. :return: iterator of tuples of (field, value), one per header line, in the
  434. order read from the text, possibly including duplicates. Includes a
  435. field named None for the freeform tag/commit text.
  436. """
  437. f = StringIO(text)
  438. for l in f:
  439. l = l.rstrip("\n")
  440. if l == "":
  441. # Empty line indicates end of headers
  442. break
  443. yield l.split(" ", 1)
  444. yield (None, f.read())
  445. f.close()
  446. def parse_tag(text):
  447. return _parse_tag_or_commit(text)
  448. class Tag(ShaFile):
  449. """A Git Tag object."""
  450. type_name = 'tag'
  451. type_num = 4
  452. __slots__ = ('_tag_timezone_neg_utc', '_name', '_object_sha',
  453. '_object_class', '_tag_time', '_tag_timezone',
  454. '_tagger', '_message')
  455. def __init__(self):
  456. super(Tag, self).__init__()
  457. self._tag_timezone_neg_utc = False
  458. @classmethod
  459. def from_path(cls, filename):
  460. tag = ShaFile.from_path(filename)
  461. if not isinstance(tag, cls):
  462. raise NotTagError(filename)
  463. return tag
  464. def check(self):
  465. """Check this object for internal consistency.
  466. :raise ObjectFormatException: if the object is malformed in some way
  467. """
  468. super(Tag, self).check()
  469. self._check_has_member("_object_sha", "missing object sha")
  470. self._check_has_member("_object_class", "missing object type")
  471. self._check_has_member("_name", "missing tag name")
  472. if not self._name:
  473. raise ObjectFormatException("empty tag name")
  474. check_hexsha(self._object_sha, "invalid object sha")
  475. if getattr(self, "_tagger", None):
  476. check_identity(self._tagger, "invalid tagger")
  477. last = None
  478. for field, _ in parse_tag("".join(self._chunked_text)):
  479. if field == _OBJECT_HEADER and last is not None:
  480. raise ObjectFormatException("unexpected object")
  481. elif field == _TYPE_HEADER and last != _OBJECT_HEADER:
  482. raise ObjectFormatException("unexpected type")
  483. elif field == _TAG_HEADER and last != _TYPE_HEADER:
  484. raise ObjectFormatException("unexpected tag name")
  485. elif field == _TAGGER_HEADER and last != _TAG_HEADER:
  486. raise ObjectFormatException("unexpected tagger")
  487. last = field
  488. def _serialize(self):
  489. chunks = []
  490. chunks.append("%s %s\n" % (_OBJECT_HEADER, self._object_sha))
  491. chunks.append("%s %s\n" % (_TYPE_HEADER, self._object_class.type_name))
  492. chunks.append("%s %s\n" % (_TAG_HEADER, self._name))
  493. if self._tagger:
  494. if self._tag_time is None:
  495. chunks.append("%s %s\n" % (_TAGGER_HEADER, self._tagger))
  496. else:
  497. chunks.append("%s %s %d %s\n" % (
  498. _TAGGER_HEADER, self._tagger, self._tag_time,
  499. format_timezone(self._tag_timezone,
  500. self._tag_timezone_neg_utc)))
  501. chunks.append("\n") # To close headers
  502. chunks.append(self._message)
  503. return chunks
  504. def _deserialize(self, chunks):
  505. """Grab the metadata attached to the tag"""
  506. self._tagger = None
  507. for field, value in parse_tag("".join(chunks)):
  508. if field == _OBJECT_HEADER:
  509. self._object_sha = value
  510. elif field == _TYPE_HEADER:
  511. obj_class = object_class(value)
  512. if not obj_class:
  513. raise ObjectFormatException("Not a known type: %s" % value)
  514. self._object_class = obj_class
  515. elif field == _TAG_HEADER:
  516. self._name = value
  517. elif field == _TAGGER_HEADER:
  518. try:
  519. sep = value.index("> ")
  520. except ValueError:
  521. self._tagger = value
  522. self._tag_time = None
  523. self._tag_timezone = None
  524. self._tag_timezone_neg_utc = False
  525. else:
  526. self._tagger = value[0:sep+1]
  527. try:
  528. (timetext, timezonetext) = value[sep+2:].rsplit(" ", 1)
  529. self._tag_time = int(timetext)
  530. self._tag_timezone, self._tag_timezone_neg_utc = \
  531. parse_timezone(timezonetext)
  532. except ValueError, e:
  533. raise ObjectFormatException(e)
  534. elif field is None:
  535. self._message = value
  536. else:
  537. raise ObjectFormatException("Unknown field %s" % field)
  538. def _get_object(self):
  539. """Get the object pointed to by this tag.
  540. :return: tuple of (object class, sha).
  541. """
  542. self._ensure_parsed()
  543. return (self._object_class, self._object_sha)
  544. def _set_object(self, value):
  545. self._ensure_parsed()
  546. (self._object_class, self._object_sha) = value
  547. self._needs_serialization = True
  548. object = property(_get_object, _set_object)
  549. name = serializable_property("name", "The name of this tag")
  550. tagger = serializable_property("tagger",
  551. "Returns the name of the person who created this tag")
  552. tag_time = serializable_property("tag_time",
  553. "The creation timestamp of the tag. As the number of seconds since the epoch")
  554. tag_timezone = serializable_property("tag_timezone",
  555. "The timezone that tag_time is in.")
  556. message = serializable_property("message", "The message attached to this tag")
  557. def parse_tree(text):
  558. """Parse a tree text.
  559. :param text: Serialized text to parse
  560. :return: iterator of tuples of (name, mode, sha)
  561. """
  562. count = 0
  563. l = len(text)
  564. while count < l:
  565. mode_end = text.index(' ', count)
  566. mode_text = text[count:mode_end]
  567. assert mode_text[0] != '0'
  568. try:
  569. mode = int(mode_text, 8)
  570. except ValueError:
  571. raise ObjectFormatException("Invalid mode '%s'" % mode_text)
  572. name_end = text.index('\0', mode_end)
  573. name = text[mode_end+1:name_end]
  574. count = name_end+21
  575. sha = text[name_end+1:count]
  576. if len(sha) != 20:
  577. raise ObjectFormatException("Sha has invalid length")
  578. hexsha = sha_to_hex(sha)
  579. yield (name, mode, hexsha)
  580. def serialize_tree(items):
  581. """Serialize the items in a tree to a text.
  582. :param items: Sorted iterable over (name, mode, sha) tuples
  583. :return: Serialized tree text as chunks
  584. """
  585. for name, mode, hexsha in items:
  586. yield "%04o %s\0%s" % (mode, name, hex_to_sha(hexsha))
  587. def sorted_tree_items(entries):
  588. """Iterate over a tree entries dictionary in the order in which
  589. the items would be serialized.
  590. :param entries: Dictionary mapping names to (mode, sha) tuples
  591. :return: Iterator over (name, mode, hexsha)
  592. """
  593. for name, entry in sorted(entries.iteritems(), cmp=cmp_entry):
  594. mode, hexsha = entry
  595. # Stricter type checks than normal to mirror checks in the C version.
  596. mode = int(mode)
  597. if not isinstance(hexsha, str):
  598. raise TypeError('Expected a string for SHA, got %r' % hexsha)
  599. yield name, mode, hexsha
  600. def cmp_entry((name1, value1), (name2, value2)):
  601. """Compare two tree entries."""
  602. if stat.S_ISDIR(value1[0]):
  603. name1 += "/"
  604. if stat.S_ISDIR(value2[0]):
  605. name2 += "/"
  606. return cmp(name1, name2)
  607. class Tree(ShaFile):
  608. """A Git tree object"""
  609. type_name = 'tree'
  610. type_num = 2
  611. __slots__ = ('_entries')
  612. def __init__(self):
  613. super(Tree, self).__init__()
  614. self._entries = {}
  615. @classmethod
  616. def from_path(cls, filename):
  617. tree = ShaFile.from_path(filename)
  618. if not isinstance(tree, cls):
  619. raise NotTreeError(filename)
  620. return tree
  621. def __contains__(self, name):
  622. self._ensure_parsed()
  623. return name in self._entries
  624. def __getitem__(self, name):
  625. self._ensure_parsed()
  626. return self._entries[name]
  627. def __setitem__(self, name, value):
  628. """Set a tree entry by name.
  629. :param name: The name of the entry, as a string.
  630. :param value: A tuple of (mode, hexsha), where mode is the mode of the
  631. entry as an integral type and hexsha is the hex SHA of the entry as
  632. a string.
  633. """
  634. mode, hexsha = value
  635. self._ensure_parsed()
  636. self._entries[name] = (mode, hexsha)
  637. self._needs_serialization = True
  638. def __delitem__(self, name):
  639. self._ensure_parsed()
  640. del self._entries[name]
  641. self._needs_serialization = True
  642. def __len__(self):
  643. self._ensure_parsed()
  644. return len(self._entries)
  645. def __iter__(self):
  646. self._ensure_parsed()
  647. return iter(self._entries)
  648. def add(self, mode, name, hexsha):
  649. """Add an entry to the tree.
  650. :param mode: The mode of the entry as an integral type. Not all possible
  651. modes are supported by git; see check() for details.
  652. :param name: The name of the entry, as a string.
  653. :param hexsha: The hex SHA of the entry as a string.
  654. """
  655. self._ensure_parsed()
  656. self._entries[name] = mode, hexsha
  657. self._needs_serialization = True
  658. def entries(self):
  659. """Return a list of tuples describing the tree entries"""
  660. self._ensure_parsed()
  661. # The order of this is different from iteritems() for historical
  662. # reasons
  663. return [
  664. (mode, name, hexsha) for (name, mode, hexsha) in self.iteritems()]
  665. def iteritems(self):
  666. """Iterate over entries in the order in which they would be serialized.
  667. :return: Iterator over (name, mode, sha) tuples
  668. """
  669. self._ensure_parsed()
  670. return sorted_tree_items(self._entries)
  671. def _deserialize(self, chunks):
  672. """Grab the entries in the tree"""
  673. try:
  674. parsed_entries = parse_tree("".join(chunks))
  675. except ValueError, e:
  676. raise ObjectFormatException(e)
  677. # TODO: list comprehension is for efficiency in the common (small) case;
  678. # if memory efficiency in the large case is a concern, use a genexp.
  679. self._entries = dict([(n, (m, s)) for n, m, s in parsed_entries])
  680. def check(self):
  681. """Check this object for internal consistency.
  682. :raise ObjectFormatException: if the object is malformed in some way
  683. """
  684. super(Tree, self).check()
  685. last = None
  686. allowed_modes = (stat.S_IFREG | 0755, stat.S_IFREG | 0644,
  687. stat.S_IFLNK, stat.S_IFDIR, S_IFGITLINK,
  688. # TODO: optionally exclude as in git fsck --strict
  689. stat.S_IFREG | 0664)
  690. for name, mode, sha in parse_tree("".join(self._chunked_text)):
  691. check_hexsha(sha, 'invalid sha %s' % sha)
  692. if '/' in name or name in ('', '.', '..'):
  693. raise ObjectFormatException('invalid name %s' % name)
  694. if mode not in allowed_modes:
  695. raise ObjectFormatException('invalid mode %06o' % mode)
  696. entry = (name, (mode, sha))
  697. if last:
  698. if cmp_entry(last, entry) > 0:
  699. raise ObjectFormatException('entries not sorted')
  700. if name == last[0]:
  701. raise ObjectFormatException('duplicate entry %s' % name)
  702. last = entry
  703. def _serialize(self):
  704. return list(serialize_tree(self.iteritems()))
  705. def as_pretty_string(self):
  706. text = []
  707. for name, mode, hexsha in self.iteritems():
  708. if mode & stat.S_IFDIR:
  709. kind = "tree"
  710. else:
  711. kind = "blob"
  712. text.append("%04o %s %s\t%s\n" % (mode, kind, hexsha, name))
  713. return "".join(text)
  714. def parse_timezone(text):
  715. offset = int(text)
  716. negative_utc = (offset == 0 and text[0] == '-')
  717. signum = (offset < 0) and -1 or 1
  718. offset = abs(offset)
  719. hours = int(offset / 100)
  720. minutes = (offset % 100)
  721. return signum * (hours * 3600 + minutes * 60), negative_utc
  722. def format_timezone(offset, negative_utc=False):
  723. if offset % 60 != 0:
  724. raise ValueError("Unable to handle non-minute offset.")
  725. if offset < 0 or (offset == 0 and negative_utc):
  726. sign = '-'
  727. else:
  728. sign = '+'
  729. offset = abs(offset)
  730. return '%c%02d%02d' % (sign, offset / 3600, (offset / 60) % 60)
  731. def parse_commit(text):
  732. return _parse_tag_or_commit(text)
  733. class Commit(ShaFile):
  734. """A git commit object"""
  735. type_name = 'commit'
  736. type_num = 1
  737. __slots__ = ('_parents', '_encoding', '_extra', '_author_timezone_neg_utc',
  738. '_commit_timezone_neg_utc', '_commit_time',
  739. '_author_time', '_author_timezone', '_commit_timezone',
  740. '_author', '_committer', '_parents', '_extra',
  741. '_encoding', '_tree', '_message')
  742. def __init__(self):
  743. super(Commit, self).__init__()
  744. self._parents = []
  745. self._encoding = None
  746. self._extra = {}
  747. self._author_timezone_neg_utc = False
  748. self._commit_timezone_neg_utc = False
  749. @classmethod
  750. def from_path(cls, path):
  751. commit = ShaFile.from_path(path)
  752. if not isinstance(commit, cls):
  753. raise NotCommitError(path)
  754. return commit
  755. def _deserialize(self, chunks):
  756. self._parents = []
  757. self._extra = []
  758. self._author = None
  759. for field, value in parse_commit("".join(self._chunked_text)):
  760. if field == _TREE_HEADER:
  761. self._tree = value
  762. elif field == _PARENT_HEADER:
  763. self._parents.append(value)
  764. elif field == _AUTHOR_HEADER:
  765. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  766. self._author_time = int(timetext)
  767. self._author_timezone, self._author_timezone_neg_utc =\
  768. parse_timezone(timezonetext)
  769. elif field == _COMMITTER_HEADER:
  770. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  771. self._commit_time = int(timetext)
  772. self._commit_timezone, self._commit_timezone_neg_utc =\
  773. parse_timezone(timezonetext)
  774. elif field == _ENCODING_HEADER:
  775. self._encoding = value
  776. elif field is None:
  777. self._message = value
  778. else:
  779. self._extra.append((field, value))
  780. def check(self):
  781. """Check this object for internal consistency.
  782. :raise ObjectFormatException: if the object is malformed in some way
  783. """
  784. super(Commit, self).check()
  785. self._check_has_member("_tree", "missing tree")
  786. self._check_has_member("_author", "missing author")
  787. self._check_has_member("_committer", "missing committer")
  788. # times are currently checked when set
  789. for parent in self._parents:
  790. check_hexsha(parent, "invalid parent sha")
  791. check_hexsha(self._tree, "invalid tree sha")
  792. check_identity(self._author, "invalid author")
  793. check_identity(self._committer, "invalid committer")
  794. last = None
  795. for field, _ in parse_commit("".join(self._chunked_text)):
  796. if field == _TREE_HEADER and last is not None:
  797. raise ObjectFormatException("unexpected tree")
  798. elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
  799. _TREE_HEADER):
  800. raise ObjectFormatException("unexpected parent")
  801. elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
  802. _PARENT_HEADER):
  803. raise ObjectFormatException("unexpected author")
  804. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  805. raise ObjectFormatException("unexpected committer")
  806. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  807. raise ObjectFormatException("unexpected encoding")
  808. last = field
  809. # TODO: optionally check for duplicate parents
  810. def _serialize(self):
  811. chunks = []
  812. chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
  813. for p in self._parents:
  814. chunks.append("%s %s\n" % (_PARENT_HEADER, p))
  815. chunks.append("%s %s %s %s\n" % (
  816. _AUTHOR_HEADER, self._author, str(self._author_time),
  817. format_timezone(self._author_timezone,
  818. self._author_timezone_neg_utc)))
  819. chunks.append("%s %s %s %s\n" % (
  820. _COMMITTER_HEADER, self._committer, str(self._commit_time),
  821. format_timezone(self._commit_timezone,
  822. self._commit_timezone_neg_utc)))
  823. if self.encoding:
  824. chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
  825. for k, v in self.extra:
  826. if "\n" in k or "\n" in v:
  827. raise AssertionError("newline in extra data: %r -> %r" % (k, v))
  828. chunks.append("%s %s\n" % (k, v))
  829. chunks.append("\n") # There must be a new line after the headers
  830. chunks.append(self._message)
  831. return chunks
  832. tree = serializable_property("tree", "Tree that is the state of this commit")
  833. def _get_parents(self):
  834. """Return a list of parents of this commit."""
  835. self._ensure_parsed()
  836. return self._parents
  837. def _set_parents(self, value):
  838. """Set a list of parents of this commit."""
  839. self._ensure_parsed()
  840. self._needs_serialization = True
  841. self._parents = value
  842. parents = property(_get_parents, _set_parents)
  843. def _get_extra(self):
  844. """Return extra settings of this commit."""
  845. self._ensure_parsed()
  846. return self._extra
  847. extra = property(_get_extra)
  848. author = serializable_property("author",
  849. "The name of the author of the commit")
  850. committer = serializable_property("committer",
  851. "The name of the committer of the commit")
  852. message = serializable_property("message",
  853. "The commit message")
  854. commit_time = serializable_property("commit_time",
  855. "The timestamp of the commit. As the number of seconds since the epoch.")
  856. commit_timezone = serializable_property("commit_timezone",
  857. "The zone the commit time is in")
  858. author_time = serializable_property("author_time",
  859. "The timestamp the commit was written. as the number of seconds since the epoch.")
  860. author_timezone = serializable_property("author_timezone",
  861. "Returns the zone the author time is in.")
  862. encoding = serializable_property("encoding",
  863. "Encoding of the commit message.")
  864. OBJECT_CLASSES = (
  865. Commit,
  866. Tree,
  867. Blob,
  868. Tag,
  869. )
  870. _TYPE_MAP = {}
  871. for cls in OBJECT_CLASSES:
  872. _TYPE_MAP[cls.type_name] = cls
  873. _TYPE_MAP[cls.type_num] = cls
  874. # Hold on to the pure-python implementations for testing
  875. _parse_tree_py = parse_tree
  876. _sorted_tree_items_py = sorted_tree_items
  877. try:
  878. # Try to import C versions
  879. from dulwich._objects import parse_tree, sorted_tree_items
  880. except ImportError:
  881. pass