objects.py 37 KB

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