2 # Copyright 2009-2012 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 from portage import os, _encodings, _unicode_encode, _unicode_decode
48 from _emerge.MetadataRegen import MetadataRegen
49 from portage.cache.cache_errors import CacheError, StatCollision
50 from portage.manifest import guessManifestFileType
51 from portage.package.ebuild._parallel_manifest.ManifestScheduler import ManifestScheduler
52 from portage.util import cmp_sort_key, writemsg_level
53 from portage.util._eventloop.global_event_loop import global_event_loop
54 from portage import cpv_getkey
55 from portage.dep import Atom, isjustname
56 from portage.versions import pkgsplit, vercmp
59 from xml.etree import ElementTree
64 from xml.parsers.expat import ExpatError
68 from repoman.utilities import parse_metadata_use
70 from repoman.utilities import FindVCS
72 if sys.hexversion >= 0x3000000:
76 usage = "egencache [options] <action> ... [atom] ..."
77 parser = optparse.OptionParser(usage=usage)
79 actions = optparse.OptionGroup(parser, 'Actions')
80 actions.add_option("--update",
82 help="update metadata/cache/ (generate as necessary)")
83 actions.add_option("--update-use-local-desc",
85 help="update the use.local.desc file from metadata.xml")
86 actions.add_option("--update-changelogs",
88 help="update the ChangeLog files from SCM logs")
89 actions.add_option("--update-manifests",
91 help="update manifests")
92 parser.add_option_group(actions)
94 common = optparse.OptionGroup(parser, 'Common options')
95 common.add_option("--repo",
97 help="name of repo to operate on (default repo is located at $PORTDIR)")
98 common.add_option("--config-root",
99 help="location of portage config files",
100 dest="portage_configroot")
101 common.add_option("--gpg-dir",
102 help="override the PORTAGE_GPG_DIR variable",
104 common.add_option("--gpg-key",
105 help="override the PORTAGE_GPG_KEY variable",
107 common.add_option("--portdir",
108 help="override the portage tree location",
110 common.add_option("--portdir-overlay",
111 help="override the PORTDIR_OVERLAY variable (requires that --repo is also specified)",
112 dest="portdir_overlay")
113 common.add_option("--sign-manifests",
117 help="manually override layout.conf sign-manifests setting")
118 common.add_option("--strict-manifests",
122 help="manually override \"strict\" FEATURES setting")
123 common.add_option("--thin-manifests",
127 help="manually override layout.conf thin-manifests setting")
128 common.add_option("--tolerant",
130 help="exit successfully if only minor errors occurred")
131 common.add_option("--ignore-default-opts",
133 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
134 parser.add_option_group(common)
136 update = optparse.OptionGroup(parser, '--update options')
137 update.add_option("--cache-dir",
138 help="location of the metadata cache",
140 update.add_option("-j", "--jobs",
142 help="max ebuild processes to spawn")
143 update.add_option("--load-average",
145 help="max load allowed when spawning multiple jobs",
147 update.add_option("--rsync",
149 help="enable rsync stat collision workaround " + \
150 "for bug 139134 (use with --update)")
151 parser.add_option_group(update)
153 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
154 uld.add_option("--preserve-comments",
156 help="preserve the comments from the existing use.local.desc file")
157 uld.add_option("--use-local-desc-output",
158 help="output file for use.local.desc data (or '-' for stdout)",
160 parser.add_option_group(uld)
162 options, args = parser.parse_args(args)
167 jobs = int(options.jobs)
172 parser.error("Invalid: --jobs='%s'" % \
180 if options.load_average:
182 load_average = float(options.load_average)
186 if load_average <= 0.0:
187 parser.error("Invalid: --load-average='%s'" % \
188 (options.load_average,))
190 options.load_average = load_average
193 options.load_average = None
195 options.config_root = options.portage_configroot
196 if options.config_root is not None and \
197 not os.path.isdir(options.config_root):
198 parser.error("Not a directory: --config-root='%s'" % \
199 (options.config_root,))
201 if options.cache_dir is not None:
202 if not os.path.isdir(options.cache_dir):
203 parser.error("Not a directory: --cache-dir='%s'" % \
204 (options.cache_dir,))
205 if not os.access(options.cache_dir, os.W_OK):
206 parser.error("Write access denied: --cache-dir='%s'" % \
207 (options.cache_dir,))
209 if options.portdir_overlay is not None and \
210 options.repo is None:
211 parser.error("--portdir-overlay option requires --repo option")
215 atom = portage.dep.Atom(atom)
216 except portage.exception.InvalidAtom:
217 parser.error('Invalid atom: %s' % (atom,))
219 if not isjustname(atom):
220 parser.error('Atom is too specific: %s' % (atom,))
222 if options.update_use_local_desc:
227 parser.error('--update-use-local-desc requires python with USE=xml!')
229 if options.uld_output == '-' and options.preserve_comments:
230 parser.error('--preserve-comments can not be used when outputting to stdout')
232 return parser, options, args
234 class GenCache(object):
235 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
237 # The caller must set portdb.porttrees in order to constrain
238 # findname, cp_list, and cpv_list to the desired tree.
239 tree = portdb.porttrees[0]
240 self._portdb = portdb
241 self._eclass_db = portdb.repositories.get_repo_for_location(tree).eclass_db
242 self._auxdbkeys = portdb._known_keys
243 # We can globally cleanse stale cache only if we
244 # iterate over every single cp.
245 self._global_cleanse = cp_iter is None
246 if cp_iter is not None:
247 self._cp_set = set(cp_iter)
248 cp_iter = iter(self._cp_set)
249 self._cp_missing = self._cp_set.copy()
252 self._cp_missing = set()
253 write_auxdb = "metadata-transfer" in portdb.settings.features
254 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
255 consumer=self._metadata_callback,
256 max_jobs=max_jobs, max_load=max_load,
257 write_auxdb=write_auxdb, main=True)
258 self.returncode = os.EX_OK
259 conf = portdb.repositories.get_repo_for_location(tree)
260 self._trg_caches = tuple(conf.iter_pregenerated_caches(
261 self._auxdbkeys, force=True, readonly=False))
262 if not self._trg_caches:
263 raise Exception("cache formats '%s' aren't supported" %
264 (" ".join(conf.cache_formats),))
267 for trg_cache in self._trg_caches:
268 if hasattr(trg_cache, 'raise_stat_collision'):
269 trg_cache.raise_stat_collision = True
270 # Make _metadata_callback write this cache first, in case
271 # it raises a StatCollision and triggers mtime
273 self._trg_caches = tuple([trg_cache] +
274 [x for x in self._trg_caches if x is not trg_cache])
276 self._existing_nodes = set()
278 def _metadata_callback(self, cpv, repo_path, metadata,
279 ebuild_hash, eapi_supported):
280 self._existing_nodes.add(cpv)
281 self._cp_missing.discard(cpv_getkey(cpv))
283 # Since we're supposed to be able to efficiently obtain the
284 # EAPI from _parse_eapi_ebuild_head, we don't write cache
285 # entries for unsupported EAPIs.
286 if metadata is not None and eapi_supported:
287 if metadata.get('EAPI') == '0':
289 for trg_cache in self._trg_caches:
290 self._write_cache(trg_cache,
291 cpv, repo_path, metadata, ebuild_hash)
293 def _write_cache(self, trg_cache, cpv, repo_path, metadata, ebuild_hash):
295 if not hasattr(trg_cache, 'raise_stat_collision'):
296 # This cache does not avoid redundant writes automatically,
297 # so check for an identical existing entry before writing.
298 # This prevents unnecessary disk writes and can also prevent
299 # unnecessary rsync transfers.
301 dest = trg_cache[cpv]
302 except (KeyError, CacheError):
305 if trg_cache.validate_entry(dest,
306 ebuild_hash, self._eclass_db):
308 for k in self._auxdbkeys:
309 if dest.get(k, '') != metadata.get(k, ''):
316 chf = trg_cache.validation_chf
317 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
319 trg_cache[cpv] = metadata
320 except StatCollision as sc:
321 # If the content of a cache entry changes and neither the
322 # file mtime nor size changes, it will prevent rsync from
323 # detecting changes. Cache backends may raise this
324 # exception from _setitem() if they detect this type of stat
325 # collision. These exceptions are handled by bumping the
326 # mtime on the ebuild (and the corresponding cache entry).
327 # See bug #139134. It is convenient to include checks for
328 # redundant writes along with the internal StatCollision
329 # detection code, so for caches with the
330 # raise_stat_collision attribute, we do not need to
331 # explicitly check for redundant writes like we do for the
332 # other cache types above.
334 for ec, ec_hash in metadata['_eclasses_'].items():
335 if max_mtime < ec_hash.mtime:
336 max_mtime = ec_hash.mtime
337 if max_mtime == sc.mtime:
339 max_mtime = long(max_mtime)
341 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
345 "%s writing target: %s\n" % (cpv, e),
346 level=logging.ERROR, noiselevel=-1)
348 ebuild_hash.mtime = max_mtime
349 metadata['_mtime_'] = max_mtime
350 trg_cache[cpv] = metadata
351 self._portdb.auxdb[repo_path][cpv] = metadata
353 except CacheError as ce:
356 "%s writing target: %s\n" % (cpv, ce),
357 level=logging.ERROR, noiselevel=-1)
363 def sighandler(signum, frame):
364 signal.signal(signal.SIGINT, signal.SIG_IGN)
365 signal.signal(signal.SIGTERM, signal.SIG_IGN)
366 self._regen.terminate()
367 received_signal.append(128 + signum)
369 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
370 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
376 # Restore previous handlers
377 if earlier_sigint_handler is not None:
378 signal.signal(signal.SIGINT, earlier_sigint_handler)
380 signal.signal(signal.SIGINT, signal.SIG_DFL)
381 if earlier_sigterm_handler is not None:
382 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
384 signal.signal(signal.SIGTERM, signal.SIG_DFL)
387 sys.exit(received_signal[0])
389 self.returncode |= self._regen.returncode
391 for trg_cache in self._trg_caches:
392 self._cleanse_cache(trg_cache)
394 def _cleanse_cache(self, trg_cache):
395 cp_missing = self._cp_missing
397 if self._global_cleanse:
399 for cpv in trg_cache:
404 "Unable to parse cp for '%s'\n" % (cpv,),
405 level=logging.ERROR, noiselevel=-1)
408 except CacheError as ce:
411 "Error listing cache entries for " + \
412 "'%s/metadata/cache': %s, continuing...\n" % \
413 (self._portdb.porttree_root, ce),
414 level=logging.ERROR, noiselevel=-1)
417 cp_set = self._cp_set
419 for cpv in trg_cache:
424 "Unable to parse cp for '%s'\n" % (cpv,),
425 level=logging.ERROR, noiselevel=-1)
427 cp_missing.discard(cp)
430 except CacheError as ce:
433 "Error listing cache entries for " + \
434 "'%s/metadata/cache': %s, continuing...\n" % \
435 (self._portdb.porttree_root, ce),
436 level=logging.ERROR, noiselevel=-1)
440 for cp in sorted(cp_missing):
442 "No ebuilds or cache entries found for '%s'\n" % (cp,),
443 level=logging.ERROR, noiselevel=-1)
446 dead_nodes.difference_update(self._existing_nodes)
452 except CacheError as ce:
455 "%s deleting stale cache: %s\n" % (k, ce),
456 level=logging.ERROR, noiselevel=-1)
458 if not trg_cache.autocommits:
461 except CacheError as ce:
464 "committing target: %s\n" % (ce,),
465 level=logging.ERROR, noiselevel=-1)
467 if hasattr(trg_cache, '_prune_empty_dirs'):
468 trg_cache._prune_empty_dirs()
470 class GenUseLocalDesc(object):
471 def __init__(self, portdb, output=None,
472 preserve_comments=False):
473 self.returncode = os.EX_OK
474 self._portdb = portdb
475 self._output = output
476 self._preserve_comments = preserve_comments
479 repo_path = self._portdb.porttrees[0]
480 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
482 if self._output is None or self._output != '-':
483 if self._output is None:
484 prof_path = os.path.join(repo_path, 'profiles')
485 desc_path = os.path.join(prof_path, 'use.local.desc')
491 desc_path = self._output
494 if self._preserve_comments:
495 # Probe in binary mode, in order to avoid
496 # potential character encoding issues.
497 output = open(_unicode_encode(desc_path,
498 encoding=_encodings['fs'], errors='strict'), 'r+b')
500 output = io.open(_unicode_encode(desc_path,
501 encoding=_encodings['fs'], errors='strict'),
502 mode='w', encoding=_encodings['repo.content'],
503 errors='backslashreplace')
505 if not self._preserve_comments or \
506 os.path.isfile(desc_path):
508 "ERROR: failed to open output file %s: %s\n" \
509 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
513 # Open in r+b mode failed because the file doesn't
514 # exist yet. We can probably recover if we disable
515 # preserve_comments mode now.
517 "WARNING: --preserve-comments enabled, but " + \
518 "output file not found: %s\n" % (desc_path,),
519 level=logging.WARNING, noiselevel=-1)
520 self._preserve_comments = False
522 output = io.open(_unicode_encode(desc_path,
523 encoding=_encodings['fs'], errors='strict'),
524 mode='w', encoding=_encodings['repo.content'],
525 errors='backslashreplace')
528 "ERROR: failed to open output file %s: %s\n" \
529 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
535 if self._preserve_comments:
538 if not output.readline().startswith(b'#'):
544 # Finished probing comments in binary mode, now append
546 output = io.open(_unicode_encode(desc_path,
547 encoding=_encodings['fs'], errors='strict'),
548 mode='a', encoding=_encodings['repo.content'],
549 errors='backslashreplace')
550 output.write(_unicode_decode('\n'))
552 output.write(textwrap.dedent(_unicode_decode('''\
553 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
554 # your descriptions to your package's metadata.xml ONLY.
555 # * generated automatically using egencache *
559 # The cmp function no longer exists in python3, so we'll
560 # implement our own here under a slightly different name
561 # since we don't want any confusion given that we never
562 # want to rely on the builtin cmp function.
564 if a is None or b is None:
565 # None can't be compared with other types in python3.
566 if a is None and b is None:
572 return (a > b) - (a < b)
574 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
576 Implements doctype() as required to avoid deprecation warnings
579 def doctype(self, name, pubid, system):
582 for cp in self._portdb.cp_all():
583 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
585 metadata = ElementTree.parse(_unicode_encode(metadata_path,
586 encoding=_encodings['fs'], errors='strict'),
587 parser=ElementTree.XMLParser(
588 target=_MetadataTreeBuilder()))
591 except (ExpatError, EnvironmentError) as e:
593 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
594 level=logging.ERROR, noiselevel=-1)
598 usedict = parse_metadata_use(metadata)
599 except portage.exception.ParseError as e:
601 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
602 level=logging.ERROR, noiselevel=-1)
605 for flag in sorted(usedict):
606 def atomcmp(atoma, atomb):
607 # None is better than an atom, that's why we reverse the args
608 if atoma is None or atomb is None:
609 return cmp_func(atomb, atoma)
610 # Same for plain PNs (.operator is None then)
611 elif atoma.operator is None or atomb.operator is None:
612 return cmp_func(atomb.operator, atoma.operator)
614 elif atoma.cpv != atomb.cpv:
615 return vercmp(atoma.version, atomb.version)
616 # Versions match, let's fallback to operator matching
618 return cmp_func(ops.get(atoma.operator, -1),
619 ops.get(atomb.operator, -1))
626 resdict = usedict[flag]
627 if len(resdict) == 1:
628 resdesc = next(iter(resdict.items()))[1]
631 reskeys = dict((_Atom(k), k) for k in resdict)
632 except portage.exception.InvalidAtom as e:
634 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
635 level=logging.ERROR, noiselevel=-1)
637 resdesc = next(iter(resdict.items()))[1]
639 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
640 resdesc = resdict[reskeys[resatoms[-1]]]
642 output.write(_unicode_decode(
643 '%s:%s - %s\n' % (cp, flag, resdesc)))
647 if sys.hexversion < 0x3000000:
648 _filename_base = unicode
652 class _special_filename(_filename_base):
654 Helps to sort file names by file type and other criteria.
656 def __new__(cls, status_change, file_name):
657 return _filename_base.__new__(cls, status_change + file_name)
659 def __init__(self, status_change, file_name):
660 _filename_base.__init__(status_change + file_name)
661 self.status_change = status_change
662 self.file_name = file_name
663 self.file_type = guessManifestFileType(file_name)
665 def file_type_lt(self, a, b):
667 Defines an ordering between file types.
674 if first == "EBUILD":
676 elif first == "MISC":
677 return second in ("EBUILD",)
679 return second in ("EBUILD", "MISC")
680 elif first == "DIST":
681 return second in ("EBUILD", "MISC", "AUX")
685 raise ValueError("Unknown file type '%s'" % first)
687 def __lt__(self, other):
689 Compare different file names, first by file type and then
690 for ebuilds by version and lexicographically for others.
691 EBUILD < MISC < AUX < DIST < None
693 if self.__class__ != other.__class__:
694 raise NotImplementedError
696 # Sort by file type as defined by file_type_lt().
697 if self.file_type_lt(self, other):
699 elif self.file_type_lt(other, self):
702 # Files have the same type.
703 if self.file_type == "EBUILD":
704 # Sort by version. Lowest first.
705 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
706 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
707 return vercmp(ver, other_ver) < 0
709 # Sort lexicographically.
710 return self.file_name < other.file_name
712 class GenChangeLogs(object):
713 def __init__(self, portdb):
714 self.returncode = os.EX_OK
715 self._portdb = portdb
716 self._wrapper = textwrap.TextWrapper(
718 initial_indent = ' ',
719 subsequent_indent = ' '
724 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
725 return _unicode_decode(p.communicate()[0],
726 encoding=_encodings['stdio'], errors='strict')
728 def generate_changelog(self, cp):
730 output = io.open('ChangeLog',
731 mode='w', encoding=_encodings['repo.content'],
732 errors='backslashreplace')
735 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
736 level=logging.ERROR, noiselevel=-1)
740 output.write(textwrap.dedent(_unicode_decode('''\
742 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
745 ''' % (cp, time.strftime('%Y')))))
747 # now grab all the commits
748 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
751 # Explaining the arguments:
752 # --name-status to get a list of added/removed files
753 # --no-renames to avoid getting more complex records on the list
754 # --format to get the timestamp, author and commit description
755 # --root to make it work fine even with the initial commit
756 # --relative to get paths relative to ebuilddir
757 # -r (recursive) to get per-file changes
758 # then the commit-id and path.
760 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
761 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
762 c, '--', '.']).rstrip('\n').split('\n')
765 # timestamp Author Name <author@email>
775 for n, l in enumerate(reversed(cinfo)):
781 if f[1] == 'Manifest':
782 pass # XXX: remanifest commits?
783 elif f[1] == 'ChangeLog':
785 elif f[0].startswith('A'):
786 changed.append(_special_filename("+", f[1]))
787 elif f[0].startswith('D'):
788 changed.append(_special_filename("-", f[1]))
789 elif f[0].startswith('M'):
790 changed.append(_special_filename("", f[1]))
793 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
794 level=logging.ERROR, noiselevel=-1)
800 (ts, author) = cinfo[0].split(' ', 1)
801 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
803 changed = [str(x) for x in sorted(changed)]
806 # Reverse the sort order for headers.
807 for c in reversed(changed):
808 if c.startswith('+') and c.endswith('.ebuild'):
809 output.write(_unicode_decode(
810 '*%s (%s)\n' % (c[1:-7], date)))
813 output.write(_unicode_decode('\n'))
815 # strip '<cp>: ', '[<cp>] ', and similar
816 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
817 # strip trailing newline
821 if body[-1].startswith('git-svn-id:') and not body[-2]:
823 # strip the repoman version/manifest note
824 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
826 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
831 # don't break filenames on hyphens
832 self._wrapper.break_on_hyphens = False
833 output.write(_unicode_decode(
835 '%s; %s %s:' % (date, author, ', '.join(changed)))))
836 # but feel free to break commit messages there
837 self._wrapper.break_on_hyphens = True
838 output.write(_unicode_decode(
839 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body)))
844 repo_path = self._portdb.porttrees[0]
847 if 'git' not in FindVCS():
849 "ERROR: --update-changelogs supported only in git repos\n",
850 level=logging.ERROR, noiselevel=-1)
851 self.returncode = 127
854 for cp in self._portdb.cp_all():
855 os.chdir(os.path.join(repo_path, cp))
856 # Determine whether ChangeLog is up-to-date by comparing
857 # the newest commit timestamp with the ChangeLog timestamp.
858 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
860 # This cp has not been added to the repo.
864 cmod = os.stat('ChangeLog').st_mtime
868 if float(cmod) < float(lmod):
869 self.generate_changelog(cp)
871 def egencache_main(args):
872 parser, options, atoms = parse_args(args)
874 config_root = options.config_root
876 # The calling environment is ignored, so the program is
877 # completely controlled by commandline arguments.
880 if options.repo is None:
881 env['PORTDIR_OVERLAY'] = ''
882 elif options.portdir_overlay:
883 env['PORTDIR_OVERLAY'] = options.portdir_overlay
885 if options.cache_dir is not None:
886 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
888 if options.portdir is not None:
889 env['PORTDIR'] = options.portdir
891 settings = portage.config(config_root=config_root,
892 local_config=False, env=env)
895 if not options.ignore_default_opts:
896 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
899 parser, options, args = parse_args(default_opts + args)
901 if options.cache_dir is not None:
902 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
904 settings = portage.config(config_root=config_root,
905 local_config=False, env=env)
907 if not (options.update or options.update_use_local_desc or
908 options.update_changelogs or options.update_manifests):
909 parser.error('No action specified')
913 if options.repo is not None:
914 repo_path = settings.repositories.treemap.get(options.repo)
915 if repo_path is None:
916 parser.error("Unable to locate repository named '%s'" % \
920 repo_path = settings.repositories.mainRepoLocation()
922 parser.error("PORTDIR is undefined")
925 repo_config = settings.repositories.get_repo_for_location(repo_path)
927 if options.strict_manifests is not None:
928 if options.strict_manifests == "y":
929 settings.features.add("strict")
931 settings.features.add("discard")
933 if options.update and 'metadata-transfer' not in settings.features:
934 # Forcibly enable metadata-transfer if portdbapi has a pregenerated
935 # cache that does not support eclass validation.
936 cache = repo_config.get_pregenerated_cache(
937 portage.dbapi.dbapi._known_keys, readonly=True)
938 if cache is not None and not cache.complete_eclass_entries:
939 settings.features.add('metadata-transfer')
944 portdb = portage.portdbapi(mysettings=settings)
946 # Limit ebuilds to the specified repo.
947 portdb.porttrees = [repo_path]
950 if options.cache_dir is not None:
951 # already validated earlier
954 # We check write access after the portdbapi constructor
955 # has had an opportunity to create it. This ensures that
956 # we don't use the cache in the "volatile" mode which is
957 # undesirable for egencache.
958 if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
959 writemsg_level("ecachegen: error: " + \
960 "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
961 level=logging.ERROR, noiselevel=-1)
964 if options.sign_manifests is not None:
965 repo_config.sign_manifest = options.sign_manifests == 'y'
967 if options.thin_manifests is not None:
968 repo_config.thin_manifest = options.thin_manifests == 'y'
972 force_sign_key = None
974 if options.update_manifests:
975 if repo_config.sign_manifest:
979 gpg_cmd = settings.get("PORTAGE_GPG_SIGNING_COMMAND")
981 writemsg_level("egencache: error: "
982 "PORTAGE_GPG_SIGNING_COMMAND is unset! "
983 "Is make.globals missing?\n",
984 level=logging.ERROR, noiselevel=-1)
986 elif "${PORTAGE_GPG_KEY}" in gpg_cmd and \
987 options.gpg_key is None and \
988 "PORTAGE_GPG_KEY" not in settings:
989 writemsg_level("egencache: error: "
990 "PORTAGE_GPG_KEY is unset!\n",
991 level=logging.ERROR, noiselevel=-1)
993 elif "${PORTAGE_GPG_DIR}" in gpg_cmd:
994 if options.gpg_dir is not None:
995 gpg_dir = options.gpg_dir
996 elif "PORTAGE_GPG_DIR" not in settings:
997 gpg_dir = os.path.expanduser("~/.gnupg")
999 gpg_dir = os.path.expanduser(settings["PORTAGE_GPG_DIR"])
1000 if not os.access(gpg_dir, os.X_OK):
1001 writemsg_level(("egencache: error: "
1002 "Unable to access directory: "
1003 "PORTAGE_GPG_DIR='%s'\n") % gpg_dir,
1004 level=logging.ERROR, noiselevel=-1)
1008 writemsg_level("egencache: You may disable manifest "
1009 "signatures with --sign-manifests=n or by setting "
1010 "\"sign-manifests = false\" in metadata/layout.conf\n",
1011 level=logging.ERROR, noiselevel=-1)
1015 if gpg_dir is not None:
1016 gpg_vars["PORTAGE_GPG_DIR"] = gpg_dir
1018 if options.gpg_key is None:
1019 gpg_var_names.append("PORTAGE_GPG_KEY")
1021 gpg_vars["PORTAGE_GPG_KEY"] = options.gpg_key
1023 for k in gpg_var_names:
1028 force_sign_key = gpg_vars.get("PORTAGE_GPG_KEY")
1035 cp_iter = iter(atoms)
1037 gen_cache = GenCache(portdb, cp_iter=cp_iter,
1038 max_jobs=options.jobs,
1039 max_load=options.load_average,
1040 rsync=options.rsync)
1042 if options.tolerant:
1043 ret.append(os.EX_OK)
1045 ret.append(gen_cache.returncode)
1047 if options.update_manifests:
1051 cp_iter = iter(atoms)
1053 event_loop = global_event_loop()
1054 scheduler = ManifestScheduler(portdb, cp_iter=cp_iter,
1055 gpg_cmd=gpg_cmd, gpg_vars=gpg_vars,
1056 force_sign_key=force_sign_key,
1057 max_jobs=options.jobs,
1058 max_load=options.load_average,
1059 event_loop=event_loop)
1061 received_signal = []
1063 def sighandler(signum, frame):
1064 signal.signal(signal.SIGINT, signal.SIG_IGN)
1065 signal.signal(signal.SIGTERM, signal.SIG_IGN)
1066 received_signal.append(128 + signum)
1067 scheduler.terminate()
1069 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
1070 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
1076 # Restore previous handlers
1077 if earlier_sigint_handler is not None:
1078 signal.signal(signal.SIGINT, earlier_sigint_handler)
1080 signal.signal(signal.SIGINT, signal.SIG_DFL)
1081 if earlier_sigterm_handler is not None:
1082 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
1084 signal.signal(signal.SIGTERM, signal.SIG_DFL)
1087 sys.exit(received_signal[0])
1089 if options.tolerant:
1090 ret.append(os.EX_OK)
1092 ret.append(scheduler.returncode)
1094 if options.update_use_local_desc:
1095 gen_desc = GenUseLocalDesc(portdb,
1096 output=options.uld_output,
1097 preserve_comments=options.preserve_comments)
1099 ret.append(gen_desc.returncode)
1101 if options.update_changelogs:
1102 gen_clogs = GenChangeLogs(portdb)
1104 ret.append(gen_clogs.returncode)
1108 if __name__ == "__main__":
1109 portage._disable_legacy_globals()
1110 portage.util.noiselimit = -1
1111 sys.exit(egencache_main(sys.argv[1:]))