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.manifest import guessManifestFileType
42 from portage.util import cmp_sort_key, writemsg_level
43 from portage import cpv_getkey
44 from portage.dep import Atom, isjustname
45 from portage.versions import pkgcmp, pkgsplit, vercmp
48 from xml.etree import ElementTree
53 from xml.parsers.expat import ExpatError
57 from repoman.utilities import parse_metadata_use
59 from repoman.utilities import FindVCS
61 if sys.hexversion >= 0x3000000:
65 usage = "egencache [options] <action> ... [atom] ..."
66 parser = optparse.OptionParser(usage=usage)
68 actions = optparse.OptionGroup(parser, 'Actions')
69 actions.add_option("--update",
71 help="update metadata/cache/ (generate as necessary)")
72 actions.add_option("--update-use-local-desc",
74 help="update the use.local.desc file from metadata.xml")
75 actions.add_option("--update-changelogs",
77 help="update the ChangeLog files from SCM logs")
78 parser.add_option_group(actions)
80 common = optparse.OptionGroup(parser, 'Common options')
81 common.add_option("--repo",
83 help="name of repo to operate on (default repo is located at $PORTDIR)")
84 common.add_option("--config-root",
85 help="location of portage config files",
86 dest="portage_configroot")
87 common.add_option("--portdir",
88 help="override the portage tree location",
90 common.add_option("--portdir-overlay",
91 help="override the PORTDIR_OVERLAY variable (requires that --repo is also specified)",
92 dest="portdir_overlay")
93 common.add_option("--tolerant",
95 help="exit successfully if only minor errors occurred")
96 common.add_option("--ignore-default-opts",
98 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
99 parser.add_option_group(common)
101 update = optparse.OptionGroup(parser, '--update options')
102 update.add_option("--cache-dir",
103 help="location of the metadata cache",
105 update.add_option("--jobs",
107 help="max ebuild processes to spawn")
108 update.add_option("--load-average",
110 help="max load allowed when spawning multiple jobs",
112 update.add_option("--rsync",
114 help="enable rsync stat collision workaround " + \
115 "for bug 139134 (use with --update)")
116 parser.add_option_group(update)
118 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
119 uld.add_option("--preserve-comments",
121 help="preserve the comments from the existing use.local.desc file")
122 uld.add_option("--use-local-desc-output",
123 help="output file for use.local.desc data (or '-' for stdout)",
125 parser.add_option_group(uld)
127 options, args = parser.parse_args(args)
132 jobs = int(options.jobs)
137 parser.error("Invalid: --jobs='%s'" % \
145 if options.load_average:
147 load_average = float(options.load_average)
151 if load_average <= 0.0:
152 parser.error("Invalid: --load-average='%s'" % \
153 (options.load_average,))
155 options.load_average = load_average
158 options.load_average = None
160 options.config_root = options.portage_configroot
161 if options.config_root is not None and \
162 not os.path.isdir(options.config_root):
163 parser.error("Not a directory: --config-root='%s'" % \
164 (options.config_root,))
166 if options.cache_dir is not None and not os.path.isdir(options.cache_dir):
167 parser.error("Not a directory: --cache-dir='%s'" % \
168 (options.cache_dir,))
170 if options.portdir_overlay is not None and \
171 options.repo is None:
172 parser.error("--portdir-overlay option requires --repo option")
176 atom = portage.dep.Atom(atom)
177 except portage.exception.InvalidAtom:
178 parser.error('Invalid atom: %s' % (atom,))
180 if not isjustname(atom):
181 parser.error('Atom is too specific: %s' % (atom,))
183 if options.update_use_local_desc:
188 parser.error('--update-use-local-desc requires python with USE=xml!')
190 if options.uld_output == '-' and options.preserve_comments:
191 parser.error('--preserve-comments can not be used when outputting to stdout')
193 return parser, options, args
195 class GenCache(object):
196 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
198 self._portdb = portdb
199 # We can globally cleanse stale cache only if we
200 # iterate over every single cp.
201 self._global_cleanse = cp_iter is None
202 if cp_iter is not None:
203 self._cp_set = set(cp_iter)
204 cp_iter = iter(self._cp_set)
205 self._cp_missing = self._cp_set.copy()
208 self._cp_missing = set()
209 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
210 consumer=self._metadata_callback,
211 max_jobs=max_jobs, max_load=max_load)
212 self.returncode = os.EX_OK
213 metadbmodule = portdb.settings.load_best_module("portdbapi.metadbmodule")
214 self._trg_cache = metadbmodule(portdb.porttrees[0],
215 "metadata/cache", portage.auxdbkeys[:])
217 self._trg_cache.raise_stat_collision = True
219 self._trg_cache.ec = \
220 portdb._repo_info[portdb.porttrees[0]].eclass_db
221 except AttributeError:
223 self._existing_nodes = set()
225 def _metadata_callback(self, cpv, ebuild_path, repo_path, metadata):
226 self._existing_nodes.add(cpv)
227 self._cp_missing.discard(cpv_getkey(cpv))
228 if metadata is not None:
229 if metadata.get('EAPI') == '0':
233 self._trg_cache[cpv] = metadata
234 except StatCollision as sc:
235 # If the content of a cache entry changes and neither the
236 # file mtime nor size changes, it will prevent rsync from
237 # detecting changes. Cache backends may raise this
238 # exception from _setitem() if they detect this type of stat
239 # collision. These exceptions are handled by bumping the
240 # mtime on the ebuild (and the corresponding cache entry).
243 for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
244 if max_mtime < ec_mtime:
246 if max_mtime == sc.mtime:
248 max_mtime = long(max_mtime)
250 os.utime(ebuild_path, (max_mtime, max_mtime))
254 "%s writing target: %s\n" % (cpv, e),
255 level=logging.ERROR, noiselevel=-1)
257 metadata['_mtime_'] = max_mtime
258 self._trg_cache[cpv] = metadata
259 self._portdb.auxdb[repo_path][cpv] = metadata
261 except CacheError as ce:
264 "%s writing target: %s\n" % (cpv, ce),
265 level=logging.ERROR, noiselevel=-1)
271 def sighandler(signum, frame):
272 signal.signal(signal.SIGINT, signal.SIG_IGN)
273 signal.signal(signal.SIGTERM, signal.SIG_IGN)
274 self._regen.terminate()
275 received_signal.append(128 + signum)
277 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
278 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
283 # Restore previous handlers
284 if earlier_sigint_handler is not None:
285 signal.signal(signal.SIGINT, earlier_sigint_handler)
287 signal.signal(signal.SIGINT, signal.SIG_DFL)
288 if earlier_sigterm_handler is not None:
289 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
291 signal.signal(signal.SIGTERM, signal.SIG_DFL)
294 sys.exit(received_signal[0])
296 self.returncode |= self._regen.returncode
297 cp_missing = self._cp_missing
299 trg_cache = self._trg_cache
301 if self._global_cleanse:
303 for cpv in trg_cache:
308 "Unable to parse cp for '%s'\n" % (cpv,),
309 level=logging.ERROR, noiselevel=-1)
312 except CacheError as ce:
315 "Error listing cache entries for " + \
316 "'%s/metadata/cache': %s, continuing...\n" % \
317 (self._portdb.porttree_root, ce),
318 level=logging.ERROR, noiselevel=-1)
321 cp_set = self._cp_set
323 for cpv in trg_cache:
328 "Unable to parse cp for '%s'\n" % (cpv,),
329 level=logging.ERROR, noiselevel=-1)
331 cp_missing.discard(cp)
334 except CacheError as ce:
337 "Error listing cache entries for " + \
338 "'%s/metadata/cache': %s, continuing...\n" % \
339 (self._portdb.porttree_root, ce),
340 level=logging.ERROR, noiselevel=-1)
344 for cp in sorted(cp_missing):
346 "No ebuilds or cache entries found for '%s'\n" % (cp,),
347 level=logging.ERROR, noiselevel=-1)
350 dead_nodes.difference_update(self._existing_nodes)
356 except CacheError as ce:
359 "%s deleting stale cache: %s\n" % (k, ce),
360 level=logging.ERROR, noiselevel=-1)
362 if not trg_cache.autocommits:
365 except CacheError as ce:
368 "committing target: %s\n" % (ce,),
369 level=logging.ERROR, noiselevel=-1)
371 class GenUseLocalDesc(object):
372 def __init__(self, portdb, output=None,
373 preserve_comments=False):
374 self.returncode = os.EX_OK
375 self._portdb = portdb
376 self._output = output
377 self._preserve_comments = preserve_comments
380 repo_path = self._portdb.porttrees[0]
381 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
383 if self._output is None or self._output != '-':
384 if self._output is None:
385 prof_path = os.path.join(repo_path, 'profiles')
386 desc_path = os.path.join(prof_path, 'use.local.desc')
392 desc_path = self._output
395 if self._preserve_comments:
396 # Probe in binary mode, in order to avoid
397 # potential character encoding issues.
398 output = open(_unicode_encode(desc_path,
399 encoding=_encodings['fs'], errors='strict'), 'r+b')
401 output = io.open(_unicode_encode(desc_path,
402 encoding=_encodings['fs'], errors='strict'),
403 mode='w', encoding=_encodings['repo.content'],
404 errors='backslashreplace')
406 if not self._preserve_comments or \
407 os.path.isfile(desc_path):
409 "ERROR: failed to open output file %s: %s\n" \
410 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
414 # Open in r+b mode failed because the file doesn't
415 # exist yet. We can probably recover if we disable
416 # preserve_comments mode now.
418 "WARNING: --preserve-comments enabled, but " + \
419 "output file not found: %s\n" % (desc_path,),
420 level=logging.WARNING, noiselevel=-1)
421 self._preserve_comments = False
423 output = io.open(_unicode_encode(desc_path,
424 encoding=_encodings['fs'], errors='strict'),
425 mode='w', encoding=_encodings['repo.content'],
426 errors='backslashreplace')
429 "ERROR: failed to open output file %s: %s\n" \
430 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
436 if self._preserve_comments:
439 if not output.readline().startswith(b'#'):
445 # Finished probing comments in binary mode, now append
447 output = io.open(_unicode_encode(desc_path,
448 encoding=_encodings['fs'], errors='strict'),
449 mode='a', encoding=_encodings['repo.content'],
450 errors='backslashreplace')
451 output.write(_unicode_decode('\n'))
453 output.write(_unicode_decode('''
454 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
455 # your descriptions to your package's metadata.xml ONLY.
456 # * generated automatically using egencache *
460 # The cmp function no longer exists in python3, so we'll
461 # implement our own here under a slightly different name
462 # since we don't want any confusion given that we never
463 # want to rely on the builtin cmp function.
465 if a is None or b is None:
466 # None can't be compared with other types in python3.
467 if a is None and b is None:
473 return (a > b) - (a < b)
475 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
477 Implements doctype() as required to avoid deprecation warnings
480 def doctype(self, name, pubid, system):
483 for cp in self._portdb.cp_all():
484 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
486 metadata = ElementTree.parse(metadata_path,
487 parser=ElementTree.XMLParser(
488 target=_MetadataTreeBuilder()))
491 except (ExpatError, EnvironmentError) as e:
493 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
494 level=logging.ERROR, noiselevel=-1)
498 usedict = parse_metadata_use(metadata)
499 except portage.exception.ParseError as e:
501 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
502 level=logging.ERROR, noiselevel=-1)
505 for flag in sorted(usedict):
506 def atomcmp(atoma, atomb):
507 # None is better than an atom, that's why we reverse the args
508 if atoma is None or atomb is None:
509 return cmp_func(atomb, atoma)
510 # Same for plain PNs (.operator is None then)
511 elif atoma.operator is None or atomb.operator is None:
512 return cmp_func(atomb.operator, atoma.operator)
514 elif atoma.cpv != atomb.cpv:
515 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
516 # Versions match, let's fallback to operator matching
518 return cmp_func(ops.get(atoma.operator, -1),
519 ops.get(atomb.operator, -1))
526 resdict = usedict[flag]
527 if len(resdict) == 1:
528 resdesc = next(iter(resdict.items()))[1]
531 reskeys = dict((_Atom(k), k) for k in resdict)
532 except portage.exception.InvalidAtom as e:
534 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
535 level=logging.ERROR, noiselevel=-1)
537 resdesc = next(iter(resdict.items()))[1]
539 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
540 resdesc = resdict[reskeys[resatoms[-1]]]
542 output.write(_unicode_decode(
543 '%s:%s - %s\n' % (cp, flag, resdesc)))
547 if sys.hexversion < 0x3000000:
548 _filename_base = unicode
552 class _special_filename(_filename_base):
554 Helps to sort file names by file type and other criteria.
556 def __new__(cls, status_change, file_name):
557 return _filename_base.__new__(cls, status_change + file_name)
559 def __init__(self, status_change, file_name):
560 _filename_base.__init__(status_change + file_name)
561 self.status_change = status_change
562 self.file_name = file_name
563 self.file_type = guessManifestFileType(file_name)
565 def file_type_lt(self, a, b):
567 Defines an ordering between file types.
574 if first == "EBUILD":
576 elif first == "MISC":
577 return second in ("EBUILD",)
579 return second in ("EBUILD", "MISC")
580 elif first == "DIST":
581 return second in ("EBUILD", "MISC", "AUX")
585 raise ValueError("Unknown file type '%s'" % first)
587 def __lt__(self, other):
589 Compare different file names, first by file type and then
590 for ebuilds by version and lexicographically for others.
591 EBUILD < MISC < AUX < DIST < None
593 if self.__class__ != other.__class__:
594 raise NotImplementedError
596 # Sort by file type as defined by file_type_lt().
597 if self.file_type_lt(self, other):
599 elif self.file_type_lt(other, self):
602 # Files have the same type.
603 if self.file_type == "EBUILD":
604 # Sort by version. Lowest first.
605 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
606 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
607 return vercmp(ver, other_ver) < 0
609 # Sort lexicographically.
610 return self.file_name < other.file_name
612 class GenChangeLogs(object):
613 def __init__(self, portdb):
614 self.returncode = os.EX_OK
615 self._portdb = portdb
616 self._wrapper = textwrap.TextWrapper(
618 initial_indent = ' ',
619 subsequent_indent = ' '
624 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
625 return _unicode_decode(p.communicate()[0],
626 encoding=_encodings['stdio'], errors='strict')
628 def generate_changelog(self, cp):
630 output = io.open('ChangeLog',
631 mode='w', encoding=_encodings['repo.content'],
632 errors='backslashreplace')
635 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
636 level=logging.ERROR, noiselevel=-1)
640 output.write(_unicode_decode('''
642 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
645 ''' % (cp, time.strftime('%Y'))).lstrip())
647 # now grab all the commits
648 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
651 # Explaining the arguments:
652 # --name-status to get a list of added/removed files
653 # --no-renames to avoid getting more complex records on the list
654 # --format to get the timestamp, author and commit description
655 # --root to make it work fine even with the initial commit
656 # --relative to get paths relative to ebuilddir
657 # -r (recursive) to get per-file changes
658 # then the commit-id and path.
660 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
661 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
662 c, '--', '.']).rstrip('\n').split('\n')
665 # timestamp Author Name <author@email>
675 for n, l in enumerate(reversed(cinfo)):
681 if f[1] == 'Manifest':
682 pass # XXX: remanifest commits?
683 elif f[1] == 'ChangeLog':
685 elif f[0].startswith('A'):
686 changed.append(_special_filename("+", f[1]))
687 elif f[0].startswith('D'):
688 changed.append(_special_filename("-", f[1]))
689 elif f[0].startswith('M'):
690 changed.append(_special_filename("", f[1]))
693 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
694 level=logging.ERROR, noiselevel=-1)
700 (ts, author) = cinfo[0].split(' ', 1)
701 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
703 changed = [str(x) for x in sorted(changed)]
706 # Reverse the sort order for headers.
707 for c in reversed(changed):
708 if c.startswith('+') and c.endswith('.ebuild'):
709 output.write(_unicode_decode(
710 '*%s (%s)\n' % (c[1:-7], date)))
713 output.write(_unicode_decode('\n'))
715 # strip '<cp>: ', '[<cp>] ', and similar
716 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
717 # strip trailing newline
721 if body[-1].startswith('git-svn-id:') and not body[-2]:
723 # strip the repoman version/manifest note
724 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
726 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
731 # don't break filenames on hyphens
732 self._wrapper.break_on_hyphens = False
733 output.write(_unicode_decode(
735 '%s; %s %s:' % (date, author, ', '.join(changed)))))
736 # but feel free to break commit messages there
737 self._wrapper.break_on_hyphens = True
738 output.write(_unicode_decode(
739 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body)))
744 repo_path = self._portdb.porttrees[0]
747 if 'git' not in FindVCS():
749 "ERROR: --update-changelogs supported only in git repos\n",
750 level=logging.ERROR, noiselevel=-1)
751 self.returncode = 127
754 for cp in self._portdb.cp_all():
755 os.chdir(os.path.join(repo_path, cp))
756 # Determine whether ChangeLog is up-to-date by comparing
757 # the newest commit timestamp with the ChangeLog timestamp.
758 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
760 # This cp has not been added to the repo.
764 cmod = os.stat('ChangeLog').st_mtime
768 if float(cmod) < float(lmod):
769 self.generate_changelog(cp)
771 def egencache_main(args):
772 parser, options, atoms = parse_args(args)
774 config_root = options.config_root
775 if config_root is None:
778 # The calling environment is ignored, so the program is
779 # completely controlled by commandline arguments.
782 if options.repo is None:
783 env['PORTDIR_OVERLAY'] = ''
784 elif options.portdir_overlay:
785 env['PORTDIR_OVERLAY'] = options.portdir_overlay
787 if options.cache_dir is not None:
788 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
790 if options.portdir is not None:
791 env['PORTDIR'] = options.portdir
793 settings = portage.config(config_root=config_root,
794 target_root='/', local_config=False, env=env)
797 if not options.ignore_default_opts:
798 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
801 parser, options, args = parse_args(default_opts + args)
803 if options.config_root is not None:
804 config_root = options.config_root
806 if options.cache_dir is not None:
807 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
809 settings = portage.config(config_root=config_root,
810 target_root='/', local_config=False, env=env)
812 if not options.update and not options.update_use_local_desc \
813 and not options.update_changelogs:
814 parser.error('No action specified')
817 if options.update and 'metadata-transfer' not in settings.features:
818 writemsg_level("ecachegen: warning: " + \
819 "automatically enabling FEATURES=metadata-transfer\n",
820 level=logging.WARNING, noiselevel=-1)
821 settings.features.add('metadata-transfer')
825 portdb = portage.portdbapi(mysettings=settings)
826 if options.repo is not None:
827 repo_path = portdb.getRepositoryPath(options.repo)
828 if repo_path is None:
829 parser.error("Unable to locate repository named '%s'" % \
833 # Limit ebuilds to the specified repo.
834 portdb.porttrees = [repo_path]
841 cp_iter = iter(atoms)
843 gen_cache = GenCache(portdb, cp_iter=cp_iter,
844 max_jobs=options.jobs,
845 max_load=options.load_average,
851 ret.append(gen_cache.returncode)
853 if options.update_use_local_desc:
854 gen_desc = GenUseLocalDesc(portdb,
855 output=options.uld_output,
856 preserve_comments=options.preserve_comments)
858 ret.append(gen_desc.returncode)
860 if options.update_changelogs:
861 gen_clogs = GenChangeLogs(portdb)
863 ret.append(gen_clogs.returncode)
867 if __name__ == "__main__":
868 portage._disable_legacy_globals()
869 portage.util.noiselimit = -1
870 sys.exit(egencache_main(sys.argv[1:]))