2
0

object_store.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. # and others
  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. """Git object store interfaces and implementation."""
  22. from io import BytesIO
  23. import errno
  24. import os
  25. import stat
  26. import sys
  27. import tempfile
  28. from dulwich.diff_tree import (
  29. tree_changes,
  30. walk_trees,
  31. )
  32. from dulwich.errors import (
  33. NotTreeError,
  34. )
  35. from dulwich.file import GitFile
  36. from dulwich.objects import (
  37. Commit,
  38. ShaFile,
  39. Tag,
  40. Tree,
  41. ZERO_SHA,
  42. hex_to_sha,
  43. sha_to_hex,
  44. hex_to_filename,
  45. S_ISGITLINK,
  46. object_class,
  47. )
  48. from dulwich.pack import (
  49. Pack,
  50. PackData,
  51. PackInflater,
  52. PackFileDisappeared,
  53. iter_sha1,
  54. pack_objects_to_data,
  55. write_pack_header,
  56. write_pack_index_v2,
  57. write_pack_data,
  58. write_pack_object,
  59. compute_file_sha,
  60. PackIndexer,
  61. PackStreamCopier,
  62. )
  63. from dulwich.refs import ANNOTATED_TAG_SUFFIX
  64. INFODIR = 'info'
  65. PACKDIR = 'pack'
  66. class BaseObjectStore(object):
  67. """Object store interface."""
  68. def determine_wants_all(self, refs):
  69. return [sha for (ref, sha) in refs.items()
  70. if sha not in self and
  71. not ref.endswith(ANNOTATED_TAG_SUFFIX) and
  72. not sha == ZERO_SHA]
  73. def iter_shas(self, shas):
  74. """Iterate over the objects for the specified shas.
  75. Args:
  76. shas: Iterable object with SHAs
  77. Returns: Object iterator
  78. """
  79. return ObjectStoreIterator(self, shas)
  80. def contains_loose(self, sha):
  81. """Check if a particular object is present by SHA1 and is loose."""
  82. raise NotImplementedError(self.contains_loose)
  83. def contains_packed(self, sha):
  84. """Check if a particular object is present by SHA1 and is packed."""
  85. raise NotImplementedError(self.contains_packed)
  86. def __contains__(self, sha):
  87. """Check if a particular object is present by SHA1.
  88. This method makes no distinction between loose and packed objects.
  89. """
  90. return self.contains_packed(sha) or self.contains_loose(sha)
  91. @property
  92. def packs(self):
  93. """Iterable of pack objects."""
  94. raise NotImplementedError
  95. def get_raw(self, name):
  96. """Obtain the raw text for an object.
  97. Args:
  98. name: sha for the object.
  99. Returns: tuple with numeric type and object contents.
  100. """
  101. raise NotImplementedError(self.get_raw)
  102. def __getitem__(self, sha):
  103. """Obtain an object by SHA1."""
  104. type_num, uncomp = self.get_raw(sha)
  105. return ShaFile.from_raw_string(type_num, uncomp, sha=sha)
  106. def __iter__(self):
  107. """Iterate over the SHAs that are present in this store."""
  108. raise NotImplementedError(self.__iter__)
  109. def add_object(self, obj):
  110. """Add a single object to this object store.
  111. """
  112. raise NotImplementedError(self.add_object)
  113. def add_objects(self, objects, progress=None):
  114. """Add a set of objects to this object store.
  115. Args:
  116. objects: Iterable over a list of (object, path) tuples
  117. """
  118. raise NotImplementedError(self.add_objects)
  119. def add_pack_data(self, count, pack_data, progress=None):
  120. """Add pack data to this object store.
  121. Args:
  122. num_items: Number of items to add
  123. pack_data: Iterator over pack data tuples
  124. """
  125. if count == 0:
  126. # Don't bother writing an empty pack file
  127. return
  128. f, commit, abort = self.add_pack()
  129. try:
  130. write_pack_data(
  131. f, count, pack_data, progress,
  132. compression_level=self.pack_compression_level)
  133. except BaseException:
  134. abort()
  135. raise
  136. else:
  137. return commit()
  138. def tree_changes(self, source, target, want_unchanged=False,
  139. include_trees=False, change_type_same=False,
  140. rename_detector=None):
  141. """Find the differences between the contents of two trees
  142. Args:
  143. source: SHA1 of the source tree
  144. target: SHA1 of the target tree
  145. want_unchanged: Whether unchanged files should be reported
  146. include_trees: Whether to include trees
  147. change_type_same: Whether to report files changing
  148. type in the same entry.
  149. Returns: Iterator over tuples with
  150. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  151. """
  152. for change in tree_changes(self, source, target,
  153. want_unchanged=want_unchanged,
  154. include_trees=include_trees,
  155. change_type_same=change_type_same,
  156. rename_detector=rename_detector):
  157. yield ((change.old.path, change.new.path),
  158. (change.old.mode, change.new.mode),
  159. (change.old.sha, change.new.sha))
  160. def iter_tree_contents(self, tree_id, include_trees=False):
  161. """Iterate the contents of a tree and all subtrees.
  162. Iteration is depth-first pre-order, as in e.g. os.walk.
  163. Args:
  164. tree_id: SHA1 of the tree.
  165. include_trees: If True, include tree objects in the iteration.
  166. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  167. tree.
  168. """
  169. for entry, _ in walk_trees(self, tree_id, None):
  170. if ((entry.mode is not None and
  171. not stat.S_ISDIR(entry.mode)) or include_trees):
  172. yield entry
  173. def find_missing_objects(self, haves, wants, shallow=None, progress=None,
  174. get_tagged=None,
  175. get_parents=lambda commit: commit.parents,
  176. depth=None):
  177. """Find the missing objects required for a set of revisions.
  178. Args:
  179. haves: Iterable over SHAs already in common.
  180. wants: Iterable over SHAs of objects to fetch.
  181. shallow: Set of shallow commit SHA1s to skip
  182. progress: Simple progress function that will be called with
  183. updated progress strings.
  184. get_tagged: Function that returns a dict of pointed-to sha ->
  185. tag sha for including tags.
  186. get_parents: Optional function for getting the parents of a
  187. commit.
  188. Returns: Iterator over (sha, path) pairs.
  189. """
  190. finder = MissingObjectFinder(self, haves, wants, shallow, progress,
  191. get_tagged, get_parents=get_parents)
  192. return iter(finder.next, None)
  193. def find_common_revisions(self, graphwalker):
  194. """Find which revisions this store has in common using graphwalker.
  195. Args:
  196. graphwalker: A graphwalker object.
  197. Returns: List of SHAs that are in common
  198. """
  199. haves = []
  200. sha = next(graphwalker)
  201. while sha:
  202. if sha in self:
  203. haves.append(sha)
  204. graphwalker.ack(sha)
  205. sha = next(graphwalker)
  206. return haves
  207. def generate_pack_contents(self, have, want, shallow=None, progress=None):
  208. """Iterate over the contents of a pack file.
  209. Args:
  210. have: List of SHA1s of objects that should not be sent
  211. want: List of SHA1s of objects that should be sent
  212. shallow: Set of shallow commit SHA1s to skip
  213. progress: Optional progress reporting method
  214. """
  215. missing = self.find_missing_objects(have, want, shallow, progress)
  216. return self.iter_shas(missing)
  217. def generate_pack_data(self, have, want, shallow=None, progress=None,
  218. ofs_delta=True):
  219. """Generate pack data objects for a set of wants/haves.
  220. Args:
  221. have: List of SHA1s of objects that should not be sent
  222. want: List of SHA1s of objects that should be sent
  223. shallow: Set of shallow commit SHA1s to skip
  224. ofs_delta: Whether OFS deltas can be included
  225. progress: Optional progress reporting method
  226. """
  227. # TODO(jelmer): More efficient implementation
  228. return pack_objects_to_data(
  229. self.generate_pack_contents(have, want, shallow, progress))
  230. def peel_sha(self, sha):
  231. """Peel all tags from a SHA.
  232. Args:
  233. sha: The object SHA to peel.
  234. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  235. intermediate tags; if the original ref does not point to a tag,
  236. this will equal the original SHA1.
  237. """
  238. obj = self[sha]
  239. obj_class = object_class(obj.type_name)
  240. while obj_class is Tag:
  241. obj_class, sha = obj.object
  242. obj = self[sha]
  243. return obj
  244. def _collect_ancestors(self, heads, common=set(), shallow=set(),
  245. get_parents=lambda commit: commit.parents):
  246. """Collect all ancestors of heads up to (excluding) those in common.
  247. Args:
  248. heads: commits to start from
  249. common: commits to end at, or empty set to walk repository
  250. completely
  251. get_parents: Optional function for getting the parents of a
  252. commit.
  253. Returns: a tuple (A, B) where A - all commits reachable
  254. from heads but not present in common, B - common (shared) elements
  255. that are directly reachable from heads
  256. """
  257. bases = set()
  258. commits = set()
  259. queue = []
  260. queue.extend(heads)
  261. while queue:
  262. e = queue.pop(0)
  263. if e in common:
  264. bases.add(e)
  265. elif e not in commits:
  266. commits.add(e)
  267. if e in shallow:
  268. continue
  269. cmt = self[e]
  270. queue.extend(get_parents(cmt))
  271. return (commits, bases)
  272. def close(self):
  273. """Close any files opened by this object store."""
  274. # Default implementation is a NO-OP
  275. class PackBasedObjectStore(BaseObjectStore):
  276. def __init__(self, pack_compression_level=-1):
  277. self._pack_cache = {}
  278. self.pack_compression_level = pack_compression_level
  279. @property
  280. def alternates(self):
  281. return []
  282. def contains_packed(self, sha):
  283. """Check if a particular object is present by SHA1 and is packed.
  284. This does not check alternates.
  285. """
  286. for pack in self.packs:
  287. try:
  288. if sha in pack:
  289. return True
  290. except PackFileDisappeared:
  291. pass
  292. return False
  293. def __contains__(self, sha):
  294. """Check if a particular object is present by SHA1.
  295. This method makes no distinction between loose and packed objects.
  296. """
  297. if self.contains_packed(sha) or self.contains_loose(sha):
  298. return True
  299. for alternate in self.alternates:
  300. if sha in alternate:
  301. return True
  302. return False
  303. def _add_cached_pack(self, base_name, pack):
  304. """Add a newly appeared pack to the cache by path.
  305. """
  306. prev_pack = self._pack_cache.get(base_name)
  307. if prev_pack is not pack:
  308. self._pack_cache[base_name] = pack
  309. if prev_pack:
  310. prev_pack.close()
  311. def _clear_cached_packs(self):
  312. pack_cache = self._pack_cache
  313. self._pack_cache = {}
  314. while pack_cache:
  315. (name, pack) = pack_cache.popitem()
  316. pack.close()
  317. def _iter_cached_packs(self):
  318. return self._pack_cache.values()
  319. def _update_pack_cache(self):
  320. raise NotImplementedError(self._update_pack_cache)
  321. def close(self):
  322. self._clear_cached_packs()
  323. @property
  324. def packs(self):
  325. """List with pack objects."""
  326. return (
  327. list(self._iter_cached_packs()) + list(self._update_pack_cache()))
  328. def _iter_alternate_objects(self):
  329. """Iterate over the SHAs of all the objects in alternate stores."""
  330. for alternate in self.alternates:
  331. for alternate_object in alternate:
  332. yield alternate_object
  333. def _iter_loose_objects(self):
  334. """Iterate over the SHAs of all loose objects."""
  335. raise NotImplementedError(self._iter_loose_objects)
  336. def _get_loose_object(self, sha):
  337. raise NotImplementedError(self._get_loose_object)
  338. def _remove_loose_object(self, sha):
  339. raise NotImplementedError(self._remove_loose_object)
  340. def _remove_pack(self, name):
  341. raise NotImplementedError(self._remove_pack)
  342. def pack_loose_objects(self):
  343. """Pack loose objects.
  344. Returns: Number of objects packed
  345. """
  346. objects = set()
  347. for sha in self._iter_loose_objects():
  348. objects.add((self._get_loose_object(sha), None))
  349. self.add_objects(list(objects))
  350. for obj, path in objects:
  351. self._remove_loose_object(obj.id)
  352. return len(objects)
  353. def repack(self):
  354. """Repack the packs in this repository.
  355. Note that this implementation is fairly naive and currently keeps all
  356. objects in memory while it repacks.
  357. """
  358. loose_objects = set()
  359. for sha in self._iter_loose_objects():
  360. loose_objects.add(self._get_loose_object(sha))
  361. objects = {(obj, None) for obj in loose_objects}
  362. old_packs = {p.name(): p for p in self.packs}
  363. for name, pack in old_packs.items():
  364. objects.update((obj, None) for obj in pack.iterobjects())
  365. # The name of the consolidated pack might match the name of a
  366. # pre-existing pack. Take care not to remove the newly created
  367. # consolidated pack.
  368. consolidated = self.add_objects(objects)
  369. old_packs.pop(consolidated.name(), None)
  370. for obj in loose_objects:
  371. self._remove_loose_object(obj.id)
  372. for name, pack in old_packs.items():
  373. self._remove_pack(pack)
  374. self._update_pack_cache()
  375. return len(objects)
  376. def __iter__(self):
  377. """Iterate over the SHAs that are present in this store."""
  378. self._update_pack_cache()
  379. for pack in self._iter_cached_packs():
  380. try:
  381. for sha in pack:
  382. yield sha
  383. except PackFileDisappeared:
  384. pass
  385. for sha in self._iter_loose_objects():
  386. yield sha
  387. for sha in self._iter_alternate_objects():
  388. yield sha
  389. def contains_loose(self, sha):
  390. """Check if a particular object is present by SHA1 and is loose.
  391. This does not check alternates.
  392. """
  393. return self._get_loose_object(sha) is not None
  394. def get_raw(self, name):
  395. """Obtain the raw fulltext for an object.
  396. Args:
  397. name: sha for the object.
  398. Returns: tuple with numeric type and object contents.
  399. """
  400. if name == ZERO_SHA:
  401. raise KeyError(name)
  402. if len(name) == 40:
  403. sha = hex_to_sha(name)
  404. hexsha = name
  405. elif len(name) == 20:
  406. sha = name
  407. hexsha = None
  408. else:
  409. raise AssertionError("Invalid object name %r" % (name, ))
  410. for pack in self._iter_cached_packs():
  411. try:
  412. return pack.get_raw(sha)
  413. except (KeyError, PackFileDisappeared):
  414. pass
  415. if hexsha is None:
  416. hexsha = sha_to_hex(name)
  417. ret = self._get_loose_object(hexsha)
  418. if ret is not None:
  419. return ret.type_num, ret.as_raw_string()
  420. # Maybe something else has added a pack with the object
  421. # in the mean time?
  422. for pack in self._update_pack_cache():
  423. try:
  424. return pack.get_raw(sha)
  425. except KeyError:
  426. pass
  427. for alternate in self.alternates:
  428. try:
  429. return alternate.get_raw(hexsha)
  430. except KeyError:
  431. pass
  432. raise KeyError(hexsha)
  433. def add_objects(self, objects, progress=None):
  434. """Add a set of objects to this object store.
  435. Args:
  436. objects: Iterable over (object, path) tuples, should support
  437. __len__.
  438. Returns: Pack object of the objects written.
  439. """
  440. return self.add_pack_data(
  441. *pack_objects_to_data(objects),
  442. progress=progress)
  443. class DiskObjectStore(PackBasedObjectStore):
  444. """Git-style object store that exists on disk."""
  445. def __init__(self, path, loose_compression_level=-1):
  446. """Open an object store.
  447. Args:
  448. path: Path of the object store.
  449. loose_compression_level: zlib compression level for loose objects
  450. """
  451. super(DiskObjectStore, self).__init__(
  452. pack_compression_level=pack_compression_level)
  453. self.path = path
  454. self.pack_dir = os.path.join(self.path, PACKDIR)
  455. self._alternates = None
  456. self.loose_compression_level = loose_compression_level
  457. def __repr__(self):
  458. return "<%s(%r)>" % (self.__class__.__name__, self.path)
  459. @classmethod
  460. def from_config(cls, path, config):
  461. try:
  462. default_compression_level = int(config.get(
  463. (b'core', ), b'compression').decode())
  464. except KeyError:
  465. default_compression_level = -1
  466. try:
  467. loose_compression_level = int(config.get(
  468. (b'core', ), b'looseCompression').decode())
  469. except KeyError:
  470. loose_compression_level = default_compression_level
  471. try:
  472. pack_compression_level = int(config.get(
  473. (b'core', ), 'packCompression').decode())
  474. except KeyError:
  475. pack_compression_level = default_compression_level
  476. return cls(path, loose_compression_level, pack_compression_level)
  477. @property
  478. def alternates(self):
  479. if self._alternates is not None:
  480. return self._alternates
  481. self._alternates = []
  482. for path in self._read_alternate_paths():
  483. self._alternates.append(DiskObjectStore(path))
  484. return self._alternates
  485. def _read_alternate_paths(self):
  486. try:
  487. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), 'rb')
  488. except (OSError, IOError) as e:
  489. if e.errno == errno.ENOENT:
  490. return
  491. raise
  492. with f:
  493. for line in f.readlines():
  494. line = line.rstrip(b"\n")
  495. if line[0] == b"#":
  496. continue
  497. if os.path.isabs(line):
  498. yield line.decode(sys.getfilesystemencoding())
  499. else:
  500. yield os.path.join(self.path, line).decode(
  501. sys.getfilesystemencoding())
  502. def add_alternate_path(self, path):
  503. """Add an alternate path to this object store.
  504. """
  505. try:
  506. os.mkdir(os.path.join(self.path, INFODIR))
  507. except OSError as e:
  508. if e.errno != errno.EEXIST:
  509. raise
  510. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  511. with GitFile(alternates_path, 'wb') as f:
  512. try:
  513. orig_f = open(alternates_path, 'rb')
  514. except (OSError, IOError) as e:
  515. if e.errno != errno.ENOENT:
  516. raise
  517. else:
  518. with orig_f:
  519. f.write(orig_f.read())
  520. f.write(path.encode(sys.getfilesystemencoding()) + b"\n")
  521. if not os.path.isabs(path):
  522. path = os.path.join(self.path, path)
  523. self.alternates.append(DiskObjectStore(path))
  524. def _update_pack_cache(self):
  525. """Read and iterate over new pack files and cache them."""
  526. try:
  527. pack_dir_contents = os.listdir(self.pack_dir)
  528. except OSError as e:
  529. if e.errno == errno.ENOENT:
  530. self.close()
  531. return []
  532. raise
  533. pack_files = set()
  534. for name in pack_dir_contents:
  535. if name.startswith("pack-") and name.endswith(".pack"):
  536. # verify that idx exists first (otherwise the pack was not yet
  537. # fully written)
  538. idx_name = os.path.splitext(name)[0] + ".idx"
  539. if idx_name in pack_dir_contents:
  540. pack_name = name[:-len(".pack")]
  541. pack_files.add(pack_name)
  542. # Open newly appeared pack files
  543. new_packs = []
  544. for f in pack_files:
  545. if f not in self._pack_cache:
  546. pack = Pack(os.path.join(self.pack_dir, f))
  547. new_packs.append(pack)
  548. self._pack_cache[f] = pack
  549. # Remove disappeared pack files
  550. for f in set(self._pack_cache) - pack_files:
  551. self._pack_cache.pop(f).close()
  552. return new_packs
  553. def _get_shafile_path(self, sha):
  554. # Check from object dir
  555. return hex_to_filename(self.path, sha)
  556. def _iter_loose_objects(self):
  557. for base in os.listdir(self.path):
  558. if len(base) != 2:
  559. continue
  560. for rest in os.listdir(os.path.join(self.path, base)):
  561. yield (base+rest).encode(sys.getfilesystemencoding())
  562. def _get_loose_object(self, sha):
  563. path = self._get_shafile_path(sha)
  564. try:
  565. return ShaFile.from_path(path)
  566. except (OSError, IOError) as e:
  567. if e.errno == errno.ENOENT:
  568. return None
  569. raise
  570. def _remove_loose_object(self, sha):
  571. os.remove(self._get_shafile_path(sha))
  572. def _remove_pack(self, pack):
  573. try:
  574. del self._pack_cache[os.path.basename(pack._basename)]
  575. except KeyError:
  576. pass
  577. pack.close()
  578. os.remove(pack.data.path)
  579. os.remove(pack.index.path)
  580. def _get_pack_basepath(self, entries):
  581. suffix = iter_sha1(entry[0] for entry in entries)
  582. # TODO: Handle self.pack_dir being bytes
  583. suffix = suffix.decode('ascii')
  584. return os.path.join(self.pack_dir, "pack-" + suffix)
  585. def _complete_thin_pack(self, f, path, copier, indexer):
  586. """Move a specific file containing a pack into the pack directory.
  587. Note: The file should be on the same file system as the
  588. packs directory.
  589. Args:
  590. f: Open file object for the pack.
  591. path: Path to the pack file.
  592. copier: A PackStreamCopier to use for writing pack data.
  593. indexer: A PackIndexer for indexing the pack.
  594. """
  595. entries = list(indexer)
  596. # Update the header with the new number of objects.
  597. f.seek(0)
  598. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  599. # Must flush before reading (http://bugs.python.org/issue3207)
  600. f.flush()
  601. # Rescan the rest of the pack, computing the SHA with the new header.
  602. new_sha = compute_file_sha(f, end_ofs=-20)
  603. # Must reposition before writing (http://bugs.python.org/issue3207)
  604. f.seek(0, os.SEEK_CUR)
  605. # Complete the pack.
  606. for ext_sha in indexer.ext_refs():
  607. assert len(ext_sha) == 20
  608. type_num, data = self.get_raw(ext_sha)
  609. offset = f.tell()
  610. crc32 = write_pack_object(
  611. f, type_num, data, sha=new_sha,
  612. compression_level=self.pack_compression_level)
  613. entries.append((ext_sha, offset, crc32))
  614. pack_sha = new_sha.digest()
  615. f.write(pack_sha)
  616. f.close()
  617. # Move the pack in.
  618. entries.sort()
  619. pack_base_name = self._get_pack_basepath(entries)
  620. target_pack = pack_base_name + '.pack'
  621. if sys.platform == 'win32':
  622. # Windows might have the target pack file lingering. Attempt
  623. # removal, silently passing if the target does not exist.
  624. try:
  625. os.remove(target_pack)
  626. except (IOError, OSError) as e:
  627. if e.errno != errno.ENOENT:
  628. raise
  629. os.rename(path, target_pack)
  630. # Write the index.
  631. index_file = GitFile(pack_base_name + '.idx', 'wb')
  632. try:
  633. write_pack_index_v2(index_file, entries, pack_sha)
  634. index_file.close()
  635. finally:
  636. index_file.abort()
  637. # Add the pack to the store and return it.
  638. final_pack = Pack(pack_base_name)
  639. final_pack.check_length_and_checksum()
  640. self._add_cached_pack(pack_base_name, final_pack)
  641. return final_pack
  642. def add_thin_pack(self, read_all, read_some):
  643. """Add a new thin pack to this object store.
  644. Thin packs are packs that contain deltas with parents that exist
  645. outside the pack. They should never be placed in the object store
  646. directly, and always indexed and completed as they are copied.
  647. Args:
  648. read_all: Read function that blocks until the number of
  649. requested bytes are read.
  650. read_some: Read function that returns at least one byte, but may
  651. not return the number of bytes requested.
  652. Returns: A Pack object pointing at the now-completed thin pack in the
  653. objects/pack directory.
  654. """
  655. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  656. with os.fdopen(fd, 'w+b') as f:
  657. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  658. copier = PackStreamCopier(read_all, read_some, f,
  659. delta_iter=indexer)
  660. copier.verify()
  661. return self._complete_thin_pack(f, path, copier, indexer)
  662. def move_in_pack(self, path):
  663. """Move a specific file containing a pack into the pack directory.
  664. Note: The file should be on the same file system as the
  665. packs directory.
  666. Args:
  667. path: Path to the pack file.
  668. """
  669. with PackData(path) as p:
  670. entries = p.sorted_entries()
  671. basename = self._get_pack_basepath(entries)
  672. index_name = basename + ".idx"
  673. if not os.path.exists(index_name):
  674. with GitFile(index_name, "wb") as f:
  675. write_pack_index_v2(f, entries, p.get_stored_checksum())
  676. for pack in self.packs:
  677. if pack._basename == basename:
  678. return pack
  679. target_pack = basename + '.pack'
  680. if sys.platform == 'win32':
  681. # Windows might have the target pack file lingering. Attempt
  682. # removal, silently passing if the target does not exist.
  683. try:
  684. os.remove(target_pack)
  685. except (IOError, OSError) as e:
  686. if e.errno != errno.ENOENT:
  687. raise
  688. os.rename(path, target_pack)
  689. final_pack = Pack(basename)
  690. self._add_cached_pack(basename, final_pack)
  691. return final_pack
  692. def add_pack(self):
  693. """Add a new pack to this object store.
  694. Returns: Fileobject to write to, a commit function to
  695. call when the pack is finished and an abort
  696. function.
  697. """
  698. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  699. f = os.fdopen(fd, 'wb')
  700. def commit():
  701. f.flush()
  702. os.fsync(fd)
  703. f.close()
  704. if os.path.getsize(path) > 0:
  705. return self.move_in_pack(path)
  706. else:
  707. os.remove(path)
  708. return None
  709. def abort():
  710. f.close()
  711. os.remove(path)
  712. return f, commit, abort
  713. def add_object(self, obj):
  714. """Add a single object to this object store.
  715. Args:
  716. obj: Object to add
  717. """
  718. path = self._get_shafile_path(obj.id)
  719. dir = os.path.dirname(path)
  720. try:
  721. os.mkdir(dir)
  722. except OSError as e:
  723. if e.errno != errno.EEXIST:
  724. raise
  725. if os.path.exists(path):
  726. return # Already there, no need to write again
  727. with GitFile(path, 'wb') as f:
  728. f.write(obj.as_legacy_object(
  729. compression_level=self.loose_compression_level))
  730. @classmethod
  731. def init(cls, path):
  732. try:
  733. os.mkdir(path)
  734. except OSError as e:
  735. if e.errno != errno.EEXIST:
  736. raise
  737. os.mkdir(os.path.join(path, "info"))
  738. os.mkdir(os.path.join(path, PACKDIR))
  739. return cls(path)
  740. class MemoryObjectStore(BaseObjectStore):
  741. """Object store that keeps all objects in memory."""
  742. def __init__(self):
  743. super(MemoryObjectStore, self).__init__()
  744. self._data = {}
  745. self.pack_compression_level = -1
  746. def _to_hexsha(self, sha):
  747. if len(sha) == 40:
  748. return sha
  749. elif len(sha) == 20:
  750. return sha_to_hex(sha)
  751. else:
  752. raise ValueError("Invalid sha %r" % (sha,))
  753. def contains_loose(self, sha):
  754. """Check if a particular object is present by SHA1 and is loose."""
  755. return self._to_hexsha(sha) in self._data
  756. def contains_packed(self, sha):
  757. """Check if a particular object is present by SHA1 and is packed."""
  758. return False
  759. def __iter__(self):
  760. """Iterate over the SHAs that are present in this store."""
  761. return iter(self._data.keys())
  762. @property
  763. def packs(self):
  764. """List with pack objects."""
  765. return []
  766. def get_raw(self, name):
  767. """Obtain the raw text for an object.
  768. Args:
  769. name: sha for the object.
  770. Returns: tuple with numeric type and object contents.
  771. """
  772. obj = self[self._to_hexsha(name)]
  773. return obj.type_num, obj.as_raw_string()
  774. def __getitem__(self, name):
  775. return self._data[self._to_hexsha(name)].copy()
  776. def __delitem__(self, name):
  777. """Delete an object from this store, for testing only."""
  778. del self._data[self._to_hexsha(name)]
  779. def add_object(self, obj):
  780. """Add a single object to this object store.
  781. """
  782. self._data[obj.id] = obj.copy()
  783. def add_objects(self, objects, progress=None):
  784. """Add a set of objects to this object store.
  785. Args:
  786. objects: Iterable over a list of (object, path) tuples
  787. """
  788. for obj, path in objects:
  789. self.add_object(obj)
  790. def add_pack(self):
  791. """Add a new pack to this object store.
  792. Because this object store doesn't support packs, we extract and add the
  793. individual objects.
  794. Returns: Fileobject to write to and a commit function to
  795. call when the pack is finished.
  796. """
  797. f = BytesIO()
  798. def commit():
  799. p = PackData.from_file(BytesIO(f.getvalue()), f.tell())
  800. f.close()
  801. for obj in PackInflater.for_pack_data(p, self.get_raw):
  802. self.add_object(obj)
  803. def abort():
  804. pass
  805. return f, commit, abort
  806. def _complete_thin_pack(self, f, indexer):
  807. """Complete a thin pack by adding external references.
  808. Args:
  809. f: Open file object for the pack.
  810. indexer: A PackIndexer for indexing the pack.
  811. """
  812. entries = list(indexer)
  813. # Update the header with the new number of objects.
  814. f.seek(0)
  815. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  816. # Rescan the rest of the pack, computing the SHA with the new header.
  817. new_sha = compute_file_sha(f, end_ofs=-20)
  818. # Complete the pack.
  819. for ext_sha in indexer.ext_refs():
  820. assert len(ext_sha) == 20
  821. type_num, data = self.get_raw(ext_sha)
  822. write_pack_object(
  823. f, type_num, data, sha=new_sha)
  824. pack_sha = new_sha.digest()
  825. f.write(pack_sha)
  826. def add_thin_pack(self, read_all, read_some):
  827. """Add a new thin pack to this object store.
  828. Thin packs are packs that contain deltas with parents that exist
  829. outside the pack. Because this object store doesn't support packs, we
  830. extract and add the individual objects.
  831. Args:
  832. read_all: Read function that blocks until the number of
  833. requested bytes are read.
  834. read_some: Read function that returns at least one byte, but may
  835. not return the number of bytes requested.
  836. """
  837. f, commit, abort = self.add_pack()
  838. try:
  839. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  840. copier = PackStreamCopier(read_all, read_some, f,
  841. delta_iter=indexer)
  842. copier.verify()
  843. self._complete_thin_pack(f, indexer)
  844. except BaseException:
  845. abort()
  846. raise
  847. else:
  848. commit()
  849. class ObjectIterator(object):
  850. """Interface for iterating over objects."""
  851. def iterobjects(self):
  852. raise NotImplementedError(self.iterobjects)
  853. class ObjectStoreIterator(ObjectIterator):
  854. """ObjectIterator that works on top of an ObjectStore."""
  855. def __init__(self, store, sha_iter):
  856. """Create a new ObjectIterator.
  857. Args:
  858. store: Object store to retrieve from
  859. sha_iter: Iterator over (sha, path) tuples
  860. """
  861. self.store = store
  862. self.sha_iter = sha_iter
  863. self._shas = []
  864. def __iter__(self):
  865. """Yield tuple with next object and path."""
  866. for sha, path in self.itershas():
  867. yield self.store[sha], path
  868. def iterobjects(self):
  869. """Iterate over just the objects."""
  870. for o, path in self:
  871. yield o
  872. def itershas(self):
  873. """Iterate over the SHAs."""
  874. for sha in self._shas:
  875. yield sha
  876. for sha in self.sha_iter:
  877. self._shas.append(sha)
  878. yield sha
  879. def __contains__(self, needle):
  880. """Check if an object is present.
  881. Note: This checks if the object is present in
  882. the underlying object store, not if it would
  883. be yielded by the iterator.
  884. Args:
  885. needle: SHA1 of the object to check for
  886. """
  887. if needle == ZERO_SHA:
  888. return False
  889. return needle in self.store
  890. def __getitem__(self, key):
  891. """Find an object by SHA1.
  892. Note: This retrieves the object from the underlying
  893. object store. It will also succeed if the object would
  894. not be returned by the iterator.
  895. """
  896. return self.store[key]
  897. def __len__(self):
  898. """Return the number of objects."""
  899. return len(list(self.itershas()))
  900. def empty(self):
  901. import warnings
  902. warnings.warn('Use bool() instead.', DeprecationWarning)
  903. return self._empty()
  904. def _empty(self):
  905. it = self.itershas()
  906. try:
  907. next(it)
  908. except StopIteration:
  909. return True
  910. else:
  911. return False
  912. def __bool__(self):
  913. """Indicate whether this object has contents."""
  914. return not self._empty()
  915. def tree_lookup_path(lookup_obj, root_sha, path):
  916. """Look up an object in a Git tree.
  917. Args:
  918. lookup_obj: Callback for retrieving object by SHA1
  919. root_sha: SHA1 of the root tree
  920. path: Path to lookup
  921. Returns: A tuple of (mode, SHA) of the resulting path.
  922. """
  923. tree = lookup_obj(root_sha)
  924. if not isinstance(tree, Tree):
  925. raise NotTreeError(root_sha)
  926. return tree.lookup_path(lookup_obj, path)
  927. def _collect_filetree_revs(obj_store, tree_sha, kset):
  928. """Collect SHA1s of files and directories for specified tree.
  929. Args:
  930. obj_store: Object store to get objects by SHA from
  931. tree_sha: tree reference to walk
  932. kset: set to fill with references to files and directories
  933. """
  934. filetree = obj_store[tree_sha]
  935. for name, mode, sha in filetree.iteritems():
  936. if not S_ISGITLINK(mode) and sha not in kset:
  937. kset.add(sha)
  938. if stat.S_ISDIR(mode):
  939. _collect_filetree_revs(obj_store, sha, kset)
  940. def _split_commits_and_tags(obj_store, lst, ignore_unknown=False):
  941. """Split object id list into three lists with commit, tag, and other SHAs.
  942. Commits referenced by tags are included into commits
  943. list as well. Only SHA1s known in this repository will get
  944. through, and unless ignore_unknown argument is True, KeyError
  945. is thrown for SHA1 missing in the repository
  946. Args:
  947. obj_store: Object store to get objects by SHA1 from
  948. lst: Collection of commit and tag SHAs
  949. ignore_unknown: True to skip SHA1 missing in the repository
  950. silently.
  951. Returns: A tuple of (commits, tags, others) SHA1s
  952. """
  953. commits = set()
  954. tags = set()
  955. others = set()
  956. for e in lst:
  957. try:
  958. o = obj_store[e]
  959. except KeyError:
  960. if not ignore_unknown:
  961. raise
  962. else:
  963. if isinstance(o, Commit):
  964. commits.add(e)
  965. elif isinstance(o, Tag):
  966. tags.add(e)
  967. tagged = o.object[1]
  968. c, t, o = _split_commits_and_tags(
  969. obj_store, [tagged], ignore_unknown=ignore_unknown)
  970. commits |= c
  971. tags |= t
  972. others |= o
  973. else:
  974. others.add(e)
  975. return (commits, tags, others)
  976. class MissingObjectFinder(object):
  977. """Find the objects missing from another object store.
  978. Args:
  979. object_store: Object store containing at least all objects to be
  980. sent
  981. haves: SHA1s of commits not to send (already present in target)
  982. wants: SHA1s of commits to send
  983. progress: Optional function to report progress to.
  984. get_tagged: Function that returns a dict of pointed-to sha -> tag
  985. sha for including tags.
  986. get_parents: Optional function for getting the parents of a commit.
  987. tagged: dict of pointed-to sha -> tag sha for including tags
  988. """
  989. def __init__(self, object_store, haves, wants, shallow=None, progress=None,
  990. get_tagged=None, get_parents=lambda commit: commit.parents):
  991. self.object_store = object_store
  992. if shallow is None:
  993. shallow = set()
  994. self._get_parents = get_parents
  995. # process Commits and Tags differently
  996. # Note, while haves may list commits/tags not available locally,
  997. # and such SHAs would get filtered out by _split_commits_and_tags,
  998. # wants shall list only known SHAs, and otherwise
  999. # _split_commits_and_tags fails with KeyError
  1000. have_commits, have_tags, have_others = (
  1001. _split_commits_and_tags(object_store, haves, True))
  1002. want_commits, want_tags, want_others = (
  1003. _split_commits_and_tags(object_store, wants, False))
  1004. # all_ancestors is a set of commits that shall not be sent
  1005. # (complete repository up to 'haves')
  1006. all_ancestors = object_store._collect_ancestors(
  1007. have_commits, shallow=shallow, get_parents=self._get_parents)[0]
  1008. # all_missing - complete set of commits between haves and wants
  1009. # common - commits from all_ancestors we hit into while
  1010. # traversing parent hierarchy of wants
  1011. missing_commits, common_commits = object_store._collect_ancestors(
  1012. want_commits, all_ancestors, shallow=shallow,
  1013. get_parents=self._get_parents)
  1014. self.sha_done = set()
  1015. # Now, fill sha_done with commits and revisions of
  1016. # files and directories known to be both locally
  1017. # and on target. Thus these commits and files
  1018. # won't get selected for fetch
  1019. for h in common_commits:
  1020. self.sha_done.add(h)
  1021. cmt = object_store[h]
  1022. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  1023. # record tags we have as visited, too
  1024. for t in have_tags:
  1025. self.sha_done.add(t)
  1026. missing_tags = want_tags.difference(have_tags)
  1027. missing_others = want_others.difference(have_others)
  1028. # in fact, what we 'want' is commits, tags, and others
  1029. # we've found missing
  1030. wants = missing_commits.union(missing_tags)
  1031. wants = wants.union(missing_others)
  1032. self.objects_to_send = set([(w, None, False) for w in wants])
  1033. if progress is None:
  1034. self.progress = lambda x: None
  1035. else:
  1036. self.progress = progress
  1037. self._tagged = get_tagged and get_tagged() or {}
  1038. def add_todo(self, entries):
  1039. self.objects_to_send.update([e for e in entries
  1040. if not e[0] in self.sha_done])
  1041. def next(self):
  1042. while True:
  1043. if not self.objects_to_send:
  1044. return None
  1045. (sha, name, leaf) = self.objects_to_send.pop()
  1046. if sha not in self.sha_done:
  1047. break
  1048. if not leaf:
  1049. o = self.object_store[sha]
  1050. if isinstance(o, Commit):
  1051. self.add_todo([(o.tree, "", False)])
  1052. elif isinstance(o, Tree):
  1053. self.add_todo([(s, n, not stat.S_ISDIR(m))
  1054. for n, m, s in o.iteritems()
  1055. if not S_ISGITLINK(m)])
  1056. elif isinstance(o, Tag):
  1057. self.add_todo([(o.object[1], None, False)])
  1058. if sha in self._tagged:
  1059. self.add_todo([(self._tagged[sha], None, True)])
  1060. self.sha_done.add(sha)
  1061. self.progress(("counting objects: %d\r" %
  1062. len(self.sha_done)).encode('ascii'))
  1063. return (sha, name)
  1064. __next__ = next
  1065. class ObjectStoreGraphWalker(object):
  1066. """Graph walker that finds what commits are missing from an object store.
  1067. :ivar heads: Revisions without descendants in the local repo
  1068. :ivar get_parents: Function to retrieve parents in the local repo
  1069. """
  1070. def __init__(self, local_heads, get_parents, shallow=None):
  1071. """Create a new instance.
  1072. Args:
  1073. local_heads: Heads to start search with
  1074. get_parents: Function for finding the parents of a SHA1.
  1075. """
  1076. self.heads = set(local_heads)
  1077. self.get_parents = get_parents
  1078. self.parents = {}
  1079. if shallow is None:
  1080. shallow = set()
  1081. self.shallow = shallow
  1082. def ack(self, sha):
  1083. """Ack that a revision and its ancestors are present in the source."""
  1084. if len(sha) != 40:
  1085. raise ValueError("unexpected sha %r received" % sha)
  1086. ancestors = set([sha])
  1087. # stop if we run out of heads to remove
  1088. while self.heads:
  1089. for a in ancestors:
  1090. if a in self.heads:
  1091. self.heads.remove(a)
  1092. # collect all ancestors
  1093. new_ancestors = set()
  1094. for a in ancestors:
  1095. ps = self.parents.get(a)
  1096. if ps is not None:
  1097. new_ancestors.update(ps)
  1098. self.parents[a] = None
  1099. # no more ancestors; stop
  1100. if not new_ancestors:
  1101. break
  1102. ancestors = new_ancestors
  1103. def next(self):
  1104. """Iterate over ancestors of heads in the target."""
  1105. if self.heads:
  1106. ret = self.heads.pop()
  1107. ps = self.get_parents(ret)
  1108. self.parents[ret] = ps
  1109. self.heads.update(
  1110. [p for p in ps if p not in self.parents])
  1111. return ret
  1112. return None
  1113. __next__ = next
  1114. def commit_tree_changes(object_store, tree, changes):
  1115. """Commit a specified set of changes to a tree structure.
  1116. This will apply a set of changes on top of an existing tree, storing new
  1117. objects in object_store.
  1118. changes are a list of tuples with (path, mode, object_sha).
  1119. Paths can be both blobs and trees. See the mode and
  1120. object sha to None deletes the path.
  1121. This method works especially well if there are only a small
  1122. number of changes to a big tree. For a large number of changes
  1123. to a large tree, use e.g. commit_tree.
  1124. Args:
  1125. object_store: Object store to store new objects in
  1126. and retrieve old ones from.
  1127. tree: Original tree root
  1128. changes: changes to apply
  1129. Returns: New tree root object
  1130. """
  1131. # TODO(jelmer): Save up the objects and add them using .add_objects
  1132. # rather than with individual calls to .add_object.
  1133. nested_changes = {}
  1134. for (path, new_mode, new_sha) in changes:
  1135. try:
  1136. (dirname, subpath) = path.split(b'/', 1)
  1137. except ValueError:
  1138. if new_sha is None:
  1139. del tree[path]
  1140. else:
  1141. tree[path] = (new_mode, new_sha)
  1142. else:
  1143. nested_changes.setdefault(dirname, []).append(
  1144. (subpath, new_mode, new_sha))
  1145. for name, subchanges in nested_changes.items():
  1146. try:
  1147. orig_subtree = object_store[tree[name][1]]
  1148. except KeyError:
  1149. orig_subtree = Tree()
  1150. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1151. if len(subtree) == 0:
  1152. del tree[name]
  1153. else:
  1154. tree[name] = (stat.S_IFDIR, subtree.id)
  1155. object_store.add_object(tree)
  1156. return tree
  1157. class OverlayObjectStore(BaseObjectStore):
  1158. """Object store that can overlay multiple object stores."""
  1159. def __init__(self, bases, add_store=None):
  1160. self.bases = bases
  1161. self.add_store = add_store
  1162. def add_object(self, object):
  1163. if self.add_store is None:
  1164. raise NotImplementedError(self.add_object)
  1165. return self.add_store.add_object(object)
  1166. def add_objects(self, objects, progress=None):
  1167. if self.add_store is None:
  1168. raise NotImplementedError(self.add_object)
  1169. return self.add_store.add_objects(objects, progress)
  1170. @property
  1171. def packs(self):
  1172. ret = []
  1173. for b in self.bases:
  1174. ret.extend(b.packs)
  1175. return ret
  1176. def __iter__(self):
  1177. done = set()
  1178. for b in self.bases:
  1179. for o_id in b:
  1180. if o_id not in done:
  1181. yield o_id
  1182. done.add(o_id)
  1183. def get_raw(self, sha_id):
  1184. for b in self.bases:
  1185. try:
  1186. return b.get_raw(sha_id)
  1187. except KeyError:
  1188. pass
  1189. raise KeyError(sha_id)
  1190. def contains_packed(self, sha):
  1191. for b in self.bases:
  1192. if b.contains_packed(sha):
  1193. return True
  1194. return False
  1195. def contains_loose(self, sha):
  1196. for b in self.bases:
  1197. if b.contains_loose(sha):
  1198. return True
  1199. return False
  1200. def read_packs_file(f):
  1201. """Yield the packs listed in a packs file."""
  1202. for line in f.read().splitlines():
  1203. if not line:
  1204. continue
  1205. (kind, name) = line.split(b" ", 1)
  1206. if kind != b"P":
  1207. continue
  1208. yield name.decode(sys.getfilesystemencoding())