objects.py 44 KB

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