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("--tolerant",
92 help="exit successfully if only minor errors occurred")
93 common.add_option("--ignore-default-opts",
95 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
96 parser.add_option_group(common)
98 update = optparse.OptionGroup(parser, '--update options')
99 update.add_option("--cache-dir",
100 help="location of the metadata cache",
102 update.add_option("--jobs",
104 help="max ebuild processes to spawn")
105 update.add_option("--load-average",
107 help="max load allowed when spawning multiple jobs",
109 update.add_option("--rsync",
111 help="enable rsync stat collision workaround " + \
112 "for bug 139134 (use with --update)")
113 parser.add_option_group(update)
115 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
116 uld.add_option("--preserve-comments",
118 help="preserve the comments from the existing use.local.desc file")
119 uld.add_option("--use-local-desc-output",
120 help="output file for use.local.desc data (or '-' for stdout)",
122 parser.add_option_group(uld)
124 options, args = parser.parse_args(args)
129 jobs = int(options.jobs)
134 parser.error("Invalid: --jobs='%s'" % \
142 if options.load_average:
144 load_average = float(options.load_average)
148 if load_average <= 0.0:
149 parser.error("Invalid: --load-average='%s'" % \
150 (options.load_average,))
152 options.load_average = load_average
155 options.load_average = None
157 options.config_root = options.portage_configroot
158 if options.config_root is not None and \
159 not os.path.isdir(options.config_root):
160 parser.error("Not a directory: --config-root='%s'" % \
161 (options.config_root,))
163 if options.cache_dir is not None and not os.path.isdir(options.cache_dir):
164 parser.error("Not a directory: --cache-dir='%s'" % \
165 (options.cache_dir,))
169 atom = portage.dep.Atom(atom)
170 except portage.exception.InvalidAtom:
171 parser.error('Invalid atom: %s' % (atom,))
173 if not isjustname(atom):
174 parser.error('Atom is too specific: %s' % (atom,))
176 if options.update_use_local_desc:
181 parser.error('--update-use-local-desc requires python with USE=xml!')
183 if options.uld_output == '-' and options.preserve_comments:
184 parser.error('--preserve-comments can not be used when outputting to stdout')
186 return parser, options, args
188 class GenCache(object):
189 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
191 self._portdb = portdb
192 # We can globally cleanse stale cache only if we
193 # iterate over every single cp.
194 self._global_cleanse = cp_iter is None
195 if cp_iter is not None:
196 self._cp_set = set(cp_iter)
197 cp_iter = iter(self._cp_set)
198 self._cp_missing = self._cp_set.copy()
201 self._cp_missing = set()
202 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
203 consumer=self._metadata_callback,
204 max_jobs=max_jobs, max_load=max_load)
205 self.returncode = os.EX_OK
206 metadbmodule = portdb.settings.load_best_module("portdbapi.metadbmodule")
207 self._trg_cache = metadbmodule(portdb.porttrees[0],
208 "metadata/cache", portage.auxdbkeys[:])
210 self._trg_cache.raise_stat_collision = True
212 self._trg_cache.ec = \
213 portdb._repo_info[portdb.porttrees[0]].eclass_db
214 except AttributeError:
216 self._existing_nodes = set()
218 def _metadata_callback(self, cpv, ebuild_path, repo_path, metadata):
219 self._existing_nodes.add(cpv)
220 self._cp_missing.discard(cpv_getkey(cpv))
221 if metadata is not None:
222 if metadata.get('EAPI') == '0':
226 self._trg_cache[cpv] = metadata
227 except StatCollision as sc:
228 # If the content of a cache entry changes and neither the
229 # file mtime nor size changes, it will prevent rsync from
230 # detecting changes. Cache backends may raise this
231 # exception from _setitem() if they detect this type of stat
232 # collision. These exceptions are handled by bumping the
233 # mtime on the ebuild (and the corresponding cache entry).
236 for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
237 if max_mtime < ec_mtime:
239 if max_mtime == sc.mtime:
241 max_mtime = long(max_mtime)
243 os.utime(ebuild_path, (max_mtime, max_mtime))
247 "%s writing target: %s\n" % (cpv, e),
248 level=logging.ERROR, noiselevel=-1)
250 metadata['_mtime_'] = max_mtime
251 self._trg_cache[cpv] = metadata
252 self._portdb.auxdb[repo_path][cpv] = metadata
254 except CacheError as ce:
257 "%s writing target: %s\n" % (cpv, ce),
258 level=logging.ERROR, noiselevel=-1)
264 def sighandler(signum, frame):
265 signal.signal(signal.SIGINT, signal.SIG_IGN)
266 signal.signal(signal.SIGTERM, signal.SIG_IGN)
267 self._regen.terminate()
268 received_signal.append(128 + signum)
270 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
271 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
277 sys.exit(received_signal[0])
279 # Restore previous handlers
280 if earlier_sigint_handler is not None:
281 signal.signal(signal.SIGINT, earlier_sigint_handler)
282 if earlier_sigterm_handler is not None:
283 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
285 self.returncode |= self._regen.returncode
286 cp_missing = self._cp_missing
288 trg_cache = self._trg_cache
290 if self._global_cleanse:
292 for cpv in trg_cache:
297 "Unable to parse cp for '%s'\n" % (cpv,),
298 level=logging.ERROR, noiselevel=-1)
301 except CacheError as ce:
304 "Error listing cache entries for " + \
305 "'%s/metadata/cache': %s, continuing...\n" % \
306 (self._portdb.porttree_root, ce),
307 level=logging.ERROR, noiselevel=-1)
310 cp_set = self._cp_set
312 for cpv in trg_cache:
317 "Unable to parse cp for '%s'\n" % (cpv,),
318 level=logging.ERROR, noiselevel=-1)
320 cp_missing.discard(cp)
323 except CacheError as ce:
326 "Error listing cache entries for " + \
327 "'%s/metadata/cache': %s, continuing...\n" % \
328 (self._portdb.porttree_root, ce),
329 level=logging.ERROR, noiselevel=-1)
333 for cp in sorted(cp_missing):
335 "No ebuilds or cache entries found for '%s'\n" % (cp,),
336 level=logging.ERROR, noiselevel=-1)
339 dead_nodes.difference_update(self._existing_nodes)
345 except CacheError as ce:
348 "%s deleting stale cache: %s\n" % (k, ce),
349 level=logging.ERROR, noiselevel=-1)
351 if not trg_cache.autocommits:
354 except CacheError as ce:
357 "committing target: %s\n" % (ce,),
358 level=logging.ERROR, noiselevel=-1)
360 class GenUseLocalDesc(object):
361 def __init__(self, portdb, output=None,
362 preserve_comments=False):
363 self.returncode = os.EX_OK
364 self._portdb = portdb
365 self._output = output
366 self._preserve_comments = preserve_comments
369 repo_path = self._portdb.porttrees[0]
370 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
372 if self._output is None or self._output != '-':
373 if self._output is None:
374 prof_path = os.path.join(repo_path, 'profiles')
375 desc_path = os.path.join(prof_path, 'use.local.desc')
381 desc_path = self._output
384 if self._preserve_comments:
385 # Probe in binary mode, in order to avoid
386 # potential character encoding issues.
387 output = open(_unicode_encode(desc_path,
388 encoding=_encodings['fs'], errors='strict'), 'r+b')
390 output = codecs.open(_unicode_encode(desc_path,
391 encoding=_encodings['fs'], errors='strict'),
392 mode='w', encoding=_encodings['repo.content'],
396 "ERROR: failed to open output file %s: %s\n" % (desc_path,e,),
397 level=logging.ERROR, noiselevel=-1)
403 if self._preserve_comments:
406 if not output.readline().startswith(b'#'):
412 # Finished probing comments in binary mode, now append
414 output = codecs.open(_unicode_encode(desc_path,
415 encoding=_encodings['fs'], errors='strict'),
416 mode='a', encoding=_encodings['repo.content'],
421 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
422 # your descriptions to your package's metadata.xml ONLY.
423 # * generated automatically using egencache *
427 # The cmp function no longer exists in python3, so we'll
428 # implement our own here under a slightly different name
429 # since we don't want any confusion given that we never
430 # want to rely on the builtin cmp function.
432 return (a > b) - (a < b)
434 for cp in self._portdb.cp_all():
435 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
437 metadata = ElementTree.parse(metadata_path)
440 except (ExpatError, EnvironmentError) as e:
442 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
443 level=logging.ERROR, noiselevel=-1)
447 usedict = parse_metadata_use(metadata)
448 except portage.exception.ParseError as e:
450 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
451 level=logging.ERROR, noiselevel=-1)
454 for flag in sorted(usedict):
455 def atomcmp(atoma, atomb):
456 # None is better than an atom, that's why we reverse the args
457 if atoma is None or atomb is None:
458 return cmp_func(atomb, atoma)
459 # Same for plain PNs (.operator is None then)
460 elif atoma.operator is None or atomb.operator is None:
461 return cmp_func(atomb.operator, atoma.operator)
463 elif atoma.cpv != atomb.cpv:
464 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
465 # Versions match, let's fallback to operator matching
467 return cmp_func(ops.get(atoma.operator, -1),
468 ops.get(atomb.operator, -1))
475 resdict = usedict[flag]
476 if len(resdict) == 1:
477 resdesc = next(iter(resdict.items()))[1]
480 reskeys = dict((_Atom(k), k) for k in resdict)
481 except portage.exception.InvalidAtom as e:
483 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
484 level=logging.ERROR, noiselevel=-1)
486 resdesc = next(iter(resdict.items()))[1]
488 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
489 resdesc = resdict[reskeys[resatoms[-1]]]
491 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
495 if sys.hexversion < 0x3000000:
496 _filename_base = unicode
500 class _special_filename(_filename_base):
502 Helps to sort file names by file type and other criteria.
504 def __new__(cls, status_change, file_name):
505 return _filename_base.__new__(cls, status_change + file_name)
507 def __init__(self, status_change, file_name):
508 _filename_base.__init__(status_change + file_name)
509 self.status_change = status_change
510 self.file_name = file_name
511 self.file_type = guessManifestFileType(file_name)
513 def file_type_lt(self, a, b):
515 Defines an ordering between file types.
522 if first == "EBUILD":
524 elif first == "MISC":
525 return second in ("EBUILD",)
527 return second in ("EBUILD", "MISC")
528 elif first == "DIST":
529 return second in ("EBUILD", "MISC", "AUX")
533 raise ValueError("Unknown file type '%s'" % first)
535 def __lt__(self, other):
537 Compare different file names, first by file type and then
538 for ebuilds by version and lexicographically for others.
539 EBUILD < MISC < AUX < DIST < None
541 if self.__class__ != other.__class__:
542 raise NotImplementedError
544 # Sort by file type as defined by file_type_lt().
545 if self.file_type_lt(self, other):
547 elif self.file_type_lt(other, self):
550 # Files have the same type.
551 if self.file_type == "EBUILD":
552 # Sort by version. Lowest first.
553 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
554 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
555 return vercmp(ver, other_ver) < 0
557 # Sort lexicographically.
558 return self.file_name < other.file_name
560 class GenChangeLogs(object):
561 def __init__(self, portdb):
562 self.returncode = os.EX_OK
563 self._portdb = portdb
564 self._wrapper = textwrap.TextWrapper(
566 initial_indent = ' ',
567 subsequent_indent = ' '
572 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
573 return _unicode_decode(p.communicate()[0],
574 encoding=_encodings['stdio'], errors='strict')
576 def generate_changelog(self, cp):
578 output = codecs.open('ChangeLog',
579 mode='w', encoding=_encodings['repo.content'],
583 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
584 level=logging.ERROR, noiselevel=-1)
590 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
593 ''' % (cp, time.strftime('%Y'))).lstrip())
595 # now grab all the commits
596 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
599 # Explaining the arguments:
600 # --name-status to get a list of added/removed files
601 # --no-renames to avoid getting more complex records on the list
602 # --format to get the timestamp, author and commit description
603 # --root to make it work fine even with the initial commit
604 # --relative to get paths relative to ebuilddir
605 # -r (recursive) to get per-file changes
606 # then the commit-id and path.
608 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
609 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
610 c, '--', '.']).rstrip('\n').split('\n')
613 # timestamp Author Name <author@email>
623 for n, l in enumerate(reversed(cinfo)):
629 if f[1] == 'Manifest':
630 pass # XXX: remanifest commits?
631 elif f[1] == 'ChangeLog':
633 elif f[0].startswith('A'):
634 changed.append(_special_filename("+", f[1]))
635 elif f[0].startswith('D'):
636 changed.append(_special_filename("-", f[1]))
637 elif f[0].startswith('M'):
638 changed.append(_special_filename("", f[1]))
641 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
642 level=logging.ERROR, noiselevel=-1)
648 (ts, author) = cinfo[0].split(' ', 1)
649 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
651 changed = [str(x) for x in sorted(changed)]
654 # Reverse the sort order for headers.
655 for c in reversed(changed):
656 if c.startswith('+') and c.endswith('.ebuild'):
657 output.write('*%s (%s)\n' % (c[1:-7], date))
662 # strip '<cp>: ', '[<cp>] ', and similar
663 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
664 # strip trailing newline
668 if body[-1].startswith('git-svn-id:') and not body[-2]:
670 # strip the repoman version/manifest note
671 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
673 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
678 # don't break filenames on hyphens
679 self._wrapper.break_on_hyphens = False
680 output.write(self._wrapper.fill('%s; %s %s:' % (date, author, ', '.join(changed))))
681 # but feel free to break commit messages there
682 self._wrapper.break_on_hyphens = True
683 output.write('\n%s\n\n' % '\n'.join([self._wrapper.fill(x) for x in body]))
688 repo_path = self._portdb.porttrees[0]
691 if 'git' not in FindVCS():
693 "ERROR: --update-changelogs supported only in git repos\n",
694 level=logging.ERROR, noiselevel=-1)
695 self.returncode = 127
698 for cp in self._portdb.cp_all():
699 os.chdir(os.path.join(repo_path, cp))
700 # Determine whether ChangeLog is up-to-date by comparing
701 # the newest commit timestamp with the ChangeLog timestamp.
702 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
704 # This cp has not been added to the repo.
708 cmod = os.stat('ChangeLog').st_mtime
712 if float(cmod) < float(lmod):
713 self.generate_changelog(cp)
715 def egencache_main(args):
716 parser, options, atoms = parse_args(args)
718 config_root = options.config_root
719 if config_root is None:
722 # The calling environment is ignored, so the program is
723 # completely controlled by commandline arguments.
726 if options.repo is None:
727 env['PORTDIR_OVERLAY'] = ''
729 if options.cache_dir is not None:
730 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
732 if options.portdir is not None:
733 env['PORTDIR'] = options.portdir
735 settings = portage.config(config_root=config_root,
736 target_root='/', local_config=False, env=env)
739 if not options.ignore_default_opts:
740 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
743 parser, options, args = parse_args(default_opts + args)
745 if options.config_root is not None:
746 config_root = options.config_root
748 if options.cache_dir is not None:
749 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
751 settings = portage.config(config_root=config_root,
752 target_root='/', local_config=False, env=env)
754 if not options.update and not options.update_use_local_desc \
755 and not options.update_changelogs:
756 parser.error('No action specified')
759 if options.update and 'metadata-transfer' not in settings.features:
760 writemsg_level("ecachegen: warning: " + \
761 "automatically enabling FEATURES=metadata-transfer\n",
762 level=logging.WARNING, noiselevel=-1)
763 settings.features.add('metadata-transfer')
767 portdb = portage.portdbapi(mysettings=settings)
768 if options.repo is not None:
769 repo_path = portdb.getRepositoryPath(options.repo)
770 if repo_path is None:
771 parser.error("Unable to locate repository named '%s'" % \
775 # Limit ebuilds to the specified repo.
776 portdb.porttrees = [repo_path]
783 cp_iter = iter(atoms)
785 gen_cache = GenCache(portdb, cp_iter=cp_iter,
786 max_jobs=options.jobs,
787 max_load=options.load_average,
790 ret.append(gen_cache.returncode)
792 if options.update_use_local_desc:
793 gen_desc = GenUseLocalDesc(portdb,
794 output=options.uld_output,
795 preserve_comments=options.preserve_comments)
797 ret.append(gen_desc.returncode)
799 if options.update_changelogs:
800 gen_clogs = GenChangeLogs(portdb)
802 ret.append(gen_clogs.returncode)
808 if __name__ == "__main__":
809 portage._disable_legacy_globals()
810 portage.util.noiselimit = -1
811 sys.exit(egencache_main(sys.argv[1:]))