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)
276 # Restore previous handlers
277 if earlier_sigint_handler is not None:
278 signal.signal(signal.SIGINT, earlier_sigint_handler)
280 signal.signal(signal.SIGINT, signal.SIG_DFL)
281 if earlier_sigterm_handler is not None:
282 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
284 signal.signal(signal.SIGTERM, signal.SIG_DFL)
287 sys.exit(received_signal[0])
289 self.returncode |= self._regen.returncode
290 cp_missing = self._cp_missing
292 trg_cache = self._trg_cache
294 if self._global_cleanse:
296 for cpv in trg_cache:
301 "Unable to parse cp for '%s'\n" % (cpv,),
302 level=logging.ERROR, noiselevel=-1)
305 except CacheError as ce:
308 "Error listing cache entries for " + \
309 "'%s/metadata/cache': %s, continuing...\n" % \
310 (self._portdb.porttree_root, ce),
311 level=logging.ERROR, noiselevel=-1)
314 cp_set = self._cp_set
316 for cpv in trg_cache:
321 "Unable to parse cp for '%s'\n" % (cpv,),
322 level=logging.ERROR, noiselevel=-1)
324 cp_missing.discard(cp)
327 except CacheError as ce:
330 "Error listing cache entries for " + \
331 "'%s/metadata/cache': %s, continuing...\n" % \
332 (self._portdb.porttree_root, ce),
333 level=logging.ERROR, noiselevel=-1)
337 for cp in sorted(cp_missing):
339 "No ebuilds or cache entries found for '%s'\n" % (cp,),
340 level=logging.ERROR, noiselevel=-1)
343 dead_nodes.difference_update(self._existing_nodes)
349 except CacheError as ce:
352 "%s deleting stale cache: %s\n" % (k, ce),
353 level=logging.ERROR, noiselevel=-1)
355 if not trg_cache.autocommits:
358 except CacheError as ce:
361 "committing target: %s\n" % (ce,),
362 level=logging.ERROR, noiselevel=-1)
364 class GenUseLocalDesc(object):
365 def __init__(self, portdb, output=None,
366 preserve_comments=False):
367 self.returncode = os.EX_OK
368 self._portdb = portdb
369 self._output = output
370 self._preserve_comments = preserve_comments
373 repo_path = self._portdb.porttrees[0]
374 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
376 if self._output is None or self._output != '-':
377 if self._output is None:
378 prof_path = os.path.join(repo_path, 'profiles')
379 desc_path = os.path.join(prof_path, 'use.local.desc')
385 desc_path = self._output
388 if self._preserve_comments:
389 # Probe in binary mode, in order to avoid
390 # potential character encoding issues.
391 output = open(_unicode_encode(desc_path,
392 encoding=_encodings['fs'], errors='strict'), 'r+b')
394 output = codecs.open(_unicode_encode(desc_path,
395 encoding=_encodings['fs'], errors='strict'),
396 mode='w', encoding=_encodings['repo.content'],
400 "ERROR: failed to open output file %s: %s\n" % (desc_path,e,),
401 level=logging.ERROR, noiselevel=-1)
407 if self._preserve_comments:
410 if not output.readline().startswith(b'#'):
416 # Finished probing comments in binary mode, now append
418 output = codecs.open(_unicode_encode(desc_path,
419 encoding=_encodings['fs'], errors='strict'),
420 mode='a', encoding=_encodings['repo.content'],
425 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
426 # your descriptions to your package's metadata.xml ONLY.
427 # * generated automatically using egencache *
431 # The cmp function no longer exists in python3, so we'll
432 # implement our own here under a slightly different name
433 # since we don't want any confusion given that we never
434 # want to rely on the builtin cmp function.
436 return (a > b) - (a < b)
438 for cp in self._portdb.cp_all():
439 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
441 metadata = ElementTree.parse(metadata_path)
444 except (ExpatError, EnvironmentError) as e:
446 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
447 level=logging.ERROR, noiselevel=-1)
451 usedict = parse_metadata_use(metadata)
452 except portage.exception.ParseError as e:
454 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
455 level=logging.ERROR, noiselevel=-1)
458 for flag in sorted(usedict):
459 def atomcmp(atoma, atomb):
460 # None is better than an atom, that's why we reverse the args
461 if atoma is None or atomb is None:
462 return cmp_func(atomb, atoma)
463 # Same for plain PNs (.operator is None then)
464 elif atoma.operator is None or atomb.operator is None:
465 return cmp_func(atomb.operator, atoma.operator)
467 elif atoma.cpv != atomb.cpv:
468 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
469 # Versions match, let's fallback to operator matching
471 return cmp_func(ops.get(atoma.operator, -1),
472 ops.get(atomb.operator, -1))
479 resdict = usedict[flag]
480 if len(resdict) == 1:
481 resdesc = next(iter(resdict.items()))[1]
484 reskeys = dict((_Atom(k), k) for k in resdict)
485 except portage.exception.InvalidAtom as e:
487 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
488 level=logging.ERROR, noiselevel=-1)
490 resdesc = next(iter(resdict.items()))[1]
492 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
493 resdesc = resdict[reskeys[resatoms[-1]]]
495 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
499 if sys.hexversion < 0x3000000:
500 _filename_base = unicode
504 class _special_filename(_filename_base):
506 Helps to sort file names by file type and other criteria.
508 def __new__(cls, status_change, file_name):
509 return _filename_base.__new__(cls, status_change + file_name)
511 def __init__(self, status_change, file_name):
512 _filename_base.__init__(status_change + file_name)
513 self.status_change = status_change
514 self.file_name = file_name
515 self.file_type = guessManifestFileType(file_name)
517 def file_type_lt(self, a, b):
519 Defines an ordering between file types.
526 if first == "EBUILD":
528 elif first == "MISC":
529 return second in ("EBUILD",)
531 return second in ("EBUILD", "MISC")
532 elif first == "DIST":
533 return second in ("EBUILD", "MISC", "AUX")
537 raise ValueError("Unknown file type '%s'" % first)
539 def __lt__(self, other):
541 Compare different file names, first by file type and then
542 for ebuilds by version and lexicographically for others.
543 EBUILD < MISC < AUX < DIST < None
545 if self.__class__ != other.__class__:
546 raise NotImplementedError
548 # Sort by file type as defined by file_type_lt().
549 if self.file_type_lt(self, other):
551 elif self.file_type_lt(other, self):
554 # Files have the same type.
555 if self.file_type == "EBUILD":
556 # Sort by version. Lowest first.
557 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
558 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
559 return vercmp(ver, other_ver) < 0
561 # Sort lexicographically.
562 return self.file_name < other.file_name
564 class GenChangeLogs(object):
565 def __init__(self, portdb):
566 self.returncode = os.EX_OK
567 self._portdb = portdb
568 self._wrapper = textwrap.TextWrapper(
570 initial_indent = ' ',
571 subsequent_indent = ' '
576 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
577 return _unicode_decode(p.communicate()[0],
578 encoding=_encodings['stdio'], errors='strict')
580 def generate_changelog(self, cp):
582 output = codecs.open('ChangeLog',
583 mode='w', encoding=_encodings['repo.content'],
587 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
588 level=logging.ERROR, noiselevel=-1)
594 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
597 ''' % (cp, time.strftime('%Y'))).lstrip())
599 # now grab all the commits
600 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
603 # Explaining the arguments:
604 # --name-status to get a list of added/removed files
605 # --no-renames to avoid getting more complex records on the list
606 # --format to get the timestamp, author and commit description
607 # --root to make it work fine even with the initial commit
608 # --relative to get paths relative to ebuilddir
609 # -r (recursive) to get per-file changes
610 # then the commit-id and path.
612 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
613 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
614 c, '--', '.']).rstrip('\n').split('\n')
617 # timestamp Author Name <author@email>
627 for n, l in enumerate(reversed(cinfo)):
633 if f[1] == 'Manifest':
634 pass # XXX: remanifest commits?
635 elif f[1] == 'ChangeLog':
637 elif f[0].startswith('A'):
638 changed.append(_special_filename("+", f[1]))
639 elif f[0].startswith('D'):
640 changed.append(_special_filename("-", f[1]))
641 elif f[0].startswith('M'):
642 changed.append(_special_filename("", f[1]))
645 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
646 level=logging.ERROR, noiselevel=-1)
652 (ts, author) = cinfo[0].split(' ', 1)
653 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
655 changed = [str(x) for x in sorted(changed)]
658 # Reverse the sort order for headers.
659 for c in reversed(changed):
660 if c.startswith('+') and c.endswith('.ebuild'):
661 output.write('*%s (%s)\n' % (c[1:-7], date))
666 # strip '<cp>: ', '[<cp>] ', and similar
667 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
668 # strip trailing newline
672 if body[-1].startswith('git-svn-id:') and not body[-2]:
674 # strip the repoman version/manifest note
675 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
677 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
682 # don't break filenames on hyphens
683 self._wrapper.break_on_hyphens = False
684 output.write(self._wrapper.fill('%s; %s %s:' % (date, author, ', '.join(changed))))
685 # but feel free to break commit messages there
686 self._wrapper.break_on_hyphens = True
687 output.write('\n%s\n\n' % '\n'.join([self._wrapper.fill(x) for x in body]))
692 repo_path = self._portdb.porttrees[0]
695 if 'git' not in FindVCS():
697 "ERROR: --update-changelogs supported only in git repos\n",
698 level=logging.ERROR, noiselevel=-1)
699 self.returncode = 127
702 for cp in self._portdb.cp_all():
703 os.chdir(os.path.join(repo_path, cp))
704 # Determine whether ChangeLog is up-to-date by comparing
705 # the newest commit timestamp with the ChangeLog timestamp.
706 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
708 # This cp has not been added to the repo.
712 cmod = os.stat('ChangeLog').st_mtime
716 if float(cmod) < float(lmod):
717 self.generate_changelog(cp)
719 def egencache_main(args):
720 parser, options, atoms = parse_args(args)
722 config_root = options.config_root
723 if config_root is None:
726 # The calling environment is ignored, so the program is
727 # completely controlled by commandline arguments.
730 if options.repo is None:
731 env['PORTDIR_OVERLAY'] = ''
733 if options.cache_dir is not None:
734 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
736 if options.portdir is not None:
737 env['PORTDIR'] = options.portdir
739 settings = portage.config(config_root=config_root,
740 target_root='/', local_config=False, env=env)
743 if not options.ignore_default_opts:
744 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
747 parser, options, args = parse_args(default_opts + args)
749 if options.config_root is not None:
750 config_root = options.config_root
752 if options.cache_dir is not None:
753 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
755 settings = portage.config(config_root=config_root,
756 target_root='/', local_config=False, env=env)
758 if not options.update and not options.update_use_local_desc \
759 and not options.update_changelogs:
760 parser.error('No action specified')
763 if options.update and 'metadata-transfer' not in settings.features:
764 writemsg_level("ecachegen: warning: " + \
765 "automatically enabling FEATURES=metadata-transfer\n",
766 level=logging.WARNING, noiselevel=-1)
767 settings.features.add('metadata-transfer')
771 portdb = portage.portdbapi(mysettings=settings)
772 if options.repo is not None:
773 repo_path = portdb.getRepositoryPath(options.repo)
774 if repo_path is None:
775 parser.error("Unable to locate repository named '%s'" % \
779 # Limit ebuilds to the specified repo.
780 portdb.porttrees = [repo_path]
787 cp_iter = iter(atoms)
789 gen_cache = GenCache(portdb, cp_iter=cp_iter,
790 max_jobs=options.jobs,
791 max_load=options.load_average,
794 ret.append(gen_cache.returncode)
796 if options.update_use_local_desc:
797 gen_desc = GenUseLocalDesc(portdb,
798 output=options.uld_output,
799 preserve_comments=options.preserve_comments)
801 ret.append(gen_desc.returncode)
803 if options.update_changelogs:
804 gen_clogs = GenChangeLogs(portdb)
806 ret.append(gen_clogs.returncode)
812 if __name__ == "__main__":
813 portage._disable_legacy_globals()
814 portage.util.noiselimit = -1
815 sys.exit(egencache_main(sys.argv[1:]))