objects.py 41 KB

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