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)
44 from os import path as osp
45 pym_path = osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym")
46 sys.path.insert(0, pym_path)
48 portage._internal_caller = True
49 from portage import os, _encodings, _unicode_encode, _unicode_decode
50 from _emerge.MetadataRegen import MetadataRegen
51 from portage.cache.cache_errors import CacheError, StatCollision
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._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 = optparse.OptionParser(usage=usage)
82 actions = optparse.OptionGroup(parser, 'Actions')
83 actions.add_option("--update",
85 help="update metadata/cache/ (generate as necessary)")
86 actions.add_option("--update-use-local-desc",
88 help="update the use.local.desc file from metadata.xml")
89 actions.add_option("--update-changelogs",
91 help="update the ChangeLog files from SCM logs")
92 actions.add_option("--update-manifests",
94 help="update manifests")
95 parser.add_option_group(actions)
97 common = optparse.OptionGroup(parser, 'Common options')
98 common.add_option("--repo",
100 help="name of repo to operate on (default repo is located at $PORTDIR)")
101 common.add_option("--config-root",
102 help="location of portage config files",
103 dest="portage_configroot")
104 common.add_option("--gpg-dir",
105 help="override the PORTAGE_GPG_DIR variable",
107 common.add_option("--gpg-key",
108 help="override the PORTAGE_GPG_KEY variable",
110 common.add_option("--portdir",
111 help="override the portage tree location",
113 common.add_option("--portdir-overlay",
114 help="override the PORTDIR_OVERLAY variable (requires that --repo is also specified)",
115 dest="portdir_overlay")
116 common.add_option("--sign-manifests",
120 help="manually override layout.conf sign-manifests setting")
121 common.add_option("--strict-manifests",
125 help="manually override \"strict\" FEATURES setting")
126 common.add_option("--thin-manifests",
130 help="manually override layout.conf thin-manifests setting")
131 common.add_option("--tolerant",
133 help="exit successfully if only minor errors occurred")
134 common.add_option("--ignore-default-opts",
136 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
137 parser.add_option_group(common)
139 update = optparse.OptionGroup(parser, '--update options')
140 update.add_option("--cache-dir",
141 help="location of the metadata cache",
143 update.add_option("-j", "--jobs",
145 help="max ebuild processes to spawn")
146 update.add_option("--load-average",
148 help="max load allowed when spawning multiple jobs",
150 update.add_option("--rsync",
152 help="enable rsync stat collision workaround " + \
153 "for bug 139134 (use with --update)")
154 parser.add_option_group(update)
156 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
157 uld.add_option("--preserve-comments",
159 help="preserve the comments from the existing use.local.desc file")
160 uld.add_option("--use-local-desc-output",
161 help="output file for use.local.desc data (or '-' for stdout)",
163 parser.add_option_group(uld)
165 options, args = parser.parse_args(args)
170 jobs = int(options.jobs)
175 parser.error("Invalid: --jobs='%s'" % \
183 if options.load_average:
185 load_average = float(options.load_average)
189 if load_average <= 0.0:
190 parser.error("Invalid: --load-average='%s'" % \
191 (options.load_average,))
193 options.load_average = load_average
196 options.load_average = None
198 options.config_root = options.portage_configroot
199 if options.config_root is not None and \
200 not os.path.isdir(options.config_root):
201 parser.error("Not a directory: --config-root='%s'" % \
202 (options.config_root,))
204 if options.cache_dir is not None:
205 if not os.path.isdir(options.cache_dir):
206 parser.error("Not a directory: --cache-dir='%s'" % \
207 (options.cache_dir,))
208 if not os.access(options.cache_dir, os.W_OK):
209 parser.error("Write access denied: --cache-dir='%s'" % \
210 (options.cache_dir,))
212 if options.portdir_overlay is not None and \
213 options.repo is None:
214 parser.error("--portdir-overlay option requires --repo option")
218 atom = portage.dep.Atom(atom)
219 except portage.exception.InvalidAtom:
220 parser.error('Invalid atom: %s' % (atom,))
222 if not isjustname(atom):
223 parser.error('Atom is too specific: %s' % (atom,))
225 if options.update_use_local_desc:
230 parser.error('--update-use-local-desc requires python with USE=xml!')
232 if options.uld_output == '-' and options.preserve_comments:
233 parser.error('--preserve-comments can not be used when outputting to stdout')
235 return parser, options, args
237 class GenCache(object):
238 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
240 # The caller must set portdb.porttrees in order to constrain
241 # findname, cp_list, and cpv_list to the desired tree.
242 tree = portdb.porttrees[0]
243 self._portdb = portdb
244 self._eclass_db = portdb.repositories.get_repo_for_location(tree).eclass_db
245 self._auxdbkeys = portdb._known_keys
246 # We can globally cleanse stale cache only if we
247 # iterate over every single cp.
248 self._global_cleanse = cp_iter is None
249 if cp_iter is not None:
250 self._cp_set = set(cp_iter)
251 cp_iter = iter(self._cp_set)
252 self._cp_missing = self._cp_set.copy()
255 self._cp_missing = set()
256 write_auxdb = "metadata-transfer" in portdb.settings.features
257 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
258 consumer=self._metadata_callback,
259 max_jobs=max_jobs, max_load=max_load,
260 write_auxdb=write_auxdb, main=True)
261 self.returncode = os.EX_OK
262 conf = portdb.repositories.get_repo_for_location(tree)
263 self._trg_caches = tuple(conf.iter_pregenerated_caches(
264 self._auxdbkeys, force=True, readonly=False))
265 if not self._trg_caches:
266 raise Exception("cache formats '%s' aren't supported" %
267 (" ".join(conf.cache_formats),))
270 for trg_cache in self._trg_caches:
271 if hasattr(trg_cache, 'raise_stat_collision'):
272 trg_cache.raise_stat_collision = True
273 # Make _metadata_callback write this cache first, in case
274 # it raises a StatCollision and triggers mtime
276 self._trg_caches = tuple([trg_cache] +
277 [x for x in self._trg_caches if x is not trg_cache])
279 self._existing_nodes = set()
281 def _metadata_callback(self, cpv, repo_path, metadata,
282 ebuild_hash, eapi_supported):
283 self._existing_nodes.add(cpv)
284 self._cp_missing.discard(cpv_getkey(cpv))
286 # Since we're supposed to be able to efficiently obtain the
287 # EAPI from _parse_eapi_ebuild_head, we don't write cache
288 # entries for unsupported EAPIs.
289 if metadata is not None and eapi_supported:
290 if metadata.get('EAPI') == '0':
292 for trg_cache in self._trg_caches:
293 self._write_cache(trg_cache,
294 cpv, repo_path, metadata, ebuild_hash)
296 def _write_cache(self, trg_cache, cpv, repo_path, metadata, ebuild_hash):
298 if not hasattr(trg_cache, 'raise_stat_collision'):
299 # This cache does not avoid redundant writes automatically,
300 # so check for an identical existing entry before writing.
301 # This prevents unnecessary disk writes and can also prevent
302 # unnecessary rsync transfers.
304 dest = trg_cache[cpv]
305 except (KeyError, CacheError):
308 if trg_cache.validate_entry(dest,
309 ebuild_hash, self._eclass_db):
311 for k in self._auxdbkeys:
312 if dest.get(k, '') != metadata.get(k, ''):
319 chf = trg_cache.validation_chf
320 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
322 trg_cache[cpv] = metadata
323 except StatCollision as sc:
324 # If the content of a cache entry changes and neither the
325 # file mtime nor size changes, it will prevent rsync from
326 # detecting changes. Cache backends may raise this
327 # exception from _setitem() if they detect this type of stat
328 # collision. These exceptions are handled by bumping the
329 # mtime on the ebuild (and the corresponding cache entry).
330 # See bug #139134. It is convenient to include checks for
331 # redundant writes along with the internal StatCollision
332 # detection code, so for caches with the
333 # raise_stat_collision attribute, we do not need to
334 # explicitly check for redundant writes like we do for the
335 # other cache types above.
337 for ec, ec_hash in metadata['_eclasses_'].items():
338 if max_mtime < ec_hash.mtime:
339 max_mtime = ec_hash.mtime
340 if max_mtime == sc.mtime:
342 max_mtime = long(max_mtime)
344 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
348 "%s writing target: %s\n" % (cpv, e),
349 level=logging.ERROR, noiselevel=-1)
351 ebuild_hash.mtime = max_mtime
352 metadata['_mtime_'] = max_mtime
353 trg_cache[cpv] = metadata
354 self._portdb.auxdb[repo_path][cpv] = metadata
356 except CacheError as ce:
359 "%s writing target: %s\n" % (cpv, ce),
360 level=logging.ERROR, noiselevel=-1)
363 signum = run_main_scheduler(self._regen)
364 if signum is not None:
365 sys.exit(128 + signum)
367 self.returncode |= self._regen.returncode
369 for trg_cache in self._trg_caches:
370 self._cleanse_cache(trg_cache)
372 def _cleanse_cache(self, trg_cache):
373 cp_missing = self._cp_missing
375 if self._global_cleanse:
377 for cpv in trg_cache:
382 "Unable to parse cp for '%s'\n" % (cpv,),
383 level=logging.ERROR, noiselevel=-1)
386 except CacheError as ce:
389 "Error listing cache entries for " + \
390 "'%s/metadata/cache': %s, continuing...\n" % \
391 (self._portdb.porttree_root, ce),
392 level=logging.ERROR, noiselevel=-1)
395 cp_set = self._cp_set
397 for cpv in trg_cache:
402 "Unable to parse cp for '%s'\n" % (cpv,),
403 level=logging.ERROR, noiselevel=-1)
405 cp_missing.discard(cp)
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)
418 for cp in sorted(cp_missing):
420 "No ebuilds or cache entries found for '%s'\n" % (cp,),
421 level=logging.ERROR, noiselevel=-1)
424 dead_nodes.difference_update(self._existing_nodes)
430 except CacheError as ce:
433 "%s deleting stale cache: %s\n" % (k, ce),
434 level=logging.ERROR, noiselevel=-1)
436 if not trg_cache.autocommits:
439 except CacheError as ce:
442 "committing target: %s\n" % (ce,),
443 level=logging.ERROR, noiselevel=-1)
445 if hasattr(trg_cache, '_prune_empty_dirs'):
446 trg_cache._prune_empty_dirs()
448 class GenUseLocalDesc(object):
449 def __init__(self, portdb, output=None,
450 preserve_comments=False):
451 self.returncode = os.EX_OK
452 self._portdb = portdb
453 self._output = output
454 self._preserve_comments = preserve_comments
457 repo_path = self._portdb.porttrees[0]
458 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
460 if self._output is None or self._output != '-':
461 if self._output is None:
462 prof_path = os.path.join(repo_path, 'profiles')
463 desc_path = os.path.join(prof_path, 'use.local.desc')
469 desc_path = self._output
472 if self._preserve_comments:
473 # Probe in binary mode, in order to avoid
474 # potential character encoding issues.
475 output = open(_unicode_encode(desc_path,
476 encoding=_encodings['fs'], errors='strict'), 'r+b')
478 output = io.open(_unicode_encode(desc_path,
479 encoding=_encodings['fs'], errors='strict'),
480 mode='w', encoding=_encodings['repo.content'],
481 errors='backslashreplace')
483 if not self._preserve_comments or \
484 os.path.isfile(desc_path):
486 "ERROR: failed to open output file %s: %s\n" \
487 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
491 # Open in r+b mode failed because the file doesn't
492 # exist yet. We can probably recover if we disable
493 # preserve_comments mode now.
495 "WARNING: --preserve-comments enabled, but " + \
496 "output file not found: %s\n" % (desc_path,),
497 level=logging.WARNING, noiselevel=-1)
498 self._preserve_comments = False
500 output = io.open(_unicode_encode(desc_path,
501 encoding=_encodings['fs'], errors='strict'),
502 mode='w', encoding=_encodings['repo.content'],
503 errors='backslashreplace')
506 "ERROR: failed to open output file %s: %s\n" \
507 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
513 if self._preserve_comments:
516 if not output.readline().startswith(b'#'):
522 # Finished probing comments in binary mode, now append
524 output = io.open(_unicode_encode(desc_path,
525 encoding=_encodings['fs'], errors='strict'),
526 mode='a', encoding=_encodings['repo.content'],
527 errors='backslashreplace')
530 output.write(textwrap.dedent('''\
531 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
532 # your descriptions to your package's metadata.xml ONLY.
533 # * generated automatically using egencache *
537 # The cmp function no longer exists in python3, so we'll
538 # implement our own here under a slightly different name
539 # since we don't want any confusion given that we never
540 # want to rely on the builtin cmp function.
542 if a is None or b is None:
543 # None can't be compared with other types in python3.
544 if a is None and b is None:
550 return (a > b) - (a < b)
552 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
554 Implements doctype() as required to avoid deprecation warnings
557 def doctype(self, name, pubid, system):
560 for cp in self._portdb.cp_all():
561 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
563 metadata = ElementTree.parse(_unicode_encode(metadata_path,
564 encoding=_encodings['fs'], errors='strict'),
565 parser=ElementTree.XMLParser(
566 target=_MetadataTreeBuilder()))
569 except (ExpatError, EnvironmentError) as e:
571 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
572 level=logging.ERROR, noiselevel=-1)
576 usedict = parse_metadata_use(metadata)
577 except portage.exception.ParseError as e:
579 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
580 level=logging.ERROR, noiselevel=-1)
583 for flag in sorted(usedict):
584 def atomcmp(atoma, atomb):
585 # None is better than an atom, that's why we reverse the args
586 if atoma is None or atomb is None:
587 return cmp_func(atomb, atoma)
588 # Same for plain PNs (.operator is None then)
589 elif atoma.operator is None or atomb.operator is None:
590 return cmp_func(atomb.operator, atoma.operator)
592 elif atoma.cpv != atomb.cpv:
593 return vercmp(atoma.version, atomb.version)
594 # Versions match, let's fallback to operator matching
596 return cmp_func(ops.get(atoma.operator, -1),
597 ops.get(atomb.operator, -1))
604 resdict = usedict[flag]
605 if len(resdict) == 1:
606 resdesc = next(iter(resdict.items()))[1]
609 reskeys = dict((_Atom(k), k) for k in resdict)
610 except portage.exception.InvalidAtom as e:
612 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
613 level=logging.ERROR, noiselevel=-1)
615 resdesc = next(iter(resdict.items()))[1]
617 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
618 resdesc = resdict[reskeys[resatoms[-1]]]
620 output.write('%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('''\
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('*%s (%s)\n' % (c[1:-7], date))
791 # strip '<cp>: ', '[<cp>] ', and similar
792 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
793 # strip trailing newline
797 if body[-1].startswith('git-svn-id:') and not body[-2]:
799 # strip the repoman version/manifest note
800 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
802 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
807 # don't break filenames on hyphens
808 self._wrapper.break_on_hyphens = False
809 output.write(self._wrapper.fill(
810 '%s; %s %s:' % (date, author, ', '.join(changed))))
811 # but feel free to break commit messages there
812 self._wrapper.break_on_hyphens = True
814 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body))
819 repo_path = self._portdb.porttrees[0]
822 if 'git' not in FindVCS():
824 "ERROR: --update-changelogs supported only in git repos\n",
825 level=logging.ERROR, noiselevel=-1)
826 self.returncode = 127
829 for cp in self._portdb.cp_all():
830 os.chdir(os.path.join(repo_path, cp))
831 # Determine whether ChangeLog is up-to-date by comparing
832 # the newest commit timestamp with the ChangeLog timestamp.
833 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
835 # This cp has not been added to the repo.
839 cmod = os.stat('ChangeLog').st_mtime
843 if float(cmod) < float(lmod):
844 self.generate_changelog(cp)
846 def egencache_main(args):
848 # The calling environment is ignored, so the program is
849 # completely controlled by commandline arguments.
852 if not sys.stdout.isatty():
853 portage.output.nocolor()
854 env['NOCOLOR'] = 'true'
856 parser, options, atoms = parse_args(args)
858 config_root = options.config_root
860 if options.repo is None:
861 env['PORTDIR_OVERLAY'] = ''
862 elif options.portdir_overlay:
863 env['PORTDIR_OVERLAY'] = options.portdir_overlay
865 if options.cache_dir is not None:
866 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
868 if options.portdir is not None:
869 env['PORTDIR'] = options.portdir
871 settings = portage.config(config_root=config_root,
872 local_config=False, env=env)
875 if not options.ignore_default_opts:
876 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
879 parser, options, args = parse_args(default_opts + args)
881 if options.cache_dir is not None:
882 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
884 settings = portage.config(config_root=config_root,
885 local_config=False, env=env)
887 if not (options.update or options.update_use_local_desc or
888 options.update_changelogs or options.update_manifests):
889 parser.error('No action specified')
893 if options.repo is not None:
894 repo_path = settings.repositories.treemap.get(options.repo)
895 if repo_path is None:
896 parser.error("Unable to locate repository named '%s'" % \
900 repo_path = settings.repositories.mainRepoLocation()
902 parser.error("PORTDIR is undefined")
905 repo_config = settings.repositories.get_repo_for_location(repo_path)
907 if options.strict_manifests is not None:
908 if options.strict_manifests == "y":
909 settings.features.add("strict")
911 settings.features.discard("strict")
913 if options.update and 'metadata-transfer' not in settings.features:
914 # Forcibly enable metadata-transfer if portdbapi has a pregenerated
915 # cache that does not support eclass validation.
916 cache = repo_config.get_pregenerated_cache(
917 portage.dbapi.dbapi._known_keys, readonly=True)
918 if cache is not None and not cache.complete_eclass_entries:
919 settings.features.add('metadata-transfer')
924 portdb = portage.portdbapi(mysettings=settings)
926 # Limit ebuilds to the specified repo.
927 portdb.porttrees = [repo_path]
930 if options.cache_dir is not None:
931 # already validated earlier
934 # We check write access after the portdbapi constructor
935 # has had an opportunity to create it. This ensures that
936 # we don't use the cache in the "volatile" mode which is
937 # undesirable for egencache.
938 if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
939 writemsg_level("ecachegen: error: " + \
940 "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
941 level=logging.ERROR, noiselevel=-1)
944 if options.sign_manifests is not None:
945 repo_config.sign_manifest = options.sign_manifests == 'y'
947 if options.thin_manifests is not None:
948 repo_config.thin_manifest = options.thin_manifests == 'y'
952 force_sign_key = None
954 if options.update_manifests:
955 if repo_config.sign_manifest:
959 gpg_cmd = settings.get("PORTAGE_GPG_SIGNING_COMMAND")
961 writemsg_level("egencache: error: "
962 "PORTAGE_GPG_SIGNING_COMMAND is unset! "
963 "Is make.globals missing?\n",
964 level=logging.ERROR, noiselevel=-1)
966 elif "${PORTAGE_GPG_KEY}" in gpg_cmd and \
967 options.gpg_key is None and \
968 "PORTAGE_GPG_KEY" not in settings:
969 writemsg_level("egencache: error: "
970 "PORTAGE_GPG_KEY is unset!\n",
971 level=logging.ERROR, noiselevel=-1)
973 elif "${PORTAGE_GPG_DIR}" in gpg_cmd:
974 if options.gpg_dir is not None:
975 gpg_dir = options.gpg_dir
976 elif "PORTAGE_GPG_DIR" not in settings:
977 gpg_dir = os.path.expanduser("~/.gnupg")
979 gpg_dir = os.path.expanduser(settings["PORTAGE_GPG_DIR"])
980 if not os.access(gpg_dir, os.X_OK):
981 writemsg_level(("egencache: error: "
982 "Unable to access directory: "
983 "PORTAGE_GPG_DIR='%s'\n") % gpg_dir,
984 level=logging.ERROR, noiselevel=-1)
988 writemsg_level("egencache: You may disable manifest "
989 "signatures with --sign-manifests=n or by setting "
990 "\"sign-manifests = false\" in metadata/layout.conf\n",
991 level=logging.ERROR, noiselevel=-1)
995 if gpg_dir is not None:
996 gpg_vars["PORTAGE_GPG_DIR"] = gpg_dir
998 if options.gpg_key is None:
999 gpg_var_names.append("PORTAGE_GPG_KEY")
1001 gpg_vars["PORTAGE_GPG_KEY"] = options.gpg_key
1003 for k in gpg_var_names:
1008 force_sign_key = gpg_vars.get("PORTAGE_GPG_KEY")
1015 cp_iter = iter(atoms)
1017 gen_cache = GenCache(portdb, cp_iter=cp_iter,
1018 max_jobs=options.jobs,
1019 max_load=options.load_average,
1020 rsync=options.rsync)
1022 if options.tolerant:
1023 ret.append(os.EX_OK)
1025 ret.append(gen_cache.returncode)
1027 if options.update_manifests:
1031 cp_iter = iter(atoms)
1033 event_loop = global_event_loop()
1034 scheduler = ManifestScheduler(portdb, cp_iter=cp_iter,
1035 gpg_cmd=gpg_cmd, gpg_vars=gpg_vars,
1036 force_sign_key=force_sign_key,
1037 max_jobs=options.jobs,
1038 max_load=options.load_average,
1039 event_loop=event_loop)
1041 signum = run_main_scheduler(scheduler)
1042 if signum is not None:
1043 sys.exit(128 + signum)
1045 if options.tolerant:
1046 ret.append(os.EX_OK)
1048 ret.append(scheduler.returncode)
1050 if options.update_use_local_desc:
1051 gen_desc = GenUseLocalDesc(portdb,
1052 output=options.uld_output,
1053 preserve_comments=options.preserve_comments)
1055 ret.append(gen_desc.returncode)
1057 if options.update_changelogs:
1058 gen_clogs = GenChangeLogs(portdb)
1060 ret.append(gen_clogs.returncode)
1064 if __name__ == "__main__":
1065 portage._disable_legacy_globals()
1066 portage.util.noiselimit = -1
1067 sys.exit(egencache_main(sys.argv[1:]))