2 # Copyright 2009-2013 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
5 # unicode_literals for compat with TextIOWrapper in Python 2
6 from __future__ import print_function, unicode_literals
11 # This block ensures that ^C interrupts are handled quietly.
14 def exithandler(signum,frame):
15 signal.signal(signal.SIGINT, signal.SIG_IGN)
16 signal.signal(signal.SIGTERM, signal.SIG_IGN)
17 sys.exit(128 + signum)
19 signal.signal(signal.SIGINT, exithandler)
20 signal.signal(signal.SIGTERM, exithandler)
22 except KeyboardInterrupt:
23 sys.exit(128 + signal.SIGINT)
25 def debug_signal(signum, frame):
29 if platform.python_implementation() == 'Jython':
30 debug_signum = signal.SIGUSR2 # bug #424259
32 debug_signum = signal.SIGUSR1
34 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._argparse import ArgumentParser
55 from portage.util._async.run_main_scheduler import run_main_scheduler
56 from portage.util._eventloop.global_event_loop import global_event_loop
57 from portage import cpv_getkey
58 from portage.dep import Atom, isjustname
59 from portage.versions import pkgsplit, vercmp
62 from xml.etree import ElementTree
67 from xml.parsers.expat import ExpatError
71 from repoman.utilities import parse_metadata_use
73 from repoman.utilities import FindVCS
75 if sys.hexversion >= 0x3000000:
79 usage = "egencache [options] <action> ... [atom] ..."
80 parser = ArgumentParser(usage=usage)
82 actions = parser.add_argument_group('Actions')
83 actions.add_argument("--update",
85 help="update metadata/md5-cache/ (generate as necessary)")
86 actions.add_argument("--update-use-local-desc",
88 help="update the use.local.desc file from metadata.xml")
89 actions.add_argument("--update-changelogs",
91 help="update the ChangeLog files from SCM logs")
92 actions.add_argument("--update-manifests",
94 help="update manifests")
96 common = parser.add_argument_group('Common options')
97 common.add_argument("--repo",
99 help="name of repo to operate on")
100 common.add_argument("--config-root",
101 help="location of portage config files",
102 dest="portage_configroot")
103 common.add_argument("--gpg-dir",
104 help="override the PORTAGE_GPG_DIR variable",
106 common.add_argument("--gpg-key",
107 help="override the PORTAGE_GPG_KEY variable",
109 common.add_argument("--portdir",
110 help="override the PORTDIR variable (deprecated in favor of --repositories-configuration)",
112 common.add_argument("--portdir-overlay",
113 help="override the PORTDIR_OVERLAY variable (deprecated in favor of --repositories-configuration)",
114 dest="portdir_overlay")
115 common.add_argument("--repositories-configuration",
116 help="override configuration of repositories (in format of repos.conf)",
117 dest="repositories_configuration")
118 common.add_argument("--sign-manifests",
121 help="manually override layout.conf sign-manifests setting")
122 common.add_argument("--strict-manifests",
125 help="manually override \"strict\" FEATURES setting")
126 common.add_argument("--thin-manifests",
129 help="manually override layout.conf thin-manifests setting")
130 common.add_argument("--tolerant",
132 help="exit successfully if only minor errors occurred")
133 common.add_argument("--ignore-default-opts",
135 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
137 update = parser.add_argument_group('--update options')
138 update.add_argument("--cache-dir",
139 help="location of the metadata cache",
141 update.add_argument("-j", "--jobs",
144 help="max ebuild processes to spawn")
145 update.add_argument("--load-average",
148 help="max load allowed when spawning multiple jobs",
150 update.add_argument("--rsync",
152 help="enable rsync stat collision workaround " + \
153 "for bug 139134 (use with --update)")
155 uld = parser.add_argument_group('--update-use-local-desc options')
156 uld.add_argument("--preserve-comments",
158 help="preserve the comments from the existing use.local.desc file")
159 uld.add_argument("--use-local-desc-output",
160 help="output file for use.local.desc data (or '-' for stdout)",
163 options, args = parser.parse_known_args(args)
168 jobs = int(options.jobs)
173 parser.error("Invalid: --jobs='%s'" % \
181 if options.load_average:
183 load_average = float(options.load_average)
187 if load_average <= 0.0:
188 parser.error("Invalid: --load-average='%s'" % \
189 (options.load_average,))
191 options.load_average = load_average
194 options.load_average = None
196 options.config_root = options.portage_configroot
197 if options.config_root is not None and \
198 not os.path.isdir(options.config_root):
199 parser.error("Not a directory: --config-root='%s'" % \
200 (options.config_root,))
202 if options.cache_dir is not None:
203 if not os.path.isdir(options.cache_dir):
204 parser.error("Not a directory: --cache-dir='%s'" % \
205 (options.cache_dir,))
206 if not os.access(options.cache_dir, os.W_OK):
207 parser.error("Write access denied: --cache-dir='%s'" % \
208 (options.cache_dir,))
210 if options.portdir is not None:
211 writemsg_level("egencache: warning: --portdir option is deprecated in favor of --repositories-configuration option\n",
212 level=logging.WARNING, noiselevel=-1)
213 if options.portdir_overlay is not None:
214 writemsg_level("egencache: warning: --portdir-overlay option is deprecated in favor of --repositories-configuration option\n",
215 level=logging.WARNING, noiselevel=-1)
219 atom = portage.dep.Atom(atom)
220 except portage.exception.InvalidAtom:
221 parser.error('Invalid atom: %s' % (atom,))
223 if not isjustname(atom):
224 parser.error('Atom is too specific: %s' % (atom,))
226 if options.update_use_local_desc:
231 parser.error('--update-use-local-desc requires python with USE=xml!')
233 if options.uld_output == '-' and options.preserve_comments:
234 parser.error('--preserve-comments can not be used when outputting to stdout')
236 return parser, options, args
238 class GenCache(object):
239 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
241 # The caller must set portdb.porttrees in order to constrain
242 # findname, cp_list, and cpv_list to the desired tree.
243 tree = portdb.porttrees[0]
244 self._portdb = portdb
245 self._eclass_db = portdb.repositories.get_repo_for_location(tree).eclass_db
246 self._auxdbkeys = portdb._known_keys
247 # We can globally cleanse stale cache only if we
248 # iterate over every single cp.
249 self._global_cleanse = cp_iter is None
250 if cp_iter is not None:
251 self._cp_set = set(cp_iter)
252 cp_iter = iter(self._cp_set)
253 self._cp_missing = self._cp_set.copy()
256 self._cp_missing = set()
257 write_auxdb = "metadata-transfer" in portdb.settings.features
258 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
259 consumer=self._metadata_callback,
260 max_jobs=max_jobs, max_load=max_load,
261 write_auxdb=write_auxdb, main=True)
262 self.returncode = os.EX_OK
263 conf = portdb.repositories.get_repo_for_location(tree)
264 self._trg_caches = tuple(conf.iter_pregenerated_caches(
265 self._auxdbkeys, force=True, readonly=False))
266 if not self._trg_caches:
267 raise Exception("cache formats '%s' aren't supported" %
268 (" ".join(conf.cache_formats),))
271 for trg_cache in self._trg_caches:
272 if hasattr(trg_cache, 'raise_stat_collision'):
273 trg_cache.raise_stat_collision = True
274 # Make _metadata_callback write this cache first, in case
275 # it raises a StatCollision and triggers mtime
277 self._trg_caches = tuple([trg_cache] +
278 [x for x in self._trg_caches if x is not trg_cache])
280 self._existing_nodes = set()
282 def _metadata_callback(self, cpv, repo_path, metadata,
283 ebuild_hash, eapi_supported):
284 self._existing_nodes.add(cpv)
285 self._cp_missing.discard(cpv_getkey(cpv))
287 # Since we're supposed to be able to efficiently obtain the
288 # EAPI from _parse_eapi_ebuild_head, we don't write cache
289 # entries for unsupported EAPIs.
290 if metadata is not None and eapi_supported:
291 if metadata.get('EAPI') == '0':
293 for trg_cache in self._trg_caches:
294 self._write_cache(trg_cache,
295 cpv, repo_path, metadata, ebuild_hash)
297 def _write_cache(self, trg_cache, cpv, repo_path, metadata, ebuild_hash):
299 if not hasattr(trg_cache, 'raise_stat_collision'):
300 # This cache does not avoid redundant writes automatically,
301 # so check for an identical existing entry before writing.
302 # This prevents unnecessary disk writes and can also prevent
303 # unnecessary rsync transfers.
305 dest = trg_cache[cpv]
306 except (KeyError, CacheError):
309 if trg_cache.validate_entry(dest,
310 ebuild_hash, self._eclass_db):
312 for k in self._auxdbkeys:
313 if dest.get(k, '') != metadata.get(k, ''):
320 chf = trg_cache.validation_chf
321 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
323 trg_cache[cpv] = metadata
324 except StatCollision as sc:
325 # If the content of a cache entry changes and neither the
326 # file mtime nor size changes, it will prevent rsync from
327 # detecting changes. Cache backends may raise this
328 # exception from _setitem() if they detect this type of stat
329 # collision. These exceptions are handled by bumping the
330 # mtime on the ebuild (and the corresponding cache entry).
331 # See bug #139134. It is convenient to include checks for
332 # redundant writes along with the internal StatCollision
333 # detection code, so for caches with the
334 # raise_stat_collision attribute, we do not need to
335 # explicitly check for redundant writes like we do for the
336 # other cache types above.
338 for ec, ec_hash in metadata['_eclasses_'].items():
339 if max_mtime < ec_hash.mtime:
340 max_mtime = ec_hash.mtime
341 if max_mtime == sc.mtime:
343 max_mtime = long(max_mtime)
345 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
349 "%s writing target: %s\n" % (cpv, e),
350 level=logging.ERROR, noiselevel=-1)
352 ebuild_hash.mtime = max_mtime
353 metadata['_mtime_'] = max_mtime
354 trg_cache[cpv] = metadata
355 self._portdb.auxdb[repo_path][cpv] = metadata
357 except CacheError as ce:
360 "%s writing target: %s\n" % (cpv, ce),
361 level=logging.ERROR, noiselevel=-1)
364 signum = run_main_scheduler(self._regen)
365 if signum is not None:
366 sys.exit(128 + signum)
368 self.returncode |= self._regen.returncode
370 for trg_cache in self._trg_caches:
371 self._cleanse_cache(trg_cache)
373 def _cleanse_cache(self, trg_cache):
374 cp_missing = self._cp_missing
376 if self._global_cleanse:
378 for cpv in trg_cache:
383 "Unable to parse cp for '%s'\n" % (cpv,),
384 level=logging.ERROR, noiselevel=-1)
387 except CacheError as ce:
390 "Error listing cache entries for " + \
391 "'%s': %s, continuing...\n" % \
392 (trg_cache.location, ce),
393 level=logging.ERROR, noiselevel=-1)
396 cp_set = self._cp_set
398 for cpv in trg_cache:
403 "Unable to parse cp for '%s'\n" % (cpv,),
404 level=logging.ERROR, noiselevel=-1)
406 cp_missing.discard(cp)
409 except CacheError as ce:
412 "Error listing cache entries for " + \
413 "'%s': %s, continuing...\n" % \
414 (trg_cache.location, ce),
415 level=logging.ERROR, noiselevel=-1)
419 for cp in sorted(cp_missing):
421 "No ebuilds or cache entries found for '%s'\n" % (cp,),
422 level=logging.ERROR, noiselevel=-1)
425 dead_nodes.difference_update(self._existing_nodes)
431 except CacheError as ce:
434 "%s deleting stale cache: %s\n" % (k, ce),
435 level=logging.ERROR, noiselevel=-1)
437 if not trg_cache.autocommits:
440 except CacheError as ce:
443 "committing target: %s\n" % (ce,),
444 level=logging.ERROR, noiselevel=-1)
446 if hasattr(trg_cache, '_prune_empty_dirs'):
447 trg_cache._prune_empty_dirs()
449 class GenUseLocalDesc(object):
450 def __init__(self, portdb, output=None,
451 preserve_comments=False):
452 self.returncode = os.EX_OK
453 self._portdb = portdb
454 self._output = output
455 self._preserve_comments = preserve_comments
458 repo_path = self._portdb.porttrees[0]
459 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
461 if self._output is None or self._output != '-':
462 if self._output is None:
463 prof_path = os.path.join(repo_path, 'profiles')
464 desc_path = os.path.join(prof_path, 'use.local.desc')
470 desc_path = self._output
473 if self._preserve_comments:
474 # Probe in binary mode, in order to avoid
475 # potential character encoding issues.
476 output = open(_unicode_encode(desc_path,
477 encoding=_encodings['fs'], errors='strict'), 'r+b')
479 output = io.open(_unicode_encode(desc_path,
480 encoding=_encodings['fs'], errors='strict'),
481 mode='w', encoding=_encodings['repo.content'],
482 errors='backslashreplace')
484 if not self._preserve_comments or \
485 os.path.isfile(desc_path):
487 "ERROR: failed to open output file %s: %s\n" \
488 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
492 # Open in r+b mode failed because the file doesn't
493 # exist yet. We can probably recover if we disable
494 # preserve_comments mode now.
496 "WARNING: --preserve-comments enabled, but " + \
497 "output file not found: %s\n" % (desc_path,),
498 level=logging.WARNING, noiselevel=-1)
499 self._preserve_comments = False
501 output = io.open(_unicode_encode(desc_path,
502 encoding=_encodings['fs'], errors='strict'),
503 mode='w', encoding=_encodings['repo.content'],
504 errors='backslashreplace')
507 "ERROR: failed to open output file %s: %s\n" \
508 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
514 if self._preserve_comments:
517 if not output.readline().startswith(b'#'):
523 # Finished probing comments in binary mode, now append
525 output = io.open(_unicode_encode(desc_path,
526 encoding=_encodings['fs'], errors='strict'),
527 mode='a', encoding=_encodings['repo.content'],
528 errors='backslashreplace')
531 output.write(textwrap.dedent('''\
532 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
533 # your descriptions to your package's metadata.xml ONLY.
534 # * generated automatically using egencache *
538 # The cmp function no longer exists in python3, so we'll
539 # implement our own here under a slightly different name
540 # since we don't want any confusion given that we never
541 # want to rely on the builtin cmp function.
543 if a is None or b is None:
544 # None can't be compared with other types in python3.
545 if a is None and b is None:
551 return (a > b) - (a < b)
553 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
555 Implements doctype() as required to avoid deprecation warnings
558 def doctype(self, name, pubid, system):
561 for cp in self._portdb.cp_all():
562 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
564 metadata = ElementTree.parse(_unicode_encode(metadata_path,
565 encoding=_encodings['fs'], errors='strict'),
566 parser=ElementTree.XMLParser(
567 target=_MetadataTreeBuilder()))
570 except (ExpatError, EnvironmentError) as e:
572 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
573 level=logging.ERROR, noiselevel=-1)
577 usedict = parse_metadata_use(metadata)
578 except portage.exception.ParseError as e:
580 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
581 level=logging.ERROR, noiselevel=-1)
584 for flag in sorted(usedict):
585 def atomcmp(atoma, atomb):
586 # None is better than an atom, that's why we reverse the args
587 if atoma is None or atomb is None:
588 return cmp_func(atomb, atoma)
589 # Same for plain PNs (.operator is None then)
590 elif atoma.operator is None or atomb.operator is None:
591 return cmp_func(atomb.operator, atoma.operator)
593 elif atoma.cpv != atomb.cpv:
594 return vercmp(atoma.version, atomb.version)
595 # Versions match, let's fallback to operator matching
597 return cmp_func(ops.get(atoma.operator, -1),
598 ops.get(atomb.operator, -1))
605 resdict = usedict[flag]
606 if len(resdict) == 1:
607 resdesc = next(iter(resdict.items()))[1]
610 reskeys = dict((_Atom(k), k) for k in resdict)
611 except portage.exception.InvalidAtom as e:
613 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
614 level=logging.ERROR, noiselevel=-1)
616 resdesc = next(iter(resdict.items()))[1]
618 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
619 resdesc = resdict[reskeys[resatoms[-1]]]
621 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
625 if sys.hexversion < 0x3000000:
626 _filename_base = unicode
630 class _special_filename(_filename_base):
632 Helps to sort file names by file type and other criteria.
634 def __new__(cls, status_change, file_name):
635 return _filename_base.__new__(cls, status_change + file_name)
637 def __init__(self, status_change, file_name):
638 _filename_base.__init__(status_change + file_name)
639 self.status_change = status_change
640 self.file_name = file_name
641 self.file_type = guessManifestFileType(file_name)
643 def file_type_lt(self, a, b):
645 Defines an ordering between file types.
652 if first == "EBUILD":
654 elif first == "MISC":
655 return second in ("EBUILD",)
657 return second in ("EBUILD", "MISC")
658 elif first == "DIST":
659 return second in ("EBUILD", "MISC", "AUX")
663 raise ValueError("Unknown file type '%s'" % first)
665 def __lt__(self, other):
667 Compare different file names, first by file type and then
668 for ebuilds by version and lexicographically for others.
669 EBUILD < MISC < AUX < DIST < None
671 if self.__class__ != other.__class__:
672 raise NotImplementedError
674 # Sort by file type as defined by file_type_lt().
675 if self.file_type_lt(self, other):
677 elif self.file_type_lt(other, self):
680 # Files have the same type.
681 if self.file_type == "EBUILD":
682 # Sort by version. Lowest first.
683 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
684 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
685 return vercmp(ver, other_ver) < 0
687 # Sort lexicographically.
688 return self.file_name < other.file_name
690 class GenChangeLogs(object):
691 def __init__(self, portdb):
692 self.returncode = os.EX_OK
693 self._portdb = portdb
694 self._wrapper = textwrap.TextWrapper(
696 initial_indent = ' ',
697 subsequent_indent = ' '
702 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
703 return _unicode_decode(p.communicate()[0],
704 encoding=_encodings['stdio'], errors='strict')
706 def generate_changelog(self, cp):
708 output = io.open('ChangeLog',
709 mode='w', encoding=_encodings['repo.content'],
710 errors='backslashreplace')
713 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
714 level=logging.ERROR, noiselevel=-1)
718 output.write(textwrap.dedent('''\
720 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
723 ''' % (cp, time.strftime('%Y'))))
725 # now grab all the commits
726 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
729 # Explaining the arguments:
730 # --name-status to get a list of added/removed files
731 # --no-renames to avoid getting more complex records on the list
732 # --format to get the timestamp, author and commit description
733 # --root to make it work fine even with the initial commit
734 # --relative to get paths relative to ebuilddir
735 # -r (recursive) to get per-file changes
736 # then the commit-id and path.
738 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
739 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
740 c, '--', '.']).rstrip('\n').split('\n')
743 # timestamp Author Name <author@email>
753 for n, l in enumerate(reversed(cinfo)):
759 if f[1] == 'Manifest':
760 pass # XXX: remanifest commits?
761 elif f[1] == 'ChangeLog':
763 elif f[0].startswith('A'):
764 changed.append(_special_filename("+", f[1]))
765 elif f[0].startswith('D'):
766 changed.append(_special_filename("-", f[1]))
767 elif f[0].startswith('M'):
768 changed.append(_special_filename("", f[1]))
771 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
772 level=logging.ERROR, noiselevel=-1)
778 (ts, author) = cinfo[0].split(' ', 1)
779 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
781 changed = [str(x) for x in sorted(changed)]
784 # Reverse the sort order for headers.
785 for c in reversed(changed):
786 if c.startswith('+') and c.endswith('.ebuild'):
787 output.write('*%s (%s)\n' % (c[1:-7], date))
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(self._wrapper.fill(
811 '%s; %s %s:' % (date, author, ', '.join(changed))))
812 # but feel free to break commit messages there
813 self._wrapper.break_on_hyphens = True
815 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body))
820 repo_path = self._portdb.porttrees[0]
823 if 'git' not in FindVCS():
825 "ERROR: --update-changelogs supported only in git repos\n",
826 level=logging.ERROR, noiselevel=-1)
827 self.returncode = 127
830 for cp in self._portdb.cp_all():
831 os.chdir(os.path.join(repo_path, cp))
832 # Determine whether ChangeLog is up-to-date by comparing
833 # the newest commit timestamp with the ChangeLog timestamp.
834 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
836 # This cp has not been added to the repo.
840 cmod = os.stat('ChangeLog').st_mtime
844 if float(cmod) < float(lmod):
845 self.generate_changelog(cp)
847 def egencache_main(args):
849 # The calling environment is ignored, so the program is
850 # completely controlled by commandline arguments.
853 if not sys.stdout.isatty():
854 portage.output.nocolor()
855 env['NOCOLOR'] = 'true'
857 parser, options, atoms = parse_args(args)
859 config_root = options.config_root
861 if options.repositories_configuration is not None:
862 env['PORTAGE_REPOSITORIES'] = options.repositories_configuration
863 elif options.portdir_overlay is not None:
864 env['PORTDIR_OVERLAY'] = options.portdir_overlay
866 if options.cache_dir is not None:
867 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
869 if options.portdir is not None:
870 env['PORTDIR'] = options.portdir
872 settings = portage.config(config_root=config_root,
873 local_config=False, env=env)
876 if not options.ignore_default_opts:
877 default_opts = portage.util.shlex_split(
878 settings.get('EGENCACHE_DEFAULT_OPTS', ''))
881 parser, options, args = parse_args(default_opts + args)
883 if options.cache_dir is not None:
884 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
886 settings = portage.config(config_root=config_root,
887 local_config=False, env=env)
889 if not (options.update or options.update_use_local_desc or
890 options.update_changelogs or options.update_manifests):
891 parser.error('No action specified')
894 if options.repo is None:
895 if len(settings.repositories.prepos) == 2:
896 for repo in settings.repositories:
897 if repo.name != "DEFAULT":
898 options.repo = repo.name
901 if options.repo is None:
902 parser.error("--repo option is required")
904 repo_path = settings.repositories.treemap.get(options.repo)
905 if repo_path is None:
906 parser.error("Unable to locate repository named '%s'" % (options.repo,))
909 repo_config = settings.repositories.get_repo_for_location(repo_path)
911 if options.strict_manifests is not None:
912 if options.strict_manifests == "y":
913 settings.features.add("strict")
915 settings.features.discard("strict")
917 if options.update and 'metadata-transfer' not in settings.features:
918 # Forcibly enable metadata-transfer if portdbapi has a pregenerated
919 # cache that does not support eclass validation.
920 cache = repo_config.get_pregenerated_cache(
921 portage.dbapi.dbapi._known_keys, readonly=True)
922 if cache is not None and not cache.complete_eclass_entries:
923 settings.features.add('metadata-transfer')
928 portdb = portage.portdbapi(mysettings=settings)
930 # Limit ebuilds to the specified repo.
931 portdb.porttrees = [repo_path]
934 if options.cache_dir is not None:
935 # already validated earlier
938 # We check write access after the portdbapi constructor
939 # has had an opportunity to create it. This ensures that
940 # we don't use the cache in the "volatile" mode which is
941 # undesirable for egencache.
942 if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
943 writemsg_level("ecachegen: error: " + \
944 "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
945 level=logging.ERROR, noiselevel=-1)
948 if options.sign_manifests is not None:
949 repo_config.sign_manifest = options.sign_manifests == 'y'
951 if options.thin_manifests is not None:
952 repo_config.thin_manifest = options.thin_manifests == 'y'
956 force_sign_key = None
958 if options.update_manifests:
959 if repo_config.sign_manifest:
963 gpg_cmd = settings.get("PORTAGE_GPG_SIGNING_COMMAND")
965 writemsg_level("egencache: error: "
966 "PORTAGE_GPG_SIGNING_COMMAND is unset! "
967 "Is make.globals missing?\n",
968 level=logging.ERROR, noiselevel=-1)
970 elif "${PORTAGE_GPG_KEY}" in gpg_cmd and \
971 options.gpg_key is None and \
972 "PORTAGE_GPG_KEY" not in settings:
973 writemsg_level("egencache: error: "
974 "PORTAGE_GPG_KEY is unset!\n",
975 level=logging.ERROR, noiselevel=-1)
977 elif "${PORTAGE_GPG_DIR}" in gpg_cmd:
978 if options.gpg_dir is not None:
979 gpg_dir = options.gpg_dir
980 elif "PORTAGE_GPG_DIR" not in settings:
981 gpg_dir = os.path.expanduser("~/.gnupg")
983 gpg_dir = os.path.expanduser(settings["PORTAGE_GPG_DIR"])
984 if not os.access(gpg_dir, os.X_OK):
985 writemsg_level(("egencache: error: "
986 "Unable to access directory: "
987 "PORTAGE_GPG_DIR='%s'\n") % gpg_dir,
988 level=logging.ERROR, noiselevel=-1)
992 writemsg_level("egencache: You may disable manifest "
993 "signatures with --sign-manifests=n or by setting "
994 "\"sign-manifests = false\" in metadata/layout.conf\n",
995 level=logging.ERROR, noiselevel=-1)
999 if gpg_dir is not None:
1000 gpg_vars["PORTAGE_GPG_DIR"] = gpg_dir
1002 if options.gpg_key is None:
1003 gpg_var_names.append("PORTAGE_GPG_KEY")
1005 gpg_vars["PORTAGE_GPG_KEY"] = options.gpg_key
1007 for k in gpg_var_names:
1012 force_sign_key = gpg_vars.get("PORTAGE_GPG_KEY")
1019 cp_iter = iter(atoms)
1021 gen_cache = GenCache(portdb, cp_iter=cp_iter,
1022 max_jobs=options.jobs,
1023 max_load=options.load_average,
1024 rsync=options.rsync)
1026 if options.tolerant:
1027 ret.append(os.EX_OK)
1029 ret.append(gen_cache.returncode)
1031 if options.update_manifests:
1035 cp_iter = iter(atoms)
1037 event_loop = global_event_loop()
1038 scheduler = ManifestScheduler(portdb, cp_iter=cp_iter,
1039 gpg_cmd=gpg_cmd, gpg_vars=gpg_vars,
1040 force_sign_key=force_sign_key,
1041 max_jobs=options.jobs,
1042 max_load=options.load_average,
1043 event_loop=event_loop)
1045 signum = run_main_scheduler(scheduler)
1046 if signum is not None:
1047 sys.exit(128 + signum)
1049 if options.tolerant:
1050 ret.append(os.EX_OK)
1052 ret.append(scheduler.returncode)
1054 if options.update_use_local_desc:
1055 gen_desc = GenUseLocalDesc(portdb,
1056 output=options.uld_output,
1057 preserve_comments=options.preserve_comments)
1059 ret.append(gen_desc.returncode)
1061 if options.update_changelogs:
1062 gen_clogs = GenChangeLogs(portdb)
1064 ret.append(gen_clogs.returncode)
1068 if __name__ == "__main__":
1069 portage._disable_legacy_globals()
1070 portage.util.noiselimit = -1
1071 sys.exit(egencache_main(sys.argv[1:]))