objects.py 45 KB

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