object_store.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  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. pack_compression_level=-1):
  447. """Open an object store.
  448. Args:
  449. path: Path of the object store.
  450. loose_compression_level: zlib compression level for loose objects
  451. pack_compression_level: zlib compression level for pack objects
  452. """
  453. super(DiskObjectStore, self).__init__(
  454. pack_compression_level=pack_compression_level)
  455. self.path = path
  456. self.pack_dir = os.path.join(self.path, PACKDIR)
  457. self._alternates = None
  458. self.loose_compression_level = loose_compression_level
  459. self.pack_compression_level = pack_compression_level
  460. def __repr__(self):
  461. return "<%s(%r)>" % (self.__class__.__name__, self.path)
  462. @classmethod
  463. def from_config(cls, path, config):
  464. try:
  465. default_compression_level = int(config.get(
  466. (b'core', ), b'compression').decode())
  467. except KeyError:
  468. default_compression_level = -1
  469. try:
  470. loose_compression_level = int(config.get(
  471. (b'core', ), b'looseCompression').decode())
  472. except KeyError:
  473. loose_compression_level = default_compression_level
  474. try:
  475. pack_compression_level = int(config.get(
  476. (b'core', ), 'packCompression').decode())
  477. except KeyError:
  478. pack_compression_level = default_compression_level
  479. return cls(path, loose_compression_level, pack_compression_level)
  480. @property
  481. def alternates(self):
  482. if self._alternates is not None:
  483. return self._alternates
  484. self._alternates = []
  485. for path in self._read_alternate_paths():
  486. self._alternates.append(DiskObjectStore(path))
  487. return self._alternates
  488. def _read_alternate_paths(self):
  489. try:
  490. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), 'rb')
  491. except (OSError, IOError) as e:
  492. if e.errno == errno.ENOENT:
  493. return
  494. raise
  495. with f:
  496. for line in f.readlines():
  497. line = line.rstrip(b"\n")
  498. if line[0] == b"#":
  499. continue
  500. if os.path.isabs(line):
  501. yield line.decode(sys.getfilesystemencoding())
  502. else:
  503. yield os.path.join(self.path, line).decode(
  504. sys.getfilesystemencoding())
  505. def add_alternate_path(self, path):
  506. """Add an alternate path to this object store.
  507. """
  508. try:
  509. os.mkdir(os.path.join(self.path, INFODIR))
  510. except OSError as e:
  511. if e.errno != errno.EEXIST:
  512. raise
  513. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  514. with GitFile(alternates_path, 'wb') as f:
  515. try:
  516. orig_f = open(alternates_path, 'rb')
  517. except (OSError, IOError) as e:
  518. if e.errno != errno.ENOENT:
  519. raise
  520. else:
  521. with orig_f:
  522. f.write(orig_f.read())
  523. f.write(path.encode(sys.getfilesystemencoding()) + b"\n")
  524. if not os.path.isabs(path):
  525. path = os.path.join(self.path, path)
  526. self.alternates.append(DiskObjectStore(path))
  527. def _update_pack_cache(self):
  528. """Read and iterate over new pack files and cache them."""
  529. try:
  530. pack_dir_contents = os.listdir(self.pack_dir)
  531. except OSError as e:
  532. if e.errno == errno.ENOENT:
  533. self.close()
  534. return []
  535. raise
  536. pack_files = set()
  537. for name in pack_dir_contents:
  538. if name.startswith("pack-") and name.endswith(".pack"):
  539. # verify that idx exists first (otherwise the pack was not yet
  540. # fully written)
  541. idx_name = os.path.splitext(name)[0] + ".idx"
  542. if idx_name in pack_dir_contents:
  543. pack_name = name[:-len(".pack")]
  544. pack_files.add(pack_name)
  545. # Open newly appeared pack files
  546. new_packs = []
  547. for f in pack_files:
  548. if f not in self._pack_cache:
  549. pack = Pack(os.path.join(self.pack_dir, f))
  550. new_packs.append(pack)
  551. self._pack_cache[f] = pack
  552. # Remove disappeared pack files
  553. for f in set(self._pack_cache) - pack_files:
  554. self._pack_cache.pop(f).close()
  555. return new_packs
  556. def _get_shafile_path(self, sha):
  557. # Check from object dir
  558. return hex_to_filename(self.path, sha)
  559. def _iter_loose_objects(self):
  560. for base in os.listdir(self.path):
  561. if len(base) != 2:
  562. continue
  563. for rest in os.listdir(os.path.join(self.path, base)):
  564. yield (base+rest).encode(sys.getfilesystemencoding())
  565. def _get_loose_object(self, sha):
  566. path = self._get_shafile_path(sha)
  567. try:
  568. return ShaFile.from_path(path)
  569. except (OSError, IOError) as e:
  570. if e.errno == errno.ENOENT:
  571. return None
  572. raise
  573. def _remove_loose_object(self, sha):
  574. os.remove(self._get_shafile_path(sha))
  575. def _remove_pack(self, pack):
  576. try:
  577. del self._pack_cache[os.path.basename(pack._basename)]
  578. except KeyError:
  579. pass
  580. pack.close()
  581. os.remove(pack.data.path)
  582. os.remove(pack.index.path)
  583. def _get_pack_basepath(self, entries):
  584. suffix = iter_sha1(entry[0] for entry in entries)
  585. # TODO: Handle self.pack_dir being bytes
  586. suffix = suffix.decode('ascii')
  587. return os.path.join(self.pack_dir, "pack-" + suffix)
  588. def _complete_thin_pack(self, f, path, copier, indexer):
  589. """Move a specific file containing a pack into the pack directory.
  590. Note: The file should be on the same file system as the
  591. packs directory.
  592. Args:
  593. f: Open file object for the pack.
  594. path: Path to the pack file.
  595. copier: A PackStreamCopier to use for writing pack data.
  596. indexer: A PackIndexer for indexing the pack.
  597. """
  598. entries = list(indexer)
  599. # Update the header with the new number of objects.
  600. f.seek(0)
  601. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  602. # Must flush before reading (http://bugs.python.org/issue3207)
  603. f.flush()
  604. # Rescan the rest of the pack, computing the SHA with the new header.
  605. new_sha = compute_file_sha(f, end_ofs=-20)
  606. # Must reposition before writing (http://bugs.python.org/issue3207)
  607. f.seek(0, os.SEEK_CUR)
  608. # Complete the pack.
  609. for ext_sha in indexer.ext_refs():
  610. assert len(ext_sha) == 20
  611. type_num, data = self.get_raw(ext_sha)
  612. offset = f.tell()
  613. crc32 = write_pack_object(
  614. f, type_num, data, sha=new_sha,
  615. compression_level=self.pack_compression_level)
  616. entries.append((ext_sha, offset, crc32))
  617. pack_sha = new_sha.digest()
  618. f.write(pack_sha)
  619. f.close()
  620. # Move the pack in.
  621. entries.sort()
  622. pack_base_name = self._get_pack_basepath(entries)
  623. target_pack = pack_base_name + '.pack'
  624. if sys.platform == 'win32':
  625. # Windows might have the target pack file lingering. Attempt
  626. # removal, silently passing if the target does not exist.
  627. try:
  628. os.remove(target_pack)
  629. except (IOError, OSError) as e:
  630. if e.errno != errno.ENOENT:
  631. raise
  632. os.rename(path, target_pack)
  633. # Write the index.
  634. index_file = GitFile(pack_base_name + '.idx', 'wb')
  635. try:
  636. write_pack_index_v2(index_file, entries, pack_sha)
  637. index_file.close()
  638. finally:
  639. index_file.abort()
  640. # Add the pack to the store and return it.
  641. final_pack = Pack(pack_base_name)
  642. final_pack.check_length_and_checksum()
  643. self._add_cached_pack(pack_base_name, final_pack)
  644. return final_pack
  645. def add_thin_pack(self, read_all, read_some):
  646. """Add a new thin pack to this object store.
  647. Thin packs are packs that contain deltas with parents that exist
  648. outside the pack. They should never be placed in the object store
  649. directly, and always indexed and completed as they are copied.
  650. Args:
  651. read_all: Read function that blocks until the number of
  652. requested bytes are read.
  653. read_some: Read function that returns at least one byte, but may
  654. not return the number of bytes requested.
  655. Returns: A Pack object pointing at the now-completed thin pack in the
  656. objects/pack directory.
  657. """
  658. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  659. with os.fdopen(fd, 'w+b') as f:
  660. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  661. copier = PackStreamCopier(read_all, read_some, f,
  662. delta_iter=indexer)
  663. copier.verify()
  664. return self._complete_thin_pack(f, path, copier, indexer)
  665. def move_in_pack(self, path):
  666. """Move a specific file containing a pack into the pack directory.
  667. Note: The file should be on the same file system as the
  668. packs directory.
  669. Args:
  670. path: Path to the pack file.
  671. """
  672. with PackData(path) as p:
  673. entries = p.sorted_entries()
  674. basename = self._get_pack_basepath(entries)
  675. index_name = basename + ".idx"
  676. if not os.path.exists(index_name):
  677. with GitFile(index_name, "wb") as f:
  678. write_pack_index_v2(f, entries, p.get_stored_checksum())
  679. for pack in self.packs:
  680. if pack._basename == basename:
  681. return pack
  682. target_pack = basename + '.pack'
  683. if sys.platform == 'win32':
  684. # Windows might have the target pack file lingering. Attempt
  685. # removal, silently passing if the target does not exist.
  686. try:
  687. os.remove(target_pack)
  688. except (IOError, OSError) as e:
  689. if e.errno != errno.ENOENT:
  690. raise
  691. os.rename(path, target_pack)
  692. final_pack = Pack(basename)
  693. self._add_cached_pack(basename, final_pack)
  694. return final_pack
  695. def add_pack(self):
  696. """Add a new pack to this object store.
  697. Returns: Fileobject to write to, a commit function to
  698. call when the pack is finished and an abort
  699. function.
  700. """
  701. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  702. f = os.fdopen(fd, 'wb')
  703. def commit():
  704. f.flush()
  705. os.fsync(fd)
  706. f.close()
  707. if os.path.getsize(path) > 0:
  708. return self.move_in_pack(path)
  709. else:
  710. os.remove(path)
  711. return None
  712. def abort():
  713. f.close()
  714. os.remove(path)
  715. return f, commit, abort
  716. def add_object(self, obj):
  717. """Add a single object to this object store.
  718. Args:
  719. obj: Object to add
  720. """
  721. path = self._get_shafile_path(obj.id)
  722. dir = os.path.dirname(path)
  723. try:
  724. os.mkdir(dir)
  725. except OSError as e:
  726. if e.errno != errno.EEXIST:
  727. raise
  728. if os.path.exists(path):
  729. return # Already there, no need to write again
  730. with GitFile(path, 'wb') as f:
  731. f.write(obj.as_legacy_object(
  732. compression_level=self.loose_compression_level))
  733. @classmethod
  734. def init(cls, path):
  735. try:
  736. os.mkdir(path)
  737. except OSError as e:
  738. if e.errno != errno.EEXIST:
  739. raise
  740. os.mkdir(os.path.join(path, "info"))
  741. os.mkdir(os.path.join(path, PACKDIR))
  742. return cls(path)
  743. class MemoryObjectStore(BaseObjectStore):
  744. """Object store that keeps all objects in memory."""
  745. def __init__(self):
  746. super(MemoryObjectStore, self).__init__()
  747. self._data = {}
  748. self.pack_compression_level = -1
  749. def _to_hexsha(self, sha):
  750. if len(sha) == 40:
  751. return sha
  752. elif len(sha) == 20:
  753. return sha_to_hex(sha)
  754. else:
  755. raise ValueError("Invalid sha %r" % (sha,))
  756. def contains_loose(self, sha):
  757. """Check if a particular object is present by SHA1 and is loose."""
  758. return self._to_hexsha(sha) in self._data
  759. def contains_packed(self, sha):
  760. """Check if a particular object is present by SHA1 and is packed."""
  761. return False
  762. def __iter__(self):
  763. """Iterate over the SHAs that are present in this store."""
  764. return iter(self._data.keys())
  765. @property
  766. def packs(self):
  767. """List with pack objects."""
  768. return []
  769. def get_raw(self, name):
  770. """Obtain the raw text for an object.
  771. Args:
  772. name: sha for the object.
  773. Returns: tuple with numeric type and object contents.
  774. """
  775. obj = self[self._to_hexsha(name)]
  776. return obj.type_num, obj.as_raw_string()
  777. def __getitem__(self, name):
  778. return self._data[self._to_hexsha(name)].copy()
  779. def __delitem__(self, name):
  780. """Delete an object from this store, for testing only."""
  781. del self._data[self._to_hexsha(name)]
  782. def add_object(self, obj):
  783. """Add a single object to this object store.
  784. """
  785. self._data[obj.id] = obj.copy()
  786. def add_objects(self, objects, progress=None):
  787. """Add a set of objects to this object store.
  788. Args:
  789. objects: Iterable over a list of (object, path) tuples
  790. """
  791. for obj, path in objects:
  792. self.add_object(obj)
  793. def add_pack(self):
  794. """Add a new pack to this object store.
  795. Because this object store doesn't support packs, we extract and add the
  796. individual objects.
  797. Returns: Fileobject to write to and a commit function to
  798. call when the pack is finished.
  799. """
  800. f = BytesIO()
  801. def commit():
  802. p = PackData.from_file(BytesIO(f.getvalue()), f.tell())
  803. f.close()
  804. for obj in PackInflater.for_pack_data(p, self.get_raw):
  805. self.add_object(obj)
  806. def abort():
  807. pass
  808. return f, commit, abort
  809. def _complete_thin_pack(self, f, indexer):
  810. """Complete a thin pack by adding external references.
  811. Args:
  812. f: Open file object for the pack.
  813. indexer: A PackIndexer for indexing the pack.
  814. """
  815. entries = list(indexer)
  816. # Update the header with the new number of objects.
  817. f.seek(0)
  818. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  819. # Rescan the rest of the pack, computing the SHA with the new header.
  820. new_sha = compute_file_sha(f, end_ofs=-20)
  821. # Complete the pack.
  822. for ext_sha in indexer.ext_refs():
  823. assert len(ext_sha) == 20
  824. type_num, data = self.get_raw(ext_sha)
  825. write_pack_object(
  826. f, type_num, data, sha=new_sha)
  827. pack_sha = new_sha.digest()
  828. f.write(pack_sha)
  829. def add_thin_pack(self, read_all, read_some):
  830. """Add a new thin pack to this object store.
  831. Thin packs are packs that contain deltas with parents that exist
  832. outside the pack. Because this object store doesn't support packs, we
  833. extract and add the individual objects.
  834. Args:
  835. read_all: Read function that blocks until the number of
  836. requested bytes are read.
  837. read_some: Read function that returns at least one byte, but may
  838. not return the number of bytes requested.
  839. """
  840. f, commit, abort = self.add_pack()
  841. try:
  842. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  843. copier = PackStreamCopier(read_all, read_some, f,
  844. delta_iter=indexer)
  845. copier.verify()
  846. self._complete_thin_pack(f, indexer)
  847. except BaseException:
  848. abort()
  849. raise
  850. else:
  851. commit()
  852. class ObjectIterator(object):
  853. """Interface for iterating over objects."""
  854. def iterobjects(self):
  855. raise NotImplementedError(self.iterobjects)
  856. class ObjectStoreIterator(ObjectIterator):
  857. """ObjectIterator that works on top of an ObjectStore."""
  858. def __init__(self, store, sha_iter):
  859. """Create a new ObjectIterator.
  860. Args:
  861. store: Object store to retrieve from
  862. sha_iter: Iterator over (sha, path) tuples
  863. """
  864. self.store = store
  865. self.sha_iter = sha_iter
  866. self._shas = []
  867. def __iter__(self):
  868. """Yield tuple with next object and path."""
  869. for sha, path in self.itershas():
  870. yield self.store[sha], path
  871. def iterobjects(self):
  872. """Iterate over just the objects."""
  873. for o, path in self:
  874. yield o
  875. def itershas(self):
  876. """Iterate over the SHAs."""
  877. for sha in self._shas:
  878. yield sha
  879. for sha in self.sha_iter:
  880. self._shas.append(sha)
  881. yield sha
  882. def __contains__(self, needle):
  883. """Check if an object is present.
  884. Note: This checks if the object is present in
  885. the underlying object store, not if it would
  886. be yielded by the iterator.
  887. Args:
  888. needle: SHA1 of the object to check for
  889. """
  890. if needle == ZERO_SHA:
  891. return False
  892. return needle in self.store
  893. def __getitem__(self, key):
  894. """Find an object by SHA1.
  895. Note: This retrieves the object from the underlying
  896. object store. It will also succeed if the object would
  897. not be returned by the iterator.
  898. """
  899. return self.store[key]
  900. def __len__(self):
  901. """Return the number of objects."""
  902. return len(list(self.itershas()))
  903. def empty(self):
  904. import warnings
  905. warnings.warn('Use bool() instead.', DeprecationWarning)
  906. return self._empty()
  907. def _empty(self):
  908. it = self.itershas()
  909. try:
  910. next(it)
  911. except StopIteration:
  912. return True
  913. else:
  914. return False
  915. def __bool__(self):
  916. """Indicate whether this object has contents."""
  917. return not self._empty()
  918. def tree_lookup_path(lookup_obj, root_sha, path):
  919. """Look up an object in a Git tree.
  920. Args:
  921. lookup_obj: Callback for retrieving object by SHA1
  922. root_sha: SHA1 of the root tree
  923. path: Path to lookup
  924. Returns: A tuple of (mode, SHA) of the resulting path.
  925. """
  926. tree = lookup_obj(root_sha)
  927. if not isinstance(tree, Tree):
  928. raise NotTreeError(root_sha)
  929. return tree.lookup_path(lookup_obj, path)
  930. def _collect_filetree_revs(obj_store, tree_sha, kset):
  931. """Collect SHA1s of files and directories for specified tree.
  932. Args:
  933. obj_store: Object store to get objects by SHA from
  934. tree_sha: tree reference to walk
  935. kset: set to fill with references to files and directories
  936. """
  937. filetree = obj_store[tree_sha]
  938. for name, mode, sha in filetree.iteritems():
  939. if not S_ISGITLINK(mode) and sha not in kset:
  940. kset.add(sha)
  941. if stat.S_ISDIR(mode):
  942. _collect_filetree_revs(obj_store, sha, kset)
  943. def _split_commits_and_tags(obj_store, lst, ignore_unknown=False):
  944. """Split object id list into three lists with commit, tag, and other SHAs.
  945. Commits referenced by tags are included into commits
  946. list as well. Only SHA1s known in this repository will get
  947. through, and unless ignore_unknown argument is True, KeyError
  948. is thrown for SHA1 missing in the repository
  949. Args:
  950. obj_store: Object store to get objects by SHA1 from
  951. lst: Collection of commit and tag SHAs
  952. ignore_unknown: True to skip SHA1 missing in the repository
  953. silently.
  954. Returns: A tuple of (commits, tags, others) SHA1s
  955. """
  956. commits = set()
  957. tags = set()
  958. others = set()
  959. for e in lst:
  960. try:
  961. o = obj_store[e]
  962. except KeyError:
  963. if not ignore_unknown:
  964. raise
  965. else:
  966. if isinstance(o, Commit):
  967. commits.add(e)
  968. elif isinstance(o, Tag):
  969. tags.add(e)
  970. tagged = o.object[1]
  971. c, t, o = _split_commits_and_tags(
  972. obj_store, [tagged], ignore_unknown=ignore_unknown)
  973. commits |= c
  974. tags |= t
  975. others |= o
  976. else:
  977. others.add(e)
  978. return (commits, tags, others)
  979. class MissingObjectFinder(object):
  980. """Find the objects missing from another object store.
  981. Args:
  982. object_store: Object store containing at least all objects to be
  983. sent
  984. haves: SHA1s of commits not to send (already present in target)
  985. wants: SHA1s of commits to send
  986. progress: Optional function to report progress to.
  987. get_tagged: Function that returns a dict of pointed-to sha -> tag
  988. sha for including tags.
  989. get_parents: Optional function for getting the parents of a commit.
  990. tagged: dict of pointed-to sha -> tag sha for including tags
  991. """
  992. def __init__(self, object_store, haves, wants, shallow=None, progress=None,
  993. get_tagged=None, get_parents=lambda commit: commit.parents):
  994. self.object_store = object_store
  995. if shallow is None:
  996. shallow = set()
  997. self._get_parents = get_parents
  998. # process Commits and Tags differently
  999. # Note, while haves may list commits/tags not available locally,
  1000. # and such SHAs would get filtered out by _split_commits_and_tags,
  1001. # wants shall list only known SHAs, and otherwise
  1002. # _split_commits_and_tags fails with KeyError
  1003. have_commits, have_tags, have_others = (
  1004. _split_commits_and_tags(object_store, haves, True))
  1005. want_commits, want_tags, want_others = (
  1006. _split_commits_and_tags(object_store, wants, False))
  1007. # all_ancestors is a set of commits that shall not be sent
  1008. # (complete repository up to 'haves')
  1009. all_ancestors = object_store._collect_ancestors(
  1010. have_commits, shallow=shallow, get_parents=self._get_parents)[0]
  1011. # all_missing - complete set of commits between haves and wants
  1012. # common - commits from all_ancestors we hit into while
  1013. # traversing parent hierarchy of wants
  1014. missing_commits, common_commits = object_store._collect_ancestors(
  1015. want_commits, all_ancestors, shallow=shallow,
  1016. get_parents=self._get_parents)
  1017. self.sha_done = set()
  1018. # Now, fill sha_done with commits and revisions of
  1019. # files and directories known to be both locally
  1020. # and on target. Thus these commits and files
  1021. # won't get selected for fetch
  1022. for h in common_commits:
  1023. self.sha_done.add(h)
  1024. cmt = object_store[h]
  1025. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  1026. # record tags we have as visited, too
  1027. for t in have_tags:
  1028. self.sha_done.add(t)
  1029. missing_tags = want_tags.difference(have_tags)
  1030. missing_others = want_others.difference(have_others)
  1031. # in fact, what we 'want' is commits, tags, and others
  1032. # we've found missing
  1033. wants = missing_commits.union(missing_tags)
  1034. wants = wants.union(missing_others)
  1035. self.objects_to_send = set([(w, None, False) for w in wants])
  1036. if progress is None:
  1037. self.progress = lambda x: None
  1038. else:
  1039. self.progress = progress
  1040. self._tagged = get_tagged and get_tagged() or {}
  1041. def add_todo(self, entries):
  1042. self.objects_to_send.update([e for e in entries
  1043. if not e[0] in self.sha_done])
  1044. def next(self):
  1045. while True:
  1046. if not self.objects_to_send:
  1047. return None
  1048. (sha, name, leaf) = self.objects_to_send.pop()
  1049. if sha not in self.sha_done:
  1050. break
  1051. if not leaf:
  1052. o = self.object_store[sha]
  1053. if isinstance(o, Commit):
  1054. self.add_todo([(o.tree, "", False)])
  1055. elif isinstance(o, Tree):
  1056. self.add_todo([(s, n, not stat.S_ISDIR(m))
  1057. for n, m, s in o.iteritems()
  1058. if not S_ISGITLINK(m)])
  1059. elif isinstance(o, Tag):
  1060. self.add_todo([(o.object[1], None, False)])
  1061. if sha in self._tagged:
  1062. self.add_todo([(self._tagged[sha], None, True)])
  1063. self.sha_done.add(sha)
  1064. self.progress(("counting objects: %d\r" %
  1065. len(self.sha_done)).encode('ascii'))
  1066. return (sha, name)
  1067. __next__ = next
  1068. class ObjectStoreGraphWalker(object):
  1069. """Graph walker that finds what commits are missing from an object store.
  1070. :ivar heads: Revisions without descendants in the local repo
  1071. :ivar get_parents: Function to retrieve parents in the local repo
  1072. """
  1073. def __init__(self, local_heads, get_parents, shallow=None):
  1074. """Create a new instance.
  1075. Args:
  1076. local_heads: Heads to start search with
  1077. get_parents: Function for finding the parents of a SHA1.
  1078. """
  1079. self.heads = set(local_heads)
  1080. self.get_parents = get_parents
  1081. self.parents = {}
  1082. if shallow is None:
  1083. shallow = set()
  1084. self.shallow = shallow
  1085. def ack(self, sha):
  1086. """Ack that a revision and its ancestors are present in the source."""
  1087. if len(sha) != 40:
  1088. raise ValueError("unexpected sha %r received" % sha)
  1089. ancestors = set([sha])
  1090. # stop if we run out of heads to remove
  1091. while self.heads:
  1092. for a in ancestors:
  1093. if a in self.heads:
  1094. self.heads.remove(a)
  1095. # collect all ancestors
  1096. new_ancestors = set()
  1097. for a in ancestors:
  1098. ps = self.parents.get(a)
  1099. if ps is not None:
  1100. new_ancestors.update(ps)
  1101. self.parents[a] = None
  1102. # no more ancestors; stop
  1103. if not new_ancestors:
  1104. break
  1105. ancestors = new_ancestors
  1106. def next(self):
  1107. """Iterate over ancestors of heads in the target."""
  1108. if self.heads:
  1109. ret = self.heads.pop()
  1110. ps = self.get_parents(ret)
  1111. self.parents[ret] = ps
  1112. self.heads.update(
  1113. [p for p in ps if p not in self.parents])
  1114. return ret
  1115. return None
  1116. __next__ = next
  1117. def commit_tree_changes(object_store, tree, changes):
  1118. """Commit a specified set of changes to a tree structure.
  1119. This will apply a set of changes on top of an existing tree, storing new
  1120. objects in object_store.
  1121. changes are a list of tuples with (path, mode, object_sha).
  1122. Paths can be both blobs and trees. See the mode and
  1123. object sha to None deletes the path.
  1124. This method works especially well if there are only a small
  1125. number of changes to a big tree. For a large number of changes
  1126. to a large tree, use e.g. commit_tree.
  1127. Args:
  1128. object_store: Object store to store new objects in
  1129. and retrieve old ones from.
  1130. tree: Original tree root
  1131. changes: changes to apply
  1132. Returns: New tree root object
  1133. """
  1134. # TODO(jelmer): Save up the objects and add them using .add_objects
  1135. # rather than with individual calls to .add_object.
  1136. nested_changes = {}
  1137. for (path, new_mode, new_sha) in changes:
  1138. try:
  1139. (dirname, subpath) = path.split(b'/', 1)
  1140. except ValueError:
  1141. if new_sha is None:
  1142. del tree[path]
  1143. else:
  1144. tree[path] = (new_mode, new_sha)
  1145. else:
  1146. nested_changes.setdefault(dirname, []).append(
  1147. (subpath, new_mode, new_sha))
  1148. for name, subchanges in nested_changes.items():
  1149. try:
  1150. orig_subtree = object_store[tree[name][1]]
  1151. except KeyError:
  1152. orig_subtree = Tree()
  1153. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1154. if len(subtree) == 0:
  1155. del tree[name]
  1156. else:
  1157. tree[name] = (stat.S_IFDIR, subtree.id)
  1158. object_store.add_object(tree)
  1159. return tree
  1160. class OverlayObjectStore(BaseObjectStore):
  1161. """Object store that can overlay multiple object stores."""
  1162. def __init__(self, bases, add_store=None):
  1163. self.bases = bases
  1164. self.add_store = add_store
  1165. def add_object(self, object):
  1166. if self.add_store is None:
  1167. raise NotImplementedError(self.add_object)
  1168. return self.add_store.add_object(object)
  1169. def add_objects(self, objects, progress=None):
  1170. if self.add_store is None:
  1171. raise NotImplementedError(self.add_object)
  1172. return self.add_store.add_objects(objects, progress)
  1173. @property
  1174. def packs(self):
  1175. ret = []
  1176. for b in self.bases:
  1177. ret.extend(b.packs)
  1178. return ret
  1179. def __iter__(self):
  1180. done = set()
  1181. for b in self.bases:
  1182. for o_id in b:
  1183. if o_id not in done:
  1184. yield o_id
  1185. done.add(o_id)
  1186. def get_raw(self, sha_id):
  1187. for b in self.bases:
  1188. try:
  1189. return b.get_raw(sha_id)
  1190. except KeyError:
  1191. pass
  1192. raise KeyError(sha_id)
  1193. def contains_packed(self, sha):
  1194. for b in self.bases:
  1195. if b.contains_packed(sha):
  1196. return True
  1197. return False
  1198. def contains_loose(self, sha):
  1199. for b in self.bases:
  1200. if b.contains_loose(sha):
  1201. return True
  1202. return False
  1203. def read_packs_file(f):
  1204. """Yield the packs listed in a packs file."""
  1205. for line in f.read().splitlines():
  1206. if not line:
  1207. continue
  1208. (kind, name) = line.split(b" ", 1)
  1209. if kind != b"P":
  1210. continue
  1211. yield name.decode(sys.getfilesystemencoding())