2 # Copyright 2009-2013 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
5 from __future__ import print_function
10 # This block ensures that ^C interrupts are handled quietly.
13 def exithandler(signum,frame):
14 signal.signal(signal.SIGINT, signal.SIG_IGN)
15 signal.signal(signal.SIGTERM, signal.SIG_IGN)
16 sys.exit(128 + signum)
18 signal.signal(signal.SIGINT, exithandler)
19 signal.signal(signal.SIGTERM, exithandler)
21 except KeyboardInterrupt:
22 sys.exit(128 + signal.SIGINT)
24 def debug_signal(signum, frame):
28 if platform.python_implementation() == 'Jython':
29 debug_signum = signal.SIGUSR2 # bug #424259
31 debug_signum = signal.SIGUSR1
33 signal.signal(debug_signum, debug_signal)
43 from os import path as osp
44 pym_path = osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym")
45 sys.path.insert(0, pym_path)
47 portage._internal_caller = True
48 from portage import os, _encodings, _unicode_encode, _unicode_decode
49 from _emerge.MetadataRegen import MetadataRegen
50 from portage.cache.cache_errors import CacheError, StatCollision
51 from portage.manifest import guessManifestFileType
52 from portage.package.ebuild._parallel_manifest.ManifestScheduler import ManifestScheduler
53 from portage.util import cmp_sort_key, writemsg_level
54 from portage.util._async.run_main_scheduler import run_main_scheduler
55 from portage.util._eventloop.global_event_loop import global_event_loop
56 from portage import cpv_getkey
57 from portage.dep import Atom, isjustname
58 from portage.versions import pkgsplit, vercmp
61 from xml.etree import ElementTree
66 from xml.parsers.expat import ExpatError
70 from repoman.utilities import parse_metadata_use
72 from repoman.utilities import FindVCS
74 if sys.hexversion >= 0x3000000:
78 usage = "egencache [options] <action> ... [atom] ..."
79 parser = optparse.OptionParser(usage=usage)
81 actions = optparse.OptionGroup(parser, 'Actions')
82 actions.add_option("--update",
84 help="update metadata/cache/ (generate as necessary)")
85 actions.add_option("--update-use-local-desc",
87 help="update the use.local.desc file from metadata.xml")
88 actions.add_option("--update-changelogs",
90 help="update the ChangeLog files from SCM logs")
91 actions.add_option("--update-manifests",
93 help="update manifests")
94 parser.add_option_group(actions)
96 common = optparse.OptionGroup(parser, 'Common options')
97 common.add_option("--repo",
99 help="name of repo to operate on (default repo is located at $PORTDIR)")
100 common.add_option("--config-root",
101 help="location of portage config files",
102 dest="portage_configroot")
103 common.add_option("--gpg-dir",
104 help="override the PORTAGE_GPG_DIR variable",
106 common.add_option("--gpg-key",
107 help="override the PORTAGE_GPG_KEY variable",
109 common.add_option("--portdir",
110 help="override the portage tree location",
112 common.add_option("--portdir-overlay",
113 help="override the PORTDIR_OVERLAY variable (requires that --repo is also specified)",
114 dest="portdir_overlay")
115 common.add_option("--sign-manifests",
119 help="manually override layout.conf sign-manifests setting")
120 common.add_option("--strict-manifests",
124 help="manually override \"strict\" FEATURES setting")
125 common.add_option("--thin-manifests",
129 help="manually override layout.conf thin-manifests setting")
130 common.add_option("--tolerant",
132 help="exit successfully if only minor errors occurred")
133 common.add_option("--ignore-default-opts",
135 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
136 parser.add_option_group(common)
138 update = optparse.OptionGroup(parser, '--update options')
139 update.add_option("--cache-dir",
140 help="location of the metadata cache",
142 update.add_option("-j", "--jobs",
144 help="max ebuild processes to spawn")
145 update.add_option("--load-average",
147 help="max load allowed when spawning multiple jobs",
149 update.add_option("--rsync",
151 help="enable rsync stat collision workaround " + \
152 "for bug 139134 (use with --update)")
153 parser.add_option_group(update)
155 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
156 uld.add_option("--preserve-comments",
158 help="preserve the comments from the existing use.local.desc file")
159 uld.add_option("--use-local-desc-output",
160 help="output file for use.local.desc data (or '-' for stdout)",
162 parser.add_option_group(uld)
164 options, args = parser.parse_args(args)
169 jobs = int(options.jobs)
174 parser.error("Invalid: --jobs='%s'" % \
182 if options.load_average:
184 load_average = float(options.load_average)
188 if load_average <= 0.0:
189 parser.error("Invalid: --load-average='%s'" % \
190 (options.load_average,))
192 options.load_average = load_average
195 options.load_average = None
197 options.config_root = options.portage_configroot
198 if options.config_root is not None and \
199 not os.path.isdir(options.config_root):
200 parser.error("Not a directory: --config-root='%s'" % \
201 (options.config_root,))
203 if options.cache_dir is not None:
204 if not os.path.isdir(options.cache_dir):
205 parser.error("Not a directory: --cache-dir='%s'" % \
206 (options.cache_dir,))
207 if not os.access(options.cache_dir, os.W_OK):
208 parser.error("Write access denied: --cache-dir='%s'" % \
209 (options.cache_dir,))
211 if options.portdir_overlay is not None and \
212 options.repo is None:
213 parser.error("--portdir-overlay option requires --repo option")
217 atom = portage.dep.Atom(atom)
218 except portage.exception.InvalidAtom:
219 parser.error('Invalid atom: %s' % (atom,))
221 if not isjustname(atom):
222 parser.error('Atom is too specific: %s' % (atom,))
224 if options.update_use_local_desc:
229 parser.error('--update-use-local-desc requires python with USE=xml!')
231 if options.uld_output == '-' and options.preserve_comments:
232 parser.error('--preserve-comments can not be used when outputting to stdout')
234 return parser, options, args
236 class GenCache(object):
237 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
239 # The caller must set portdb.porttrees in order to constrain
240 # findname, cp_list, and cpv_list to the desired tree.
241 tree = portdb.porttrees[0]
242 self._portdb = portdb
243 self._eclass_db = portdb.repositories.get_repo_for_location(tree).eclass_db
244 self._auxdbkeys = portdb._known_keys
245 # We can globally cleanse stale cache only if we
246 # iterate over every single cp.
247 self._global_cleanse = cp_iter is None
248 if cp_iter is not None:
249 self._cp_set = set(cp_iter)
250 cp_iter = iter(self._cp_set)
251 self._cp_missing = self._cp_set.copy()
254 self._cp_missing = set()
255 write_auxdb = "metadata-transfer" in portdb.settings.features
256 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
257 consumer=self._metadata_callback,
258 max_jobs=max_jobs, max_load=max_load,
259 write_auxdb=write_auxdb, main=True)
260 self.returncode = os.EX_OK
261 conf = portdb.repositories.get_repo_for_location(tree)
262 self._trg_caches = tuple(conf.iter_pregenerated_caches(
263 self._auxdbkeys, force=True, readonly=False))
264 if not self._trg_caches:
265 raise Exception("cache formats '%s' aren't supported" %
266 (" ".join(conf.cache_formats),))
269 for trg_cache in self._trg_caches:
270 if hasattr(trg_cache, 'raise_stat_collision'):
271 trg_cache.raise_stat_collision = True
272 # Make _metadata_callback write this cache first, in case
273 # it raises a StatCollision and triggers mtime
275 self._trg_caches = tuple([trg_cache] +
276 [x for x in self._trg_caches if x is not trg_cache])
278 self._existing_nodes = set()
280 def _metadata_callback(self, cpv, repo_path, metadata,
281 ebuild_hash, eapi_supported):
282 self._existing_nodes.add(cpv)
283 self._cp_missing.discard(cpv_getkey(cpv))
285 # Since we're supposed to be able to efficiently obtain the
286 # EAPI from _parse_eapi_ebuild_head, we don't write cache
287 # entries for unsupported EAPIs.
288 if metadata is not None and eapi_supported:
289 if metadata.get('EAPI') == '0':
291 for trg_cache in self._trg_caches:
292 self._write_cache(trg_cache,
293 cpv, repo_path, metadata, ebuild_hash)
295 def _write_cache(self, trg_cache, cpv, repo_path, metadata, ebuild_hash):
297 if not hasattr(trg_cache, 'raise_stat_collision'):
298 # This cache does not avoid redundant writes automatically,
299 # so check for an identical existing entry before writing.
300 # This prevents unnecessary disk writes and can also prevent
301 # unnecessary rsync transfers.
303 dest = trg_cache[cpv]
304 except (KeyError, CacheError):
307 if trg_cache.validate_entry(dest,
308 ebuild_hash, self._eclass_db):
310 for k in self._auxdbkeys:
311 if dest.get(k, '') != metadata.get(k, ''):
318 chf = trg_cache.validation_chf
319 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
321 trg_cache[cpv] = metadata
322 except StatCollision as sc:
323 # If the content of a cache entry changes and neither the
324 # file mtime nor size changes, it will prevent rsync from
325 # detecting changes. Cache backends may raise this
326 # exception from _setitem() if they detect this type of stat
327 # collision. These exceptions are handled by bumping the
328 # mtime on the ebuild (and the corresponding cache entry).
329 # See bug #139134. It is convenient to include checks for
330 # redundant writes along with the internal StatCollision
331 # detection code, so for caches with the
332 # raise_stat_collision attribute, we do not need to
333 # explicitly check for redundant writes like we do for the
334 # other cache types above.
336 for ec, ec_hash in metadata['_eclasses_'].items():
337 if max_mtime < ec_hash.mtime:
338 max_mtime = ec_hash.mtime
339 if max_mtime == sc.mtime:
341 max_mtime = long(max_mtime)
343 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
347 "%s writing target: %s\n" % (cpv, e),
348 level=logging.ERROR, noiselevel=-1)
350 ebuild_hash.mtime = max_mtime
351 metadata['_mtime_'] = max_mtime
352 trg_cache[cpv] = metadata
353 self._portdb.auxdb[repo_path][cpv] = metadata
355 except CacheError as ce:
358 "%s writing target: %s\n" % (cpv, ce),
359 level=logging.ERROR, noiselevel=-1)
362 signum = run_main_scheduler(self._regen)
363 if signum is not None:
364 sys.exit(128 + signum)
366 self.returncode |= self._regen.returncode
368 for trg_cache in self._trg_caches:
369 self._cleanse_cache(trg_cache)
371 def _cleanse_cache(self, trg_cache):
372 cp_missing = self._cp_missing
374 if self._global_cleanse:
376 for cpv in trg_cache:
381 "Unable to parse cp for '%s'\n" % (cpv,),
382 level=logging.ERROR, noiselevel=-1)
385 except CacheError as ce:
388 "Error listing cache entries for " + \
389 "'%s/metadata/cache': %s, continuing...\n" % \
390 (self._portdb.porttree_root, ce),
391 level=logging.ERROR, noiselevel=-1)
394 cp_set = self._cp_set
396 for cpv in trg_cache:
401 "Unable to parse cp for '%s'\n" % (cpv,),
402 level=logging.ERROR, noiselevel=-1)
404 cp_missing.discard(cp)
407 except CacheError as ce:
410 "Error listing cache entries for " + \
411 "'%s/metadata/cache': %s, continuing...\n" % \
412 (self._portdb.porttree_root, ce),
413 level=logging.ERROR, noiselevel=-1)
417 for cp in sorted(cp_missing):
419 "No ebuilds or cache entries found for '%s'\n" % (cp,),
420 level=logging.ERROR, noiselevel=-1)
423 dead_nodes.difference_update(self._existing_nodes)
429 except CacheError as ce:
432 "%s deleting stale cache: %s\n" % (k, ce),
433 level=logging.ERROR, noiselevel=-1)
435 if not trg_cache.autocommits:
438 except CacheError as ce:
441 "committing target: %s\n" % (ce,),
442 level=logging.ERROR, noiselevel=-1)
444 if hasattr(trg_cache, '_prune_empty_dirs'):
445 trg_cache._prune_empty_dirs()
447 class GenUseLocalDesc(object):
448 def __init__(self, portdb, output=None,
449 preserve_comments=False):
450 self.returncode = os.EX_OK
451 self._portdb = portdb
452 self._output = output
453 self._preserve_comments = preserve_comments
456 repo_path = self._portdb.porttrees[0]
457 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
459 if self._output is None or self._output != '-':
460 if self._output is None:
461 prof_path = os.path.join(repo_path, 'profiles')
462 desc_path = os.path.join(prof_path, 'use.local.desc')
468 desc_path = self._output
471 if self._preserve_comments:
472 # Probe in binary mode, in order to avoid
473 # potential character encoding issues.
474 output = open(_unicode_encode(desc_path,
475 encoding=_encodings['fs'], errors='strict'), 'r+b')
477 output = io.open(_unicode_encode(desc_path,
478 encoding=_encodings['fs'], errors='strict'),
479 mode='w', encoding=_encodings['repo.content'],
480 errors='backslashreplace')
482 if not self._preserve_comments or \
483 os.path.isfile(desc_path):
485 "ERROR: failed to open output file %s: %s\n" \
486 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
490 # Open in r+b mode failed because the file doesn't
491 # exist yet. We can probably recover if we disable
492 # preserve_comments mode now.
494 "WARNING: --preserve-comments enabled, but " + \
495 "output file not found: %s\n" % (desc_path,),
496 level=logging.WARNING, noiselevel=-1)
497 self._preserve_comments = False
499 output = io.open(_unicode_encode(desc_path,
500 encoding=_encodings['fs'], errors='strict'),
501 mode='w', encoding=_encodings['repo.content'],
502 errors='backslashreplace')
505 "ERROR: failed to open output file %s: %s\n" \
506 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
512 if self._preserve_comments:
515 if not output.readline().startswith(b'#'):
521 # Finished probing comments in binary mode, now append
523 output = io.open(_unicode_encode(desc_path,
524 encoding=_encodings['fs'], errors='strict'),
525 mode='a', encoding=_encodings['repo.content'],
526 errors='backslashreplace')
527 output.write(_unicode_decode('\n'))
529 output.write(textwrap.dedent(_unicode_decode('''\
530 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
531 # your descriptions to your package's metadata.xml ONLY.
532 # * generated automatically using egencache *
536 # The cmp function no longer exists in python3, so we'll
537 # implement our own here under a slightly different name
538 # since we don't want any confusion given that we never
539 # want to rely on the builtin cmp function.
541 if a is None or b is None:
542 # None can't be compared with other types in python3.
543 if a is None and b is None:
549 return (a > b) - (a < b)
551 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
553 Implements doctype() as required to avoid deprecation warnings
556 def doctype(self, name, pubid, system):
559 for cp in self._portdb.cp_all():
560 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
562 metadata = ElementTree.parse(_unicode_encode(metadata_path,
563 encoding=_encodings['fs'], errors='strict'),
564 parser=ElementTree.XMLParser(
565 target=_MetadataTreeBuilder()))
568 except (ExpatError, EnvironmentError) as e:
570 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
571 level=logging.ERROR, noiselevel=-1)
575 usedict = parse_metadata_use(metadata)
576 except portage.exception.ParseError as e:
578 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
579 level=logging.ERROR, noiselevel=-1)
582 for flag in sorted(usedict):
583 def atomcmp(atoma, atomb):
584 # None is better than an atom, that's why we reverse the args
585 if atoma is None or atomb is None:
586 return cmp_func(atomb, atoma)
587 # Same for plain PNs (.operator is None then)
588 elif atoma.operator is None or atomb.operator is None:
589 return cmp_func(atomb.operator, atoma.operator)
591 elif atoma.cpv != atomb.cpv:
592 return vercmp(atoma.version, atomb.version)
593 # Versions match, let's fallback to operator matching
595 return cmp_func(ops.get(atoma.operator, -1),
596 ops.get(atomb.operator, -1))
603 resdict = usedict[flag]
604 if len(resdict) == 1:
605 resdesc = next(iter(resdict.items()))[1]
608 reskeys = dict((_Atom(k), k) for k in resdict)
609 except portage.exception.InvalidAtom as e:
611 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
612 level=logging.ERROR, noiselevel=-1)
614 resdesc = next(iter(resdict.items()))[1]
616 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
617 resdesc = resdict[reskeys[resatoms[-1]]]
619 output.write(_unicode_decode(
620 '%s:%s - %s\n' % (cp, flag, resdesc)))
624 if sys.hexversion < 0x3000000:
625 _filename_base = unicode
629 class _special_filename(_filename_base):
631 Helps to sort file names by file type and other criteria.
633 def __new__(cls, status_change, file_name):
634 return _filename_base.__new__(cls, status_change + file_name)
636 def __init__(self, status_change, file_name):
637 _filename_base.__init__(status_change + file_name)
638 self.status_change = status_change
639 self.file_name = file_name
640 self.file_type = guessManifestFileType(file_name)
642 def file_type_lt(self, a, b):
644 Defines an ordering between file types.
651 if first == "EBUILD":
653 elif first == "MISC":
654 return second in ("EBUILD",)
656 return second in ("EBUILD", "MISC")
657 elif first == "DIST":
658 return second in ("EBUILD", "MISC", "AUX")
662 raise ValueError("Unknown file type '%s'" % first)
664 def __lt__(self, other):
666 Compare different file names, first by file type and then
667 for ebuilds by version and lexicographically for others.
668 EBUILD < MISC < AUX < DIST < None
670 if self.__class__ != other.__class__:
671 raise NotImplementedError
673 # Sort by file type as defined by file_type_lt().
674 if self.file_type_lt(self, other):
676 elif self.file_type_lt(other, self):
679 # Files have the same type.
680 if self.file_type == "EBUILD":
681 # Sort by version. Lowest first.
682 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
683 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
684 return vercmp(ver, other_ver) < 0
686 # Sort lexicographically.
687 return self.file_name < other.file_name
689 class GenChangeLogs(object):
690 def __init__(self, portdb):
691 self.returncode = os.EX_OK
692 self._portdb = portdb
693 self._wrapper = textwrap.TextWrapper(
695 initial_indent = ' ',
696 subsequent_indent = ' '
701 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
702 return _unicode_decode(p.communicate()[0],
703 encoding=_encodings['stdio'], errors='strict')
705 def generate_changelog(self, cp):
707 output = io.open('ChangeLog',
708 mode='w', encoding=_encodings['repo.content'],
709 errors='backslashreplace')
712 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
713 level=logging.ERROR, noiselevel=-1)
717 output.write(textwrap.dedent(_unicode_decode('''\
719 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
722 ''' % (cp, time.strftime('%Y')))))
724 # now grab all the commits
725 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
728 # Explaining the arguments:
729 # --name-status to get a list of added/removed files
730 # --no-renames to avoid getting more complex records on the list
731 # --format to get the timestamp, author and commit description
732 # --root to make it work fine even with the initial commit
733 # --relative to get paths relative to ebuilddir
734 # -r (recursive) to get per-file changes
735 # then the commit-id and path.
737 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
738 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
739 c, '--', '.']).rstrip('\n').split('\n')
742 # timestamp Author Name <author@email>
752 for n, l in enumerate(reversed(cinfo)):
758 if f[1] == 'Manifest':
759 pass # XXX: remanifest commits?
760 elif f[1] == 'ChangeLog':
762 elif f[0].startswith('A'):
763 changed.append(_special_filename("+", f[1]))
764 elif f[0].startswith('D'):
765 changed.append(_special_filename("-", f[1]))
766 elif f[0].startswith('M'):
767 changed.append(_special_filename("", f[1]))
770 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
771 level=logging.ERROR, noiselevel=-1)
777 (ts, author) = cinfo[0].split(' ', 1)
778 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
780 changed = [str(x) for x in sorted(changed)]
783 # Reverse the sort order for headers.
784 for c in reversed(changed):
785 if c.startswith('+') and c.endswith('.ebuild'):
786 output.write(_unicode_decode(
787 '*%s (%s)\n' % (c[1:-7], date)))
790 output.write(_unicode_decode('\n'))
792 # strip '<cp>: ', '[<cp>] ', and similar
793 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
794 # strip trailing newline
798 if body[-1].startswith('git-svn-id:') and not body[-2]:
800 # strip the repoman version/manifest note
801 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
803 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
808 # don't break filenames on hyphens
809 self._wrapper.break_on_hyphens = False
810 output.write(_unicode_decode(
812 '%s; %s %s:' % (date, author, ', '.join(changed)))))
813 # but feel free to break commit messages there
814 self._wrapper.break_on_hyphens = True
815 output.write(_unicode_decode(
816 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body)))
821 repo_path = self._portdb.porttrees[0]
824 if 'git' not in FindVCS():
826 "ERROR: --update-changelogs supported only in git repos\n",
827 level=logging.ERROR, noiselevel=-1)
828 self.returncode = 127
831 for cp in self._portdb.cp_all():
832 os.chdir(os.path.join(repo_path, cp))
833 # Determine whether ChangeLog is up-to-date by comparing
834 # the newest commit timestamp with the ChangeLog timestamp.
835 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
837 # This cp has not been added to the repo.
841 cmod = os.stat('ChangeLog').st_mtime
845 if float(cmod) < float(lmod):
846 self.generate_changelog(cp)
848 def egencache_main(args):
849 parser, options, atoms = parse_args(args)
851 config_root = options.config_root
853 # The calling environment is ignored, so the program is
854 # completely controlled by commandline arguments.
857 if options.repo is None:
858 env['PORTDIR_OVERLAY'] = ''
859 elif options.portdir_overlay:
860 env['PORTDIR_OVERLAY'] = options.portdir_overlay
862 if options.cache_dir is not None:
863 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
865 if options.portdir is not None:
866 env['PORTDIR'] = options.portdir
868 settings = portage.config(config_root=config_root,
869 local_config=False, env=env)
872 if not options.ignore_default_opts:
873 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
876 parser, options, args = parse_args(default_opts + args)
878 if options.cache_dir is not None:
879 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
881 settings = portage.config(config_root=config_root,
882 local_config=False, env=env)
884 if not (options.update or options.update_use_local_desc or
885 options.update_changelogs or options.update_manifests):
886 parser.error('No action specified')
890 if options.repo is not None:
891 repo_path = settings.repositories.treemap.get(options.repo)
892 if repo_path is None:
893 parser.error("Unable to locate repository named '%s'" % \
897 repo_path = settings.repositories.mainRepoLocation()
899 parser.error("PORTDIR is undefined")
902 repo_config = settings.repositories.get_repo_for_location(repo_path)
904 if options.strict_manifests is not None:
905 if options.strict_manifests == "y":
906 settings.features.add("strict")
908 settings.features.discard("strict")
910 if options.update and 'metadata-transfer' not in settings.features:
911 # Forcibly enable metadata-transfer if portdbapi has a pregenerated
912 # cache that does not support eclass validation.
913 cache = repo_config.get_pregenerated_cache(
914 portage.dbapi.dbapi._known_keys, readonly=True)
915 if cache is not None and not cache.complete_eclass_entries:
916 settings.features.add('metadata-transfer')
921 portdb = portage.portdbapi(mysettings=settings)
923 # Limit ebuilds to the specified repo.
924 portdb.porttrees = [repo_path]
927 if options.cache_dir is not None:
928 # already validated earlier
931 # We check write access after the portdbapi constructor
932 # has had an opportunity to create it. This ensures that
933 # we don't use the cache in the "volatile" mode which is
934 # undesirable for egencache.
935 if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
936 writemsg_level("ecachegen: error: " + \
937 "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
938 level=logging.ERROR, noiselevel=-1)
941 if options.sign_manifests is not None:
942 repo_config.sign_manifest = options.sign_manifests == 'y'
944 if options.thin_manifests is not None:
945 repo_config.thin_manifest = options.thin_manifests == 'y'
949 force_sign_key = None
951 if options.update_manifests:
952 if repo_config.sign_manifest:
956 gpg_cmd = settings.get("PORTAGE_GPG_SIGNING_COMMAND")
958 writemsg_level("egencache: error: "
959 "PORTAGE_GPG_SIGNING_COMMAND is unset! "
960 "Is make.globals missing?\n",
961 level=logging.ERROR, noiselevel=-1)
963 elif "${PORTAGE_GPG_KEY}" in gpg_cmd and \
964 options.gpg_key is None and \
965 "PORTAGE_GPG_KEY" not in settings:
966 writemsg_level("egencache: error: "
967 "PORTAGE_GPG_KEY is unset!\n",
968 level=logging.ERROR, noiselevel=-1)
970 elif "${PORTAGE_GPG_DIR}" in gpg_cmd:
971 if options.gpg_dir is not None:
972 gpg_dir = options.gpg_dir
973 elif "PORTAGE_GPG_DIR" not in settings:
974 gpg_dir = os.path.expanduser("~/.gnupg")
976 gpg_dir = os.path.expanduser(settings["PORTAGE_GPG_DIR"])
977 if not os.access(gpg_dir, os.X_OK):
978 writemsg_level(("egencache: error: "
979 "Unable to access directory: "
980 "PORTAGE_GPG_DIR='%s'\n") % gpg_dir,
981 level=logging.ERROR, noiselevel=-1)
985 writemsg_level("egencache: You may disable manifest "
986 "signatures with --sign-manifests=n or by setting "
987 "\"sign-manifests = false\" in metadata/layout.conf\n",
988 level=logging.ERROR, noiselevel=-1)
992 if gpg_dir is not None:
993 gpg_vars["PORTAGE_GPG_DIR"] = gpg_dir
995 if options.gpg_key is None:
996 gpg_var_names.append("PORTAGE_GPG_KEY")
998 gpg_vars["PORTAGE_GPG_KEY"] = options.gpg_key
1000 for k in gpg_var_names:
1005 force_sign_key = gpg_vars.get("PORTAGE_GPG_KEY")
1012 cp_iter = iter(atoms)
1014 gen_cache = GenCache(portdb, cp_iter=cp_iter,
1015 max_jobs=options.jobs,
1016 max_load=options.load_average,
1017 rsync=options.rsync)
1019 if options.tolerant:
1020 ret.append(os.EX_OK)
1022 ret.append(gen_cache.returncode)
1024 if options.update_manifests:
1028 cp_iter = iter(atoms)
1030 event_loop = global_event_loop()
1031 scheduler = ManifestScheduler(portdb, cp_iter=cp_iter,
1032 gpg_cmd=gpg_cmd, gpg_vars=gpg_vars,
1033 force_sign_key=force_sign_key,
1034 max_jobs=options.jobs,
1035 max_load=options.load_average,
1036 event_loop=event_loop)
1038 signum = run_main_scheduler(scheduler)
1039 if signum is not None:
1040 sys.exit(128 + signum)
1042 if options.tolerant:
1043 ret.append(os.EX_OK)
1045 ret.append(scheduler.returncode)
1047 if options.update_use_local_desc:
1048 gen_desc = GenUseLocalDesc(portdb,
1049 output=options.uld_output,
1050 preserve_comments=options.preserve_comments)
1052 ret.append(gen_desc.returncode)
1054 if options.update_changelogs:
1055 gen_clogs = GenChangeLogs(portdb)
1057 ret.append(gen_clogs.returncode)
1061 if __name__ == "__main__":
1062 portage._disable_legacy_globals()
1063 portage.util.noiselimit = -1
1064 sys.exit(egencache_main(sys.argv[1:]))