2 # Copyright 2009-2011 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
5 from __future__ import print_function
9 # This block ensures that ^C interrupts are handled quietly.
12 def exithandler(signum,frame):
13 signal.signal(signal.SIGINT, signal.SIG_IGN)
14 signal.signal(signal.SIGTERM, signal.SIG_IGN)
15 sys.exit(128 + signum)
17 signal.signal(signal.SIGINT, exithandler)
18 signal.signal(signal.SIGTERM, exithandler)
20 except KeyboardInterrupt:
21 sys.exit(128 + signal.SIGINT)
34 from os import path as osp
35 sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
38 from portage import os, _encodings, _unicode_encode, _unicode_decode
39 from _emerge.MetadataRegen import MetadataRegen
40 from portage.cache.cache_errors import CacheError, StatCollision
41 from portage.cache import metadata
42 from portage.manifest import guessManifestFileType
43 from portage.util import cmp_sort_key, writemsg_level
44 from portage import cpv_getkey
45 from portage.dep import Atom, isjustname
46 from portage.versions import pkgcmp, pkgsplit, vercmp
49 from xml.etree import ElementTree
54 from xml.parsers.expat import ExpatError
58 from repoman.utilities import parse_metadata_use
60 from repoman.utilities import FindVCS
62 if sys.hexversion >= 0x3000000:
66 usage = "egencache [options] <action> ... [atom] ..."
67 parser = optparse.OptionParser(usage=usage)
69 actions = optparse.OptionGroup(parser, 'Actions')
70 actions.add_option("--update",
72 help="update metadata/cache/ (generate as necessary)")
73 actions.add_option("--update-use-local-desc",
75 help="update the use.local.desc file from metadata.xml")
76 actions.add_option("--update-changelogs",
78 help="update the ChangeLog files from SCM logs")
79 parser.add_option_group(actions)
81 common = optparse.OptionGroup(parser, 'Common options')
82 common.add_option("--repo",
84 help="name of repo to operate on (default repo is located at $PORTDIR)")
85 common.add_option("--config-root",
86 help="location of portage config files",
87 dest="portage_configroot")
88 common.add_option("--portdir",
89 help="override the portage tree location",
91 common.add_option("--portdir-overlay",
92 help="override the PORTDIR_OVERLAY variable (requires that --repo is also specified)",
93 dest="portdir_overlay")
94 common.add_option("--tolerant",
96 help="exit successfully if only minor errors occurred")
97 common.add_option("--ignore-default-opts",
99 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
100 parser.add_option_group(common)
102 update = optparse.OptionGroup(parser, '--update options')
103 update.add_option("--cache-dir",
104 help="location of the metadata cache",
106 update.add_option("--jobs",
108 help="max ebuild processes to spawn")
109 update.add_option("--load-average",
111 help="max load allowed when spawning multiple jobs",
113 update.add_option("--rsync",
115 help="enable rsync stat collision workaround " + \
116 "for bug 139134 (use with --update)")
117 parser.add_option_group(update)
119 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
120 uld.add_option("--preserve-comments",
122 help="preserve the comments from the existing use.local.desc file")
123 uld.add_option("--use-local-desc-output",
124 help="output file for use.local.desc data (or '-' for stdout)",
126 parser.add_option_group(uld)
128 options, args = parser.parse_args(args)
133 jobs = int(options.jobs)
138 parser.error("Invalid: --jobs='%s'" % \
146 if options.load_average:
148 load_average = float(options.load_average)
152 if load_average <= 0.0:
153 parser.error("Invalid: --load-average='%s'" % \
154 (options.load_average,))
156 options.load_average = load_average
159 options.load_average = None
161 options.config_root = options.portage_configroot
162 if options.config_root is not None and \
163 not os.path.isdir(options.config_root):
164 parser.error("Not a directory: --config-root='%s'" % \
165 (options.config_root,))
167 if options.cache_dir is not None:
168 if not os.path.isdir(options.cache_dir):
169 parser.error("Not a directory: --cache-dir='%s'" % \
170 (options.cache_dir,))
171 if not os.access(options.cache_dir, os.W_OK):
172 parser.error("Write access denied: --cache-dir='%s'" % \
173 (options.cache_dir,))
175 if options.portdir_overlay is not None and \
176 options.repo is None:
177 parser.error("--portdir-overlay option requires --repo option")
181 atom = portage.dep.Atom(atom)
182 except portage.exception.InvalidAtom:
183 parser.error('Invalid atom: %s' % (atom,))
185 if not isjustname(atom):
186 parser.error('Atom is too specific: %s' % (atom,))
188 if options.update_use_local_desc:
193 parser.error('--update-use-local-desc requires python with USE=xml!')
195 if options.uld_output == '-' and options.preserve_comments:
196 parser.error('--preserve-comments can not be used when outputting to stdout')
198 return parser, options, args
200 class GenCache(object):
201 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
203 self._portdb = portdb
204 # We can globally cleanse stale cache only if we
205 # iterate over every single cp.
206 self._global_cleanse = cp_iter is None
207 if cp_iter is not None:
208 self._cp_set = set(cp_iter)
209 cp_iter = iter(self._cp_set)
210 self._cp_missing = self._cp_set.copy()
213 self._cp_missing = set()
214 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
215 consumer=self._metadata_callback,
216 max_jobs=max_jobs, max_load=max_load)
217 self.returncode = os.EX_OK
218 conf = portdb.repositories.get_repo_for_location(portdb.porttrees[0])
219 self._trg_cache = conf.get_pregenerated_cache(portage.auxdbkeys[:],
220 force=True, readonly=False)
221 if self._trg_cache is None:
222 raise Exception("cache format %s isn't supported" % (conf.cache_format,))
224 self._trg_cache.raise_stat_collision = True
226 self._trg_cache.ec = \
227 portdb._repo_info[portdb.porttrees[0]].eclass_db
228 except AttributeError:
230 self._existing_nodes = set()
232 def _metadata_callback(self, cpv, repo_path, metadata, ebuild_hash):
233 self._existing_nodes.add(cpv)
234 self._cp_missing.discard(cpv_getkey(cpv))
235 if metadata is not None:
236 if metadata.get('EAPI') == '0':
239 chf = self._trg_cache.validation_chf
240 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
242 self._trg_cache[cpv] = metadata
243 except StatCollision as sc:
244 # If the content of a cache entry changes and neither the
245 # file mtime nor size changes, it will prevent rsync from
246 # detecting changes. Cache backends may raise this
247 # exception from _setitem() if they detect this type of stat
248 # collision. These exceptions are handled by bumping the
249 # mtime on the ebuild (and the corresponding cache entry).
252 for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
253 if max_mtime < ec_mtime:
255 if max_mtime == sc.mtime:
257 max_mtime = long(max_mtime)
259 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
263 "%s writing target: %s\n" % (cpv, e),
264 level=logging.ERROR, noiselevel=-1)
266 metadata['_mtime_'] = max_mtime
267 self._trg_cache[cpv] = metadata
268 self._portdb.auxdb[repo_path][cpv] = metadata
270 except CacheError as ce:
273 "%s writing target: %s\n" % (cpv, ce),
274 level=logging.ERROR, noiselevel=-1)
280 def sighandler(signum, frame):
281 signal.signal(signal.SIGINT, signal.SIG_IGN)
282 signal.signal(signal.SIGTERM, signal.SIG_IGN)
283 self._regen.terminate()
284 received_signal.append(128 + signum)
286 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
287 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
292 # Restore previous handlers
293 if earlier_sigint_handler is not None:
294 signal.signal(signal.SIGINT, earlier_sigint_handler)
296 signal.signal(signal.SIGINT, signal.SIG_DFL)
297 if earlier_sigterm_handler is not None:
298 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
300 signal.signal(signal.SIGTERM, signal.SIG_DFL)
303 sys.exit(received_signal[0])
305 self.returncode |= self._regen.returncode
306 cp_missing = self._cp_missing
308 trg_cache = self._trg_cache
310 if self._global_cleanse:
312 for cpv in trg_cache:
317 "Unable to parse cp for '%s'\n" % (cpv,),
318 level=logging.ERROR, noiselevel=-1)
321 except CacheError as ce:
324 "Error listing cache entries for " + \
325 "'%s/metadata/cache': %s, continuing...\n" % \
326 (self._portdb.porttree_root, ce),
327 level=logging.ERROR, noiselevel=-1)
330 cp_set = self._cp_set
332 for cpv in trg_cache:
337 "Unable to parse cp for '%s'\n" % (cpv,),
338 level=logging.ERROR, noiselevel=-1)
340 cp_missing.discard(cp)
343 except CacheError as ce:
346 "Error listing cache entries for " + \
347 "'%s/metadata/cache': %s, continuing...\n" % \
348 (self._portdb.porttree_root, ce),
349 level=logging.ERROR, noiselevel=-1)
353 for cp in sorted(cp_missing):
355 "No ebuilds or cache entries found for '%s'\n" % (cp,),
356 level=logging.ERROR, noiselevel=-1)
359 dead_nodes.difference_update(self._existing_nodes)
365 except CacheError as ce:
368 "%s deleting stale cache: %s\n" % (k, ce),
369 level=logging.ERROR, noiselevel=-1)
371 if not trg_cache.autocommits:
374 except CacheError as ce:
377 "committing target: %s\n" % (ce,),
378 level=logging.ERROR, noiselevel=-1)
380 class GenUseLocalDesc(object):
381 def __init__(self, portdb, output=None,
382 preserve_comments=False):
383 self.returncode = os.EX_OK
384 self._portdb = portdb
385 self._output = output
386 self._preserve_comments = preserve_comments
389 repo_path = self._portdb.porttrees[0]
390 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
392 if self._output is None or self._output != '-':
393 if self._output is None:
394 prof_path = os.path.join(repo_path, 'profiles')
395 desc_path = os.path.join(prof_path, 'use.local.desc')
401 desc_path = self._output
404 if self._preserve_comments:
405 # Probe in binary mode, in order to avoid
406 # potential character encoding issues.
407 output = open(_unicode_encode(desc_path,
408 encoding=_encodings['fs'], errors='strict'), 'r+b')
410 output = io.open(_unicode_encode(desc_path,
411 encoding=_encodings['fs'], errors='strict'),
412 mode='w', encoding=_encodings['repo.content'],
413 errors='backslashreplace')
415 if not self._preserve_comments or \
416 os.path.isfile(desc_path):
418 "ERROR: failed to open output file %s: %s\n" \
419 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
423 # Open in r+b mode failed because the file doesn't
424 # exist yet. We can probably recover if we disable
425 # preserve_comments mode now.
427 "WARNING: --preserve-comments enabled, but " + \
428 "output file not found: %s\n" % (desc_path,),
429 level=logging.WARNING, noiselevel=-1)
430 self._preserve_comments = False
432 output = io.open(_unicode_encode(desc_path,
433 encoding=_encodings['fs'], errors='strict'),
434 mode='w', encoding=_encodings['repo.content'],
435 errors='backslashreplace')
438 "ERROR: failed to open output file %s: %s\n" \
439 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
445 if self._preserve_comments:
448 if not output.readline().startswith(b'#'):
454 # Finished probing comments in binary mode, now append
456 output = io.open(_unicode_encode(desc_path,
457 encoding=_encodings['fs'], errors='strict'),
458 mode='a', encoding=_encodings['repo.content'],
459 errors='backslashreplace')
460 output.write(_unicode_decode('\n'))
462 output.write(_unicode_decode('''
463 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
464 # your descriptions to your package's metadata.xml ONLY.
465 # * generated automatically using egencache *
469 # The cmp function no longer exists in python3, so we'll
470 # implement our own here under a slightly different name
471 # since we don't want any confusion given that we never
472 # want to rely on the builtin cmp function.
474 if a is None or b is None:
475 # None can't be compared with other types in python3.
476 if a is None and b is None:
482 return (a > b) - (a < b)
484 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
486 Implements doctype() as required to avoid deprecation warnings
489 def doctype(self, name, pubid, system):
492 for cp in self._portdb.cp_all():
493 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
495 metadata = ElementTree.parse(metadata_path,
496 parser=ElementTree.XMLParser(
497 target=_MetadataTreeBuilder()))
500 except (ExpatError, EnvironmentError) as e:
502 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
503 level=logging.ERROR, noiselevel=-1)
507 usedict = parse_metadata_use(metadata)
508 except portage.exception.ParseError as e:
510 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
511 level=logging.ERROR, noiselevel=-1)
514 for flag in sorted(usedict):
515 def atomcmp(atoma, atomb):
516 # None is better than an atom, that's why we reverse the args
517 if atoma is None or atomb is None:
518 return cmp_func(atomb, atoma)
519 # Same for plain PNs (.operator is None then)
520 elif atoma.operator is None or atomb.operator is None:
521 return cmp_func(atomb.operator, atoma.operator)
523 elif atoma.cpv != atomb.cpv:
524 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
525 # Versions match, let's fallback to operator matching
527 return cmp_func(ops.get(atoma.operator, -1),
528 ops.get(atomb.operator, -1))
535 resdict = usedict[flag]
536 if len(resdict) == 1:
537 resdesc = next(iter(resdict.items()))[1]
540 reskeys = dict((_Atom(k), k) for k in resdict)
541 except portage.exception.InvalidAtom as e:
543 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
544 level=logging.ERROR, noiselevel=-1)
546 resdesc = next(iter(resdict.items()))[1]
548 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
549 resdesc = resdict[reskeys[resatoms[-1]]]
551 output.write(_unicode_decode(
552 '%s:%s - %s\n' % (cp, flag, resdesc)))
556 if sys.hexversion < 0x3000000:
557 _filename_base = unicode
561 class _special_filename(_filename_base):
563 Helps to sort file names by file type and other criteria.
565 def __new__(cls, status_change, file_name):
566 return _filename_base.__new__(cls, status_change + file_name)
568 def __init__(self, status_change, file_name):
569 _filename_base.__init__(status_change + file_name)
570 self.status_change = status_change
571 self.file_name = file_name
572 self.file_type = guessManifestFileType(file_name)
574 def file_type_lt(self, a, b):
576 Defines an ordering between file types.
583 if first == "EBUILD":
585 elif first == "MISC":
586 return second in ("EBUILD",)
588 return second in ("EBUILD", "MISC")
589 elif first == "DIST":
590 return second in ("EBUILD", "MISC", "AUX")
594 raise ValueError("Unknown file type '%s'" % first)
596 def __lt__(self, other):
598 Compare different file names, first by file type and then
599 for ebuilds by version and lexicographically for others.
600 EBUILD < MISC < AUX < DIST < None
602 if self.__class__ != other.__class__:
603 raise NotImplementedError
605 # Sort by file type as defined by file_type_lt().
606 if self.file_type_lt(self, other):
608 elif self.file_type_lt(other, self):
611 # Files have the same type.
612 if self.file_type == "EBUILD":
613 # Sort by version. Lowest first.
614 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
615 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
616 return vercmp(ver, other_ver) < 0
618 # Sort lexicographically.
619 return self.file_name < other.file_name
621 class GenChangeLogs(object):
622 def __init__(self, portdb):
623 self.returncode = os.EX_OK
624 self._portdb = portdb
625 self._wrapper = textwrap.TextWrapper(
627 initial_indent = ' ',
628 subsequent_indent = ' '
633 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
634 return _unicode_decode(p.communicate()[0],
635 encoding=_encodings['stdio'], errors='strict')
637 def generate_changelog(self, cp):
639 output = io.open('ChangeLog',
640 mode='w', encoding=_encodings['repo.content'],
641 errors='backslashreplace')
644 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
645 level=logging.ERROR, noiselevel=-1)
649 output.write(_unicode_decode('''
651 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
654 ''' % (cp, time.strftime('%Y'))).lstrip())
656 # now grab all the commits
657 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
660 # Explaining the arguments:
661 # --name-status to get a list of added/removed files
662 # --no-renames to avoid getting more complex records on the list
663 # --format to get the timestamp, author and commit description
664 # --root to make it work fine even with the initial commit
665 # --relative to get paths relative to ebuilddir
666 # -r (recursive) to get per-file changes
667 # then the commit-id and path.
669 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
670 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
671 c, '--', '.']).rstrip('\n').split('\n')
674 # timestamp Author Name <author@email>
684 for n, l in enumerate(reversed(cinfo)):
690 if f[1] == 'Manifest':
691 pass # XXX: remanifest commits?
692 elif f[1] == 'ChangeLog':
694 elif f[0].startswith('A'):
695 changed.append(_special_filename("+", f[1]))
696 elif f[0].startswith('D'):
697 changed.append(_special_filename("-", f[1]))
698 elif f[0].startswith('M'):
699 changed.append(_special_filename("", f[1]))
702 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
703 level=logging.ERROR, noiselevel=-1)
709 (ts, author) = cinfo[0].split(' ', 1)
710 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
712 changed = [str(x) for x in sorted(changed)]
715 # Reverse the sort order for headers.
716 for c in reversed(changed):
717 if c.startswith('+') and c.endswith('.ebuild'):
718 output.write(_unicode_decode(
719 '*%s (%s)\n' % (c[1:-7], date)))
722 output.write(_unicode_decode('\n'))
724 # strip '<cp>: ', '[<cp>] ', and similar
725 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
726 # strip trailing newline
730 if body[-1].startswith('git-svn-id:') and not body[-2]:
732 # strip the repoman version/manifest note
733 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
735 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
740 # don't break filenames on hyphens
741 self._wrapper.break_on_hyphens = False
742 output.write(_unicode_decode(
744 '%s; %s %s:' % (date, author, ', '.join(changed)))))
745 # but feel free to break commit messages there
746 self._wrapper.break_on_hyphens = True
747 output.write(_unicode_decode(
748 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body)))
753 repo_path = self._portdb.porttrees[0]
756 if 'git' not in FindVCS():
758 "ERROR: --update-changelogs supported only in git repos\n",
759 level=logging.ERROR, noiselevel=-1)
760 self.returncode = 127
763 for cp in self._portdb.cp_all():
764 os.chdir(os.path.join(repo_path, cp))
765 # Determine whether ChangeLog is up-to-date by comparing
766 # the newest commit timestamp with the ChangeLog timestamp.
767 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
769 # This cp has not been added to the repo.
773 cmod = os.stat('ChangeLog').st_mtime
777 if float(cmod) < float(lmod):
778 self.generate_changelog(cp)
780 def egencache_main(args):
781 parser, options, atoms = parse_args(args)
783 config_root = options.config_root
785 # The calling environment is ignored, so the program is
786 # completely controlled by commandline arguments.
789 if options.repo is None:
790 env['PORTDIR_OVERLAY'] = ''
791 elif options.portdir_overlay:
792 env['PORTDIR_OVERLAY'] = options.portdir_overlay
794 if options.cache_dir is not None:
795 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
797 if options.portdir is not None:
798 env['PORTDIR'] = options.portdir
800 eprefix = os.environ.get("__PORTAGE_TEST_EPREFIX")
802 settings = portage.config(config_root=config_root,
803 local_config=False, env=env, _eprefix=eprefix)
806 if not options.ignore_default_opts:
807 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
810 parser, options, args = parse_args(default_opts + args)
812 if options.cache_dir is not None:
813 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
815 settings = portage.config(config_root=config_root,
816 local_config=False, env=env, _eprefix=eprefix)
818 if not options.update and not options.update_use_local_desc \
819 and not options.update_changelogs:
820 parser.error('No action specified')
823 if options.update and 'metadata-transfer' not in settings.features:
824 settings.features.add('metadata-transfer')
828 portdb = portage.portdbapi(mysettings=settings)
831 if options.cache_dir is not None:
832 # already validated earlier
835 # We check write access after the portdbapi constructor
836 # has had an opportunity to create it. This ensures that
837 # we don't use the cache in the "volatile" mode which is
838 # undesirable for egencache.
839 if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
840 writemsg_level("ecachegen: error: " + \
841 "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
842 level=logging.ERROR, noiselevel=-1)
845 if options.repo is not None:
846 repo_path = portdb.getRepositoryPath(options.repo)
847 if repo_path is None:
848 parser.error("Unable to locate repository named '%s'" % \
852 # Limit ebuilds to the specified repo.
853 portdb.porttrees = [repo_path]
860 cp_iter = iter(atoms)
862 gen_cache = GenCache(portdb, cp_iter=cp_iter,
863 max_jobs=options.jobs,
864 max_load=options.load_average,
870 ret.append(gen_cache.returncode)
872 if options.update_use_local_desc:
873 gen_desc = GenUseLocalDesc(portdb,
874 output=options.uld_output,
875 preserve_comments=options.preserve_comments)
877 ret.append(gen_desc.returncode)
879 if options.update_changelogs:
880 gen_clogs = GenChangeLogs(portdb)
882 ret.append(gen_clogs.returncode)
886 if __name__ == "__main__":
887 portage._disable_legacy_globals()
888 portage.util.noiselimit = -1
889 sys.exit(egencache_main(sys.argv[1:]))