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.const import TIMESTAMP_FORMAT
52 from portage.manifest import guessManifestFileType
53 from portage.package.ebuild._parallel_manifest.ManifestScheduler import ManifestScheduler
54 from portage.util import cmp_sort_key, writemsg_level
55 from portage.util._argparse import ArgumentParser
56 from portage.util._async.run_main_scheduler import run_main_scheduler
57 from portage.util._eventloop.global_event_loop import global_event_loop
58 from portage import cpv_getkey
59 from portage.dep import Atom, isjustname
60 from portage.versions import pkgsplit, vercmp
63 from xml.etree import ElementTree
68 from xml.parsers.expat import ExpatError
72 from repoman.utilities import parse_metadata_use
74 from repoman.utilities import FindVCS
76 if sys.hexversion >= 0x3000000:
77 # pylint: disable=W0622
81 usage = "egencache [options] <action> ... [atom] ..."
82 parser = ArgumentParser(usage=usage)
84 actions = parser.add_argument_group('Actions')
85 actions.add_argument("--update",
87 help="update metadata/md5-cache/ (generate as necessary)")
88 actions.add_argument("--update-use-local-desc",
90 help="update the use.local.desc file from metadata.xml")
91 actions.add_argument("--update-changelogs",
93 help="update the ChangeLog files from SCM logs")
94 actions.add_argument("--update-manifests",
96 help="update manifests")
98 common = parser.add_argument_group('Common options')
99 common.add_argument("--repo",
101 help="name of repo to operate on")
102 common.add_argument("--config-root",
103 help="location of portage config files",
104 dest="portage_configroot")
105 common.add_argument("--gpg-dir",
106 help="override the PORTAGE_GPG_DIR variable",
108 common.add_argument("--gpg-key",
109 help="override the PORTAGE_GPG_KEY variable",
111 common.add_argument("--portdir",
112 help="override the PORTDIR variable (deprecated in favor of --repositories-configuration)",
114 common.add_argument("--portdir-overlay",
115 help="override the PORTDIR_OVERLAY variable (deprecated in favor of --repositories-configuration)",
116 dest="portdir_overlay")
117 common.add_argument("--repositories-configuration",
118 help="override configuration of repositories (in format of repos.conf)",
119 dest="repositories_configuration")
120 common.add_argument("--sign-manifests",
123 help="manually override layout.conf sign-manifests setting")
124 common.add_argument("--strict-manifests",
127 help="manually override \"strict\" FEATURES setting")
128 common.add_argument("--thin-manifests",
131 help="manually override layout.conf thin-manifests setting")
132 common.add_argument("--tolerant",
134 help="exit successfully if only minor errors occurred")
135 common.add_argument("--ignore-default-opts",
137 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
138 common.add_argument("--write-timestamp",
140 help="write metadata/timestamp.chk as required for rsync repositories")
142 update = parser.add_argument_group('--update options')
143 update.add_argument("--cache-dir",
144 help="location of the metadata cache",
146 update.add_argument("-j", "--jobs",
149 help="max ebuild processes to spawn")
150 update.add_argument("--load-average",
153 help="max load allowed when spawning multiple jobs",
155 update.add_argument("--rsync",
157 help="enable rsync stat collision workaround " + \
158 "for bug 139134 (use with --update)")
160 uld = parser.add_argument_group('--update-use-local-desc options')
161 uld.add_argument("--preserve-comments",
163 help="preserve the comments from the existing use.local.desc file")
164 uld.add_argument("--use-local-desc-output",
165 help="output file for use.local.desc data (or '-' for stdout)",
168 options, args = parser.parse_known_args(args)
173 jobs = int(options.jobs)
178 parser.error("Invalid: --jobs='%s'" % \
186 if options.load_average:
188 load_average = float(options.load_average)
192 if load_average <= 0.0:
193 parser.error("Invalid: --load-average='%s'" % \
194 (options.load_average,))
196 options.load_average = load_average
199 options.load_average = None
201 options.config_root = options.portage_configroot
202 if options.config_root is not None and \
203 not os.path.isdir(options.config_root):
204 parser.error("Not a directory: --config-root='%s'" % \
205 (options.config_root,))
207 if options.cache_dir is not None:
208 if not os.path.isdir(options.cache_dir):
209 parser.error("Not a directory: --cache-dir='%s'" % \
210 (options.cache_dir,))
211 if not os.access(options.cache_dir, os.W_OK):
212 parser.error("Write access denied: --cache-dir='%s'" % \
213 (options.cache_dir,))
215 if options.portdir is not None:
216 writemsg_level("egencache: warning: --portdir option is deprecated in favor of --repositories-configuration option\n",
217 level=logging.WARNING, noiselevel=-1)
218 if options.portdir_overlay is not None:
219 writemsg_level("egencache: warning: --portdir-overlay option is deprecated in favor of --repositories-configuration option\n",
220 level=logging.WARNING, noiselevel=-1)
224 atom = portage.dep.Atom(atom)
225 except portage.exception.InvalidAtom:
226 parser.error('Invalid atom: %s' % (atom,))
228 if not isjustname(atom):
229 parser.error('Atom is too specific: %s' % (atom,))
231 if options.update_use_local_desc:
236 parser.error('--update-use-local-desc requires python with USE=xml!')
238 if options.uld_output == '-' and options.preserve_comments:
239 parser.error('--preserve-comments can not be used when outputting to stdout')
241 return parser, options, args
243 class GenCache(object):
244 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
246 # The caller must set portdb.porttrees in order to constrain
247 # findname, cp_list, and cpv_list to the desired tree.
248 tree = portdb.porttrees[0]
249 self._portdb = portdb
250 self._eclass_db = portdb.repositories.get_repo_for_location(tree).eclass_db
251 self._auxdbkeys = portdb._known_keys
252 # We can globally cleanse stale cache only if we
253 # iterate over every single cp.
254 self._global_cleanse = cp_iter is None
255 if cp_iter is not None:
256 self._cp_set = set(cp_iter)
257 cp_iter = iter(self._cp_set)
258 self._cp_missing = self._cp_set.copy()
261 self._cp_missing = set()
262 write_auxdb = "metadata-transfer" in portdb.settings.features
263 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
264 consumer=self._metadata_callback,
265 max_jobs=max_jobs, max_load=max_load,
266 write_auxdb=write_auxdb, main=True)
267 self.returncode = os.EX_OK
268 conf = portdb.repositories.get_repo_for_location(tree)
269 self._trg_caches = tuple(conf.iter_pregenerated_caches(
270 self._auxdbkeys, force=True, readonly=False))
271 if not self._trg_caches:
272 raise Exception("cache formats '%s' aren't supported" %
273 (" ".join(conf.cache_formats),))
276 for trg_cache in self._trg_caches:
277 if hasattr(trg_cache, 'raise_stat_collision'):
278 trg_cache.raise_stat_collision = True
279 # Make _metadata_callback write this cache first, in case
280 # it raises a StatCollision and triggers mtime
282 self._trg_caches = tuple([trg_cache] +
283 [x for x in self._trg_caches if x is not trg_cache])
285 self._existing_nodes = set()
287 def _metadata_callback(self, cpv, repo_path, metadata,
288 ebuild_hash, eapi_supported):
289 self._existing_nodes.add(cpv)
290 self._cp_missing.discard(cpv_getkey(cpv))
292 # Since we're supposed to be able to efficiently obtain the
293 # EAPI from _parse_eapi_ebuild_head, we don't write cache
294 # entries for unsupported EAPIs.
295 if metadata is not None and eapi_supported:
296 if metadata.get('EAPI') == '0':
298 for trg_cache in self._trg_caches:
299 self._write_cache(trg_cache,
300 cpv, repo_path, metadata, ebuild_hash)
302 def _write_cache(self, trg_cache, cpv, repo_path, metadata, ebuild_hash):
304 if not hasattr(trg_cache, 'raise_stat_collision'):
305 # This cache does not avoid redundant writes automatically,
306 # so check for an identical existing entry before writing.
307 # This prevents unnecessary disk writes and can also prevent
308 # unnecessary rsync transfers.
310 dest = trg_cache[cpv]
311 except (KeyError, CacheError):
314 if trg_cache.validate_entry(dest,
315 ebuild_hash, self._eclass_db):
317 for k in self._auxdbkeys:
318 if dest.get(k, '') != metadata.get(k, ''):
325 chf = trg_cache.validation_chf
326 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
328 trg_cache[cpv] = metadata
329 except StatCollision as sc:
330 # If the content of a cache entry changes and neither the
331 # file mtime nor size changes, it will prevent rsync from
332 # detecting changes. Cache backends may raise this
333 # exception from _setitem() if they detect this type of stat
334 # collision. These exceptions are handled by bumping the
335 # mtime on the ebuild (and the corresponding cache entry).
336 # See bug #139134. It is convenient to include checks for
337 # redundant writes along with the internal StatCollision
338 # detection code, so for caches with the
339 # raise_stat_collision attribute, we do not need to
340 # explicitly check for redundant writes like we do for the
341 # other cache types above.
343 for _ec, ec_hash in metadata['_eclasses_'].items():
344 if max_mtime < ec_hash.mtime:
345 max_mtime = ec_hash.mtime
346 if max_mtime == sc.mtime:
348 max_mtime = long(max_mtime)
350 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
354 "%s writing target: %s\n" % (cpv, e),
355 level=logging.ERROR, noiselevel=-1)
357 ebuild_hash.mtime = max_mtime
358 metadata['_mtime_'] = max_mtime
359 trg_cache[cpv] = metadata
360 self._portdb.auxdb[repo_path][cpv] = metadata
362 except CacheError as ce:
365 "%s writing target: %s\n" % (cpv, ce),
366 level=logging.ERROR, noiselevel=-1)
369 signum = run_main_scheduler(self._regen)
370 if signum is not None:
371 sys.exit(128 + signum)
373 self.returncode |= self._regen.returncode
375 for trg_cache in self._trg_caches:
376 self._cleanse_cache(trg_cache)
378 def _cleanse_cache(self, trg_cache):
379 cp_missing = self._cp_missing
381 if self._global_cleanse:
383 for cpv in trg_cache:
388 "Unable to parse cp for '%s'\n" % (cpv,),
389 level=logging.ERROR, noiselevel=-1)
392 except CacheError as ce:
395 "Error listing cache entries for " + \
396 "'%s': %s, continuing...\n" % \
397 (trg_cache.location, ce),
398 level=logging.ERROR, noiselevel=-1)
401 cp_set = self._cp_set
403 for cpv in trg_cache:
408 "Unable to parse cp for '%s'\n" % (cpv,),
409 level=logging.ERROR, noiselevel=-1)
411 cp_missing.discard(cp)
414 except CacheError as ce:
417 "Error listing cache entries for " + \
418 "'%s': %s, continuing...\n" % \
419 (trg_cache.location, ce),
420 level=logging.ERROR, noiselevel=-1)
424 for cp in sorted(cp_missing):
426 "No ebuilds or cache entries found for '%s'\n" % (cp,),
427 level=logging.ERROR, noiselevel=-1)
430 dead_nodes.difference_update(self._existing_nodes)
436 except CacheError as ce:
439 "%s deleting stale cache: %s\n" % (k, ce),
440 level=logging.ERROR, noiselevel=-1)
442 if not trg_cache.autocommits:
445 except CacheError as ce:
448 "committing target: %s\n" % (ce,),
449 level=logging.ERROR, noiselevel=-1)
451 if hasattr(trg_cache, '_prune_empty_dirs'):
452 trg_cache._prune_empty_dirs()
454 class GenUseLocalDesc(object):
455 def __init__(self, portdb, output=None,
456 preserve_comments=False):
457 self.returncode = os.EX_OK
458 self._portdb = portdb
459 self._output = output
460 self._preserve_comments = preserve_comments
463 repo_path = self._portdb.porttrees[0]
464 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
466 if self._output is None or self._output != '-':
467 if self._output is None:
468 prof_path = os.path.join(repo_path, 'profiles')
469 desc_path = os.path.join(prof_path, 'use.local.desc')
475 desc_path = self._output
478 if self._preserve_comments:
479 # Probe in binary mode, in order to avoid
480 # potential character encoding issues.
481 output = open(_unicode_encode(desc_path,
482 encoding=_encodings['fs'], errors='strict'), 'r+b')
484 output = io.open(_unicode_encode(desc_path,
485 encoding=_encodings['fs'], errors='strict'),
486 mode='w', encoding=_encodings['repo.content'],
487 errors='backslashreplace')
489 if not self._preserve_comments or \
490 os.path.isfile(desc_path):
492 "ERROR: failed to open output file %s: %s\n" \
493 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
497 # Open in r+b mode failed because the file doesn't
498 # exist yet. We can probably recover if we disable
499 # preserve_comments mode now.
501 "WARNING: --preserve-comments enabled, but " + \
502 "output file not found: %s\n" % (desc_path,),
503 level=logging.WARNING, noiselevel=-1)
504 self._preserve_comments = False
506 output = io.open(_unicode_encode(desc_path,
507 encoding=_encodings['fs'], errors='strict'),
508 mode='w', encoding=_encodings['repo.content'],
509 errors='backslashreplace')
512 "ERROR: failed to open output file %s: %s\n" \
513 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
519 if self._preserve_comments:
522 if not output.readline().startswith(b'#'):
528 # Finished probing comments in binary mode, now append
530 output = io.open(_unicode_encode(desc_path,
531 encoding=_encodings['fs'], errors='strict'),
532 mode='a', encoding=_encodings['repo.content'],
533 errors='backslashreplace')
536 output.write(textwrap.dedent('''\
537 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
538 # your descriptions to your package's metadata.xml ONLY.
539 # * generated automatically using egencache *
543 # The cmp function no longer exists in python3, so we'll
544 # implement our own here under a slightly different name
545 # since we don't want any confusion given that we never
546 # want to rely on the builtin cmp function.
548 if a is None or b is None:
549 # None can't be compared with other types in python3.
550 if a is None and b is None:
556 return (a > b) - (a < b)
558 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
560 Implements doctype() as required to avoid deprecation warnings
563 def doctype(self, name, pubid, system):
566 for cp in self._portdb.cp_all():
567 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
569 metadata = ElementTree.parse(_unicode_encode(metadata_path,
570 encoding=_encodings['fs'], errors='strict'),
571 parser=ElementTree.XMLParser(
572 target=_MetadataTreeBuilder()))
575 except (ExpatError, EnvironmentError) as e:
577 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
578 level=logging.ERROR, noiselevel=-1)
582 usedict = parse_metadata_use(metadata)
583 except portage.exception.ParseError as e:
585 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
586 level=logging.ERROR, noiselevel=-1)
589 for flag in sorted(usedict):
590 def atomcmp(atoma, atomb):
591 # None is better than an atom, that's why we reverse the args
592 if atoma is None or atomb is None:
593 return cmp_func(atomb, atoma)
594 # Same for plain PNs (.operator is None then)
595 elif atoma.operator is None or atomb.operator is None:
596 return cmp_func(atomb.operator, atoma.operator)
598 elif atoma.cpv != atomb.cpv:
599 return vercmp(atoma.version, atomb.version)
600 # Versions match, let's fallback to operator matching
602 return cmp_func(ops.get(atoma.operator, -1),
603 ops.get(atomb.operator, -1))
610 resdict = usedict[flag]
611 if len(resdict) == 1:
612 resdesc = next(iter(resdict.items()))[1]
615 reskeys = dict((_Atom(k), k) for k in resdict)
616 except portage.exception.InvalidAtom as e:
618 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
619 level=logging.ERROR, noiselevel=-1)
621 resdesc = next(iter(resdict.items()))[1]
623 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
624 resdesc = resdict[reskeys[resatoms[-1]]]
626 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
630 if sys.hexversion < 0x3000000:
631 _filename_base = unicode
635 class _special_filename(_filename_base):
637 Helps to sort file names by file type and other criteria.
639 def __new__(cls, status_change, file_name):
640 return _filename_base.__new__(cls, status_change + file_name)
642 def __init__(self, status_change, file_name):
643 _filename_base.__init__(status_change + file_name)
644 self.status_change = status_change
645 self.file_name = file_name
646 self.file_type = guessManifestFileType(file_name)
649 def file_type_lt(a, b):
651 Defines an ordering between file types.
658 if first == "EBUILD":
660 elif first == "MISC":
661 return second in ("EBUILD",)
663 return second in ("EBUILD", "MISC")
664 elif first == "DIST":
665 return second in ("EBUILD", "MISC", "AUX")
669 raise ValueError("Unknown file type '%s'" % first)
671 def __lt__(self, other):
673 Compare different file names, first by file type and then
674 for ebuilds by version and lexicographically for others.
675 EBUILD < MISC < AUX < DIST < None
677 if self.__class__ != other.__class__:
678 raise NotImplementedError
680 # Sort by file type as defined by file_type_lt().
681 if self.file_type_lt(self, other):
683 elif self.file_type_lt(other, self):
686 # Files have the same type.
687 if self.file_type == "EBUILD":
688 # Sort by version. Lowest first.
689 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
690 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
691 return vercmp(ver, other_ver) < 0
693 # Sort lexicographically.
694 return self.file_name < other.file_name
696 class GenChangeLogs(object):
697 def __init__(self, portdb):
698 self.returncode = os.EX_OK
699 self._portdb = portdb
700 self._wrapper = textwrap.TextWrapper(
702 initial_indent = ' ',
703 subsequent_indent = ' '
708 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
709 return _unicode_decode(p.communicate()[0],
710 encoding=_encodings['stdio'], errors='strict')
712 def generate_changelog(self, cp):
714 output = io.open('ChangeLog',
715 mode='w', encoding=_encodings['repo.content'],
716 errors='backslashreplace')
719 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
720 level=logging.ERROR, noiselevel=-1)
724 output.write(textwrap.dedent('''\
726 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
729 ''' % (cp, time.strftime('%Y'))))
731 # now grab all the commits
732 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
735 # Explaining the arguments:
736 # --name-status to get a list of added/removed files
737 # --no-renames to avoid getting more complex records on the list
738 # --format to get the timestamp, author and commit description
739 # --root to make it work fine even with the initial commit
740 # --relative to get paths relative to ebuilddir
741 # -r (recursive) to get per-file changes
742 # then the commit-id and path.
744 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
745 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
746 c, '--', '.']).rstrip('\n').split('\n')
749 # timestamp Author Name <author@email>
759 for n, l in enumerate(reversed(cinfo)):
765 if f[1] == 'Manifest':
766 pass # XXX: remanifest commits?
767 elif f[1] == 'ChangeLog':
769 elif f[0].startswith('A'):
770 changed.append(_special_filename("+", f[1]))
771 elif f[0].startswith('D'):
772 changed.append(_special_filename("-", f[1]))
773 elif f[0].startswith('M'):
774 changed.append(_special_filename("", f[1]))
777 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
778 level=logging.ERROR, noiselevel=-1)
784 (ts, author) = cinfo[0].split(' ', 1)
785 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
787 changed = [str(x) for x in sorted(changed)]
790 # Reverse the sort order for headers.
791 for c in reversed(changed):
792 if c.startswith('+') and c.endswith('.ebuild'):
793 output.write('*%s (%s)\n' % (c[1:-7], date))
798 # strip '<cp>: ', '[<cp>] ', and similar
799 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
800 # strip trailing newline
804 if body[-1].startswith('git-svn-id:') and not body[-2]:
806 # strip the repoman version/manifest note
807 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
809 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
814 # don't break filenames on hyphens
815 self._wrapper.break_on_hyphens = False
816 output.write(self._wrapper.fill(
817 '%s; %s %s:' % (date, author, ', '.join(changed))))
818 # but feel free to break commit messages there
819 self._wrapper.break_on_hyphens = True
821 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body))
826 repo_path = self._portdb.porttrees[0]
829 if 'git' not in FindVCS():
831 "ERROR: --update-changelogs supported only in git repos\n",
832 level=logging.ERROR, noiselevel=-1)
833 self.returncode = 127
836 for cp in self._portdb.cp_all():
837 os.chdir(os.path.join(repo_path, cp))
838 # Determine whether ChangeLog is up-to-date by comparing
839 # the newest commit timestamp with the ChangeLog timestamp.
840 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
842 # This cp has not been added to the repo.
846 cmod = os.stat('ChangeLog').st_mtime
850 if float(cmod) < float(lmod):
851 self.generate_changelog(cp)
853 def egencache_main(args):
855 # The calling environment is ignored, so the program is
856 # completely controlled by commandline arguments.
859 if not sys.stdout.isatty():
860 portage.output.nocolor()
861 env['NOCOLOR'] = 'true'
863 parser, options, atoms = parse_args(args)
865 config_root = options.config_root
867 if options.repositories_configuration is not None:
868 env['PORTAGE_REPOSITORIES'] = options.repositories_configuration
869 elif options.portdir_overlay is not None:
870 env['PORTDIR_OVERLAY'] = options.portdir_overlay
872 if options.cache_dir is not None:
873 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
875 if options.portdir is not None:
876 env['PORTDIR'] = options.portdir
878 settings = portage.config(config_root=config_root,
879 local_config=False, env=env)
882 if not options.ignore_default_opts:
883 default_opts = portage.util.shlex_split(
884 settings.get('EGENCACHE_DEFAULT_OPTS', ''))
887 parser, options, args = parse_args(default_opts + args)
889 if options.cache_dir is not None:
890 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
892 settings = portage.config(config_root=config_root,
893 local_config=False, env=env)
895 if not (options.update or options.update_use_local_desc or
896 options.update_changelogs or options.update_manifests):
897 parser.error('No action specified')
900 if options.repo is None:
901 if len(settings.repositories.prepos) == 2:
902 for repo in settings.repositories:
903 if repo.name != "DEFAULT":
904 options.repo = repo.name
907 if options.repo is None:
908 parser.error("--repo option is required")
910 repo_path = settings.repositories.treemap.get(options.repo)
911 if repo_path is None:
912 parser.error("Unable to locate repository named '%s'" % (options.repo,))
915 repo_config = settings.repositories.get_repo_for_location(repo_path)
917 if options.strict_manifests is not None:
918 if options.strict_manifests == "y":
919 settings.features.add("strict")
921 settings.features.discard("strict")
923 if options.update and 'metadata-transfer' not in settings.features:
924 # Forcibly enable metadata-transfer if portdbapi has a pregenerated
925 # cache that does not support eclass validation.
926 cache = repo_config.get_pregenerated_cache(
927 portage.dbapi.dbapi._known_keys, readonly=True)
928 if cache is not None and not cache.complete_eclass_entries:
929 settings.features.add('metadata-transfer')
934 portdb = portage.portdbapi(mysettings=settings)
936 # Limit ebuilds to the specified repo.
937 portdb.porttrees = [repo_path]
940 if options.cache_dir is not None:
941 # already validated earlier
944 # We check write access after the portdbapi constructor
945 # has had an opportunity to create it. This ensures that
946 # we don't use the cache in the "volatile" mode which is
947 # undesirable for egencache.
948 if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
949 writemsg_level("ecachegen: error: " + \
950 "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
951 level=logging.ERROR, noiselevel=-1)
954 if options.sign_manifests is not None:
955 repo_config.sign_manifest = options.sign_manifests == 'y'
957 if options.thin_manifests is not None:
958 repo_config.thin_manifest = options.thin_manifests == 'y'
962 force_sign_key = None
964 if options.update_manifests:
965 if repo_config.sign_manifest:
969 gpg_cmd = settings.get("PORTAGE_GPG_SIGNING_COMMAND")
971 writemsg_level("egencache: error: "
972 "PORTAGE_GPG_SIGNING_COMMAND is unset! "
973 "Is make.globals missing?\n",
974 level=logging.ERROR, noiselevel=-1)
976 elif "${PORTAGE_GPG_KEY}" in gpg_cmd and \
977 options.gpg_key is None and \
978 "PORTAGE_GPG_KEY" not in settings:
979 writemsg_level("egencache: error: "
980 "PORTAGE_GPG_KEY is unset!\n",
981 level=logging.ERROR, noiselevel=-1)
983 elif "${PORTAGE_GPG_DIR}" in gpg_cmd:
984 if options.gpg_dir is not None:
985 gpg_dir = options.gpg_dir
986 elif "PORTAGE_GPG_DIR" not in settings:
987 gpg_dir = os.path.expanduser("~/.gnupg")
989 gpg_dir = os.path.expanduser(settings["PORTAGE_GPG_DIR"])
990 if not os.access(gpg_dir, os.X_OK):
991 writemsg_level(("egencache: error: "
992 "Unable to access directory: "
993 "PORTAGE_GPG_DIR='%s'\n") % gpg_dir,
994 level=logging.ERROR, noiselevel=-1)
998 writemsg_level("egencache: You may disable manifest "
999 "signatures with --sign-manifests=n or by setting "
1000 "\"sign-manifests = false\" in metadata/layout.conf\n",
1001 level=logging.ERROR, noiselevel=-1)
1005 if gpg_dir is not None:
1006 gpg_vars["PORTAGE_GPG_DIR"] = gpg_dir
1008 if options.gpg_key is None:
1009 gpg_var_names.append("PORTAGE_GPG_KEY")
1011 gpg_vars["PORTAGE_GPG_KEY"] = options.gpg_key
1013 for k in gpg_var_names:
1018 force_sign_key = gpg_vars.get("PORTAGE_GPG_KEY")
1025 cp_iter = iter(atoms)
1027 gen_cache = GenCache(portdb, cp_iter=cp_iter,
1028 max_jobs=options.jobs,
1029 max_load=options.load_average,
1030 rsync=options.rsync)
1032 if options.tolerant:
1033 ret.append(os.EX_OK)
1035 ret.append(gen_cache.returncode)
1037 if options.update_manifests:
1041 cp_iter = iter(atoms)
1043 event_loop = global_event_loop()
1044 scheduler = ManifestScheduler(portdb, cp_iter=cp_iter,
1045 gpg_cmd=gpg_cmd, gpg_vars=gpg_vars,
1046 force_sign_key=force_sign_key,
1047 max_jobs=options.jobs,
1048 max_load=options.load_average,
1049 event_loop=event_loop)
1051 signum = run_main_scheduler(scheduler)
1052 if signum is not None:
1053 sys.exit(128 + signum)
1055 if options.tolerant:
1056 ret.append(os.EX_OK)
1058 ret.append(scheduler.returncode)
1060 if options.update_use_local_desc:
1061 gen_desc = GenUseLocalDesc(portdb,
1062 output=options.uld_output,
1063 preserve_comments=options.preserve_comments)
1065 ret.append(gen_desc.returncode)
1067 if options.update_changelogs:
1068 gen_clogs = GenChangeLogs(portdb)
1070 ret.append(gen_clogs.returncode)
1072 if options.write_timestamp:
1073 timestamp_path = os.path.join(repo_path, 'metadata', 'timestamp.chk')
1075 with open(timestamp_path, 'w') as f:
1076 f.write(time.strftime('%s\n' % TIMESTAMP_FORMAT, time.gmtime()))
1078 ret.append(os.EX_IOERR)
1080 ret.append(os.EX_OK)
1084 if __name__ == "__main__":
1085 portage._disable_legacy_globals()
1086 portage.util.noiselimit = -1
1087 sys.exit(egencache_main(sys.argv[1:]))