objects.py 41 KB

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