objects.py 40 KB

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