objects.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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. try:
  76. return binascii.unhexlify(hex)
  77. except TypeError, exc:
  78. if not isinstance(hex, str):
  79. raise
  80. raise ValueError(exc.message)
  81. def hex_to_filename(path, hex):
  82. """Takes a hex sha and returns its filename relative to the given path."""
  83. dir = hex[:2]
  84. file = hex[2:]
  85. # Check from object dir
  86. return os.path.join(path, dir, file)
  87. def filename_to_hex(filename):
  88. """Takes an object filename and returns its corresponding hex sha."""
  89. # grab the last (up to) two path components
  90. names = filename.rsplit(os.path.sep, 2)[-2:]
  91. errmsg = "Invalid object filename: %s" % filename
  92. assert len(names) == 2, errmsg
  93. base, rest = names
  94. assert len(base) == 2 and len(rest) == 38, errmsg
  95. hex = base + rest
  96. hex_to_sha(hex)
  97. return hex
  98. def object_header(num_type, length):
  99. """Return an object header for the given numeric type and text length."""
  100. return "%s %d\0" % (object_class(num_type).type_name, length)
  101. def serializable_property(name, docstring=None):
  102. """A property that helps tracking whether serialization is necessary.
  103. """
  104. def set(obj, value):
  105. obj._ensure_parsed()
  106. setattr(obj, "_"+name, value)
  107. obj._needs_serialization = True
  108. def get(obj):
  109. obj._ensure_parsed()
  110. return getattr(obj, "_"+name)
  111. return property(get, set, doc=docstring)
  112. def object_class(type):
  113. """Get the object class corresponding to the given type.
  114. :param type: Either a type name string or a numeric type.
  115. :return: The ShaFile subclass corresponding to the given type, or None if
  116. type is not a valid type name/number.
  117. """
  118. return _TYPE_MAP.get(type, None)
  119. def check_hexsha(hex, error_msg):
  120. """Check if a string is a valid hex sha string.
  121. :param hex: Hex string to check
  122. :param error_msg: Error message to use in exception
  123. :raise ObjectFormatException: Raised when the string is not valid
  124. """
  125. try:
  126. hex_to_sha(hex)
  127. except (TypeError, AssertionError, ValueError):
  128. raise ObjectFormatException("%s %s" % (error_msg, hex))
  129. def check_identity(identity, error_msg):
  130. """Check if the specified identity is valid.
  131. This will raise an exception if the identity is not valid.
  132. :param identity: Identity string
  133. :param error_msg: Error message to use in exception
  134. """
  135. email_start = identity.find("<")
  136. email_end = identity.find(">")
  137. if (email_start < 0 or email_end < 0 or email_end <= email_start
  138. or identity.find("<", email_start + 1) >= 0
  139. or identity.find(">", email_end + 1) >= 0
  140. or not identity.endswith(">")):
  141. raise ObjectFormatException(error_msg)
  142. class FixedSha(object):
  143. """SHA object that behaves like hashlib's but is given a fixed value."""
  144. __slots__ = ('_hexsha', '_sha')
  145. def __init__(self, hexsha):
  146. self._hexsha = hexsha
  147. self._sha = hex_to_sha(hexsha)
  148. def digest(self):
  149. """Return the raw SHA digest."""
  150. return self._sha
  151. def hexdigest(self):
  152. """Return the hex SHA digest."""
  153. return self._hexsha
  154. class ShaFile(object):
  155. """A git SHA file."""
  156. __slots__ = ('_needs_parsing', '_chunked_text', '_file', '_path',
  157. '_sha', '_needs_serialization', '_magic')
  158. @staticmethod
  159. def _parse_legacy_object_header(magic, f):
  160. """Parse a legacy object, creating it but not reading the file."""
  161. bufsize = 1024
  162. decomp = zlib.decompressobj()
  163. header = decomp.decompress(magic)
  164. start = 0
  165. end = -1
  166. while end < 0:
  167. extra = f.read(bufsize)
  168. header += decomp.decompress(extra)
  169. magic += extra
  170. end = header.find("\0", start)
  171. start = len(header)
  172. header = header[:end]
  173. type_name, size = header.split(" ", 1)
  174. size = int(size) # sanity check
  175. obj_class = object_class(type_name)
  176. if not obj_class:
  177. raise ObjectFormatException("Not a known type: %s" % type_name)
  178. ret = obj_class()
  179. ret._magic = magic
  180. return ret
  181. def _parse_legacy_object(self, map):
  182. """Parse a legacy object, setting the raw string."""
  183. text = _decompress(map)
  184. header_end = text.find('\0')
  185. if header_end < 0:
  186. raise ObjectFormatException("Invalid object header, no \\0")
  187. self.set_raw_string(text[header_end+1:])
  188. def as_legacy_object_chunks(self):
  189. """Return chunks representing the object in the experimental format.
  190. :return: List of strings
  191. """
  192. compobj = zlib.compressobj()
  193. yield compobj.compress(self._header())
  194. for chunk in self.as_raw_chunks():
  195. yield compobj.compress(chunk)
  196. yield compobj.flush()
  197. def as_legacy_object(self):
  198. """Return string representing the object in the experimental format.
  199. """
  200. return "".join(self.as_legacy_object_chunks())
  201. def as_raw_chunks(self):
  202. """Return chunks with serialization of the object.
  203. :return: List of strings, not necessarily one per line
  204. """
  205. if self._needs_parsing:
  206. self._ensure_parsed()
  207. elif self._needs_serialization:
  208. self._chunked_text = self._serialize()
  209. return self._chunked_text
  210. def as_raw_string(self):
  211. """Return raw string with serialization of the object.
  212. :return: String object
  213. """
  214. return "".join(self.as_raw_chunks())
  215. def __str__(self):
  216. """Return raw string serialization of this object."""
  217. return self.as_raw_string()
  218. def __hash__(self):
  219. """Return unique hash for this object."""
  220. return hash(self.id)
  221. def as_pretty_string(self):
  222. """Return a string representing this object, fit for display."""
  223. return self.as_raw_string()
  224. def _ensure_parsed(self):
  225. if self._needs_parsing:
  226. if not self._chunked_text:
  227. if self._file is not None:
  228. self._parse_file(self._file)
  229. self._file = None
  230. elif self._path is not None:
  231. self._parse_path()
  232. else:
  233. raise AssertionError(
  234. "ShaFile needs either text or filename")
  235. self._deserialize(self._chunked_text)
  236. self._needs_parsing = False
  237. def set_raw_string(self, text):
  238. """Set the contents of this object from a serialized string."""
  239. if type(text) != str:
  240. raise TypeError(text)
  241. self.set_raw_chunks([text])
  242. def set_raw_chunks(self, chunks):
  243. """Set the contents of this object from a list of chunks."""
  244. self._chunked_text = chunks
  245. self._deserialize(chunks)
  246. self._sha = None
  247. self._needs_parsing = False
  248. self._needs_serialization = False
  249. @staticmethod
  250. def _parse_object_header(magic, f):
  251. """Parse a new style object, creating it but not reading the file."""
  252. num_type = (ord(magic[0]) >> 4) & 7
  253. obj_class = object_class(num_type)
  254. if not obj_class:
  255. raise ObjectFormatException("Not a known type %d" % num_type)
  256. ret = obj_class()
  257. ret._magic = magic
  258. return ret
  259. def _parse_object(self, map):
  260. """Parse a new style object, setting self._text."""
  261. # skip type and size; type must have already been determined, and
  262. # we trust zlib to fail if it's otherwise corrupted
  263. byte = ord(map[0])
  264. used = 1
  265. while (byte & 0x80) != 0:
  266. byte = ord(map[used])
  267. used += 1
  268. raw = map[used:]
  269. self.set_raw_string(_decompress(raw))
  270. @classmethod
  271. def _is_legacy_object(cls, magic):
  272. b0, b1 = map(ord, magic)
  273. word = (b0 << 8) + b1
  274. return (b0 & 0x8F) == 0x08 and (word % 31) == 0
  275. @classmethod
  276. def _parse_file_header(cls, f):
  277. magic = f.read(2)
  278. if cls._is_legacy_object(magic):
  279. return cls._parse_legacy_object_header(magic, f)
  280. else:
  281. return cls._parse_object_header(magic, f)
  282. def __init__(self):
  283. """Don't call this directly"""
  284. self._sha = None
  285. self._path = None
  286. self._file = None
  287. self._magic = None
  288. self._chunked_text = []
  289. self._needs_parsing = False
  290. self._needs_serialization = True
  291. def _deserialize(self, chunks):
  292. raise NotImplementedError(self._deserialize)
  293. def _serialize(self):
  294. raise NotImplementedError(self._serialize)
  295. def _parse_path(self):
  296. f = GitFile(self._path, 'rb')
  297. try:
  298. self._parse_file(f)
  299. finally:
  300. f.close()
  301. def _parse_file(self, f):
  302. magic = self._magic
  303. if magic is None:
  304. magic = f.read(2)
  305. map = magic + f.read()
  306. if self._is_legacy_object(magic[:2]):
  307. self._parse_legacy_object(map)
  308. else:
  309. self._parse_object(map)
  310. @classmethod
  311. def from_path(cls, path):
  312. """Open a SHA file from disk."""
  313. f = GitFile(path, 'rb')
  314. try:
  315. obj = cls.from_file(f)
  316. obj._path = path
  317. obj._sha = FixedSha(filename_to_hex(path))
  318. obj._file = None
  319. obj._magic = None
  320. return obj
  321. finally:
  322. f.close()
  323. @classmethod
  324. def from_file(cls, f):
  325. """Get the contents of a SHA file on disk."""
  326. try:
  327. obj = cls._parse_file_header(f)
  328. obj._sha = None
  329. obj._needs_parsing = True
  330. obj._needs_serialization = True
  331. obj._file = f
  332. return obj
  333. except (IndexError, ValueError), e:
  334. raise ObjectFormatException("invalid object header")
  335. @staticmethod
  336. def from_raw_string(type_num, string):
  337. """Creates an object of the indicated type from the raw string given.
  338. :param type_num: The numeric type of the object.
  339. :param string: The raw uncompressed contents.
  340. """
  341. obj = object_class(type_num)()
  342. obj.set_raw_string(string)
  343. return obj
  344. @staticmethod
  345. def from_raw_chunks(type_num, chunks):
  346. """Creates an object of the indicated type from the raw chunks given.
  347. :param type_num: The numeric type of the object.
  348. :param chunks: An iterable of the raw uncompressed contents.
  349. """
  350. obj = object_class(type_num)()
  351. obj.set_raw_chunks(chunks)
  352. return obj
  353. @classmethod
  354. def from_string(cls, string):
  355. """Create a ShaFile from a string."""
  356. obj = cls()
  357. obj.set_raw_string(string)
  358. return obj
  359. def _check_has_member(self, member, error_msg):
  360. """Check that the object has a given member variable.
  361. :param member: the member variable to check for
  362. :param error_msg: the message for an error if the member is missing
  363. :raise ObjectFormatException: with the given error_msg if member is
  364. missing or is None
  365. """
  366. if getattr(self, member, None) is None:
  367. raise ObjectFormatException(error_msg)
  368. def check(self):
  369. """Check this object for internal consistency.
  370. :raise ObjectFormatException: if the object is malformed in some way
  371. :raise ChecksumMismatch: if the object was created with a SHA that does
  372. not match its contents
  373. """
  374. # TODO: if we find that error-checking during object parsing is a
  375. # performance bottleneck, those checks should be moved to the class's
  376. # check() method during optimization so we can still check the object
  377. # when necessary.
  378. old_sha = self.id
  379. try:
  380. self._deserialize(self.as_raw_chunks())
  381. self._sha = None
  382. new_sha = self.id
  383. except Exception, e:
  384. raise ObjectFormatException(e)
  385. if old_sha != new_sha:
  386. raise ChecksumMismatch(new_sha, old_sha)
  387. def _header(self):
  388. return object_header(self.type, self.raw_length())
  389. def raw_length(self):
  390. """Returns the length of the raw string of this object."""
  391. ret = 0
  392. for chunk in self.as_raw_chunks():
  393. ret += len(chunk)
  394. return ret
  395. def _make_sha(self):
  396. ret = make_sha()
  397. ret.update(self._header())
  398. for chunk in self.as_raw_chunks():
  399. ret.update(chunk)
  400. return ret
  401. def sha(self):
  402. """The SHA1 object that is the name of this object."""
  403. if self._sha is None or self._needs_serialization:
  404. # this is a local because as_raw_chunks() overwrites self._sha
  405. new_sha = make_sha()
  406. new_sha.update(self._header())
  407. for chunk in self.as_raw_chunks():
  408. new_sha.update(chunk)
  409. self._sha = new_sha
  410. return self._sha
  411. @property
  412. def id(self):
  413. """The hex SHA of this object."""
  414. return self.sha().hexdigest()
  415. def get_type(self):
  416. """Return the type number for this object class."""
  417. return self.type_num
  418. def set_type(self, type):
  419. """Set the type number for this object class."""
  420. self.type_num = type
  421. # DEPRECATED: use type_num or type_name as needed.
  422. type = property(get_type, set_type)
  423. def __repr__(self):
  424. return "<%s %s>" % (self.__class__.__name__, self.id)
  425. def __ne__(self, other):
  426. return not isinstance(other, ShaFile) or self.id != other.id
  427. def __eq__(self, other):
  428. """Return True if the SHAs of the two objects match.
  429. It doesn't make sense to talk about an order on ShaFiles, so we don't
  430. override the rich comparison methods (__le__, etc.).
  431. """
  432. return isinstance(other, ShaFile) and self.id == other.id
  433. class Blob(ShaFile):
  434. """A Git Blob object."""
  435. __slots__ = ()
  436. type_name = 'blob'
  437. type_num = 3
  438. def __init__(self):
  439. super(Blob, self).__init__()
  440. self._chunked_text = []
  441. self._needs_parsing = False
  442. self._needs_serialization = False
  443. def _get_data(self):
  444. return self.as_raw_string()
  445. def _set_data(self, data):
  446. self.set_raw_string(data)
  447. data = property(_get_data, _set_data,
  448. "The text contained within the blob object.")
  449. def _get_chunked(self):
  450. self._ensure_parsed()
  451. return self._chunked_text
  452. def _set_chunked(self, chunks):
  453. self._chunked_text = chunks
  454. def _serialize(self):
  455. if not self._chunked_text:
  456. self._ensure_parsed()
  457. self._needs_serialization = False
  458. return self._chunked_text
  459. def _deserialize(self, chunks):
  460. self._chunked_text = chunks
  461. chunked = property(_get_chunked, _set_chunked,
  462. "The text within the blob object, as chunks (not necessarily lines).")
  463. @classmethod
  464. def from_path(cls, path):
  465. blob = ShaFile.from_path(path)
  466. if not isinstance(blob, cls):
  467. raise NotBlobError(path)
  468. return blob
  469. def check(self):
  470. """Check this object for internal consistency.
  471. :raise ObjectFormatException: if the object is malformed in some way
  472. """
  473. super(Blob, self).check()
  474. def _parse_tag_or_commit(text):
  475. """Parse tag or commit text.
  476. :param text: the raw text of the tag or commit object.
  477. :return: iterator of tuples of (field, value), one per header line, in the
  478. order read from the text, possibly including duplicates. Includes a
  479. field named None for the freeform tag/commit text.
  480. """
  481. f = StringIO(text)
  482. k = None
  483. v = ""
  484. for l in f:
  485. if l.startswith(" "):
  486. v += l[1:]
  487. else:
  488. if k is not None:
  489. yield (k, v.rstrip("\n"))
  490. if l == "\n":
  491. # Empty line indicates end of headers
  492. break
  493. (k, v) = l.split(" ", 1)
  494. yield (None, f.read())
  495. f.close()
  496. def parse_tag(text):
  497. """Parse a tag object."""
  498. return _parse_tag_or_commit(text)
  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_tag("".join(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_tag("".join(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(text):
  855. return _parse_tag_or_commit(text)
  856. class Commit(ShaFile):
  857. """A git commit object"""
  858. type_name = 'commit'
  859. type_num = 1
  860. __slots__ = ('_parents', '_encoding', '_extra', '_author_timezone_neg_utc',
  861. '_commit_timezone_neg_utc', '_commit_time',
  862. '_author_time', '_author_timezone', '_commit_timezone',
  863. '_author', '_committer', '_parents', '_extra',
  864. '_encoding', '_tree', '_message', '_mergetag')
  865. def __init__(self):
  866. super(Commit, self).__init__()
  867. self._parents = []
  868. self._encoding = None
  869. self._mergetag = []
  870. self._extra = []
  871. self._author_timezone_neg_utc = False
  872. self._commit_timezone_neg_utc = False
  873. @classmethod
  874. def from_path(cls, path):
  875. commit = ShaFile.from_path(path)
  876. if not isinstance(commit, cls):
  877. raise NotCommitError(path)
  878. return commit
  879. def _deserialize(self, chunks):
  880. self._parents = []
  881. self._extra = []
  882. self._author = None
  883. for field, value in parse_commit(''.join(chunks)):
  884. if field == _TREE_HEADER:
  885. self._tree = value
  886. elif field == _PARENT_HEADER:
  887. self._parents.append(value)
  888. elif field == _AUTHOR_HEADER:
  889. self._author, timetext, timezonetext = value.rsplit(" ", 2)
  890. self._author_time = int(timetext)
  891. self._author_timezone, self._author_timezone_neg_utc =\
  892. parse_timezone(timezonetext)
  893. elif field == _COMMITTER_HEADER:
  894. self._committer, timetext, timezonetext = value.rsplit(" ", 2)
  895. self._commit_time = int(timetext)
  896. self._commit_timezone, self._commit_timezone_neg_utc =\
  897. parse_timezone(timezonetext)
  898. elif field == _ENCODING_HEADER:
  899. self._encoding = value
  900. elif field is None:
  901. self._message = value
  902. elif field == _MERGETAG_HEADER:
  903. self._mergetag.append(Tag.from_string(value + "\n"))
  904. else:
  905. self._extra.append((field, value))
  906. def check(self):
  907. """Check this object for internal consistency.
  908. :raise ObjectFormatException: if the object is malformed in some way
  909. """
  910. super(Commit, self).check()
  911. self._check_has_member("_tree", "missing tree")
  912. self._check_has_member("_author", "missing author")
  913. self._check_has_member("_committer", "missing committer")
  914. # times are currently checked when set
  915. for parent in self._parents:
  916. check_hexsha(parent, "invalid parent sha")
  917. check_hexsha(self._tree, "invalid tree sha")
  918. check_identity(self._author, "invalid author")
  919. check_identity(self._committer, "invalid committer")
  920. last = None
  921. for field, _ in parse_commit("".join(self._chunked_text)):
  922. if field == _TREE_HEADER and last is not None:
  923. raise ObjectFormatException("unexpected tree")
  924. elif field == _PARENT_HEADER and last not in (_PARENT_HEADER,
  925. _TREE_HEADER):
  926. raise ObjectFormatException("unexpected parent")
  927. elif field == _AUTHOR_HEADER and last not in (_TREE_HEADER,
  928. _PARENT_HEADER):
  929. raise ObjectFormatException("unexpected author")
  930. elif field == _COMMITTER_HEADER and last != _AUTHOR_HEADER:
  931. raise ObjectFormatException("unexpected committer")
  932. elif field == _ENCODING_HEADER and last != _COMMITTER_HEADER:
  933. raise ObjectFormatException("unexpected encoding")
  934. last = field
  935. # TODO: optionally check for duplicate parents
  936. def _serialize(self):
  937. chunks = []
  938. chunks.append("%s %s\n" % (_TREE_HEADER, self._tree))
  939. for p in self._parents:
  940. chunks.append("%s %s\n" % (_PARENT_HEADER, p))
  941. chunks.append("%s %s %s %s\n" % (
  942. _AUTHOR_HEADER, self._author, str(self._author_time),
  943. format_timezone(self._author_timezone,
  944. self._author_timezone_neg_utc)))
  945. chunks.append("%s %s %s %s\n" % (
  946. _COMMITTER_HEADER, self._committer, str(self._commit_time),
  947. format_timezone(self._commit_timezone,
  948. self._commit_timezone_neg_utc)))
  949. if self.encoding:
  950. chunks.append("%s %s\n" % (_ENCODING_HEADER, self.encoding))
  951. for mergetag in self.mergetag:
  952. mergetag_chunks = mergetag.as_raw_string().split("\n")
  953. chunks.append("%s %s\n" % (_MERGETAG_HEADER, mergetag_chunks[0]))
  954. # Embedded extra header needs leading space
  955. for chunk in mergetag_chunks[1:]:
  956. chunks.append(" %s\n" % chunk)
  957. # No trailing empty line
  958. chunks[-1] = chunks[-1].rstrip(" \n")
  959. for k, v in self.extra:
  960. if "\n" in k or "\n" in v:
  961. raise AssertionError("newline in extra data: %r -> %r" % (k, v))
  962. chunks.append("%s %s\n" % (k, v))
  963. chunks.append("\n") # There must be a new line after the headers
  964. chunks.append(self._message)
  965. return chunks
  966. tree = serializable_property("tree", "Tree that is the state of this commit")
  967. def _get_parents(self):
  968. """Return a list of parents of this commit."""
  969. self._ensure_parsed()
  970. return self._parents
  971. def _set_parents(self, value):
  972. """Set a list of parents of this commit."""
  973. self._ensure_parsed()
  974. self._needs_serialization = True
  975. self._parents = value
  976. parents = property(_get_parents, _set_parents)
  977. def _get_extra(self):
  978. """Return extra settings of this commit."""
  979. self._ensure_parsed()
  980. return self._extra
  981. extra = property(_get_extra)
  982. author = serializable_property("author",
  983. "The name of the author of the commit")
  984. committer = serializable_property("committer",
  985. "The name of the committer of the commit")
  986. message = serializable_property("message",
  987. "The commit message")
  988. commit_time = serializable_property("commit_time",
  989. "The timestamp of the commit. As the number of seconds since the epoch.")
  990. commit_timezone = serializable_property("commit_timezone",
  991. "The zone the commit time is in")
  992. author_time = serializable_property("author_time",
  993. "The timestamp the commit was written. as the number of seconds since the epoch.")
  994. author_timezone = serializable_property("author_timezone",
  995. "Returns the zone the author time is in.")
  996. encoding = serializable_property("encoding",
  997. "Encoding of the commit message.")
  998. mergetag = serializable_property("mergetag",
  999. "Associated signed tag.")
  1000. OBJECT_CLASSES = (
  1001. Commit,
  1002. Tree,
  1003. Blob,
  1004. Tag,
  1005. )
  1006. _TYPE_MAP = {}
  1007. for cls in OBJECT_CLASSES:
  1008. _TYPE_MAP[cls.type_name] = cls
  1009. _TYPE_MAP[cls.type_num] = cls
  1010. # Hold on to the pure-python implementations for testing
  1011. _parse_tree_py = parse_tree
  1012. _sorted_tree_items_py = sorted_tree_items
  1013. try:
  1014. # Try to import C versions
  1015. from dulwich._objects import parse_tree, sorted_tree_items
  1016. except ImportError:
  1017. pass