2 # Copyright 2009-2010 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
5 from __future__ import print_function
8 # 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)
17 signal.signal(signal.SIGINT, exithandler)
18 signal.signal(signal.SIGTERM, exithandler)
20 except KeyboardInterrupt:
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 import xml.etree.ElementTree
52 from repoman.utilities import parse_metadata_use
53 from xml.parsers.expat import ExpatError
55 from repoman.utilities import FindVCS
57 if sys.hexversion >= 0x3000000:
61 usage = "egencache [options] <action> ... [atom] ..."
62 parser = optparse.OptionParser(usage=usage)
64 actions = optparse.OptionGroup(parser, 'Actions')
65 actions.add_option("--update",
67 help="update metadata/cache/ (generate as necessary)")
68 actions.add_option("--update-use-local-desc",
70 help="update the use.local.desc file from metadata.xml")
71 actions.add_option("--update-changelogs",
73 help="update the ChangeLog files from SCM logs")
74 parser.add_option_group(actions)
76 common = optparse.OptionGroup(parser, 'Common options')
77 common.add_option("--repo",
79 help="name of repo to operate on (default repo is located at $PORTDIR)")
80 common.add_option("--config-root",
81 help="location of portage config files",
82 dest="portage_configroot")
83 common.add_option("--portdir",
84 help="override the portage tree location",
86 common.add_option("--tolerant",
88 help="exit successfully if only minor errors occurred")
89 common.add_option("--ignore-default-opts",
91 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
92 parser.add_option_group(common)
94 update = optparse.OptionGroup(parser, '--update options')
95 update.add_option("--cache-dir",
96 help="location of the metadata cache",
98 update.add_option("--jobs",
100 help="max ebuild processes to spawn")
101 update.add_option("--load-average",
103 help="max load allowed when spawning multiple jobs",
105 update.add_option("--rsync",
107 help="enable rsync stat collision workaround " + \
108 "for bug 139134 (use with --update)")
109 parser.add_option_group(update)
111 uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
112 uld.add_option("--preserve-comments",
114 help="preserve the comments from the existing use.local.desc file")
115 uld.add_option("--use-local-desc-output",
116 help="output file for use.local.desc data (or '-' for stdout)",
118 parser.add_option_group(uld)
120 options, args = parser.parse_args(args)
125 jobs = int(options.jobs)
130 parser.error("Invalid: --jobs='%s'" % \
138 if options.load_average:
140 load_average = float(options.load_average)
144 if load_average <= 0.0:
145 parser.error("Invalid: --load-average='%s'" % \
146 (options.load_average,))
148 options.load_average = load_average
151 options.load_average = None
153 options.config_root = options.portage_configroot
154 if options.config_root is not None and \
155 not os.path.isdir(options.config_root):
156 parser.error("Not a directory: --config-root='%s'" % \
157 (options.config_root,))
159 if options.cache_dir is not None and not os.path.isdir(options.cache_dir):
160 parser.error("Not a directory: --cache-dir='%s'" % \
161 (options.cache_dir,))
165 atom = portage.dep.Atom(atom)
166 except portage.exception.InvalidAtom:
167 parser.error('Invalid atom: %s' % (atom,))
169 if not isjustname(atom):
170 parser.error('Atom is too specific: %s' % (atom,))
172 if options.update_use_local_desc:
174 xml.etree.ElementTree
176 parser.error('--update-use-local-desc requires python with USE=xml!')
178 if options.uld_output == '-' and options.preserve_comments:
179 parser.error('--preserve-comments can not be used when outputting to stdout')
181 return parser, options, args
183 class GenCache(object):
184 def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
186 self._portdb = portdb
187 # We can globally cleanse stale cache only if we
188 # iterate over every single cp.
189 self._global_cleanse = cp_iter is None
190 if cp_iter is not None:
191 self._cp_set = set(cp_iter)
192 cp_iter = iter(self._cp_set)
193 self._cp_missing = self._cp_set.copy()
196 self._cp_missing = set()
197 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
198 consumer=self._metadata_callback,
199 max_jobs=max_jobs, max_load=max_load)
200 self.returncode = os.EX_OK
201 metadbmodule = portdb.settings.load_best_module("portdbapi.metadbmodule")
202 self._trg_cache = metadbmodule(portdb.porttrees[0],
203 "metadata/cache", portage.auxdbkeys[:])
205 self._trg_cache.raise_stat_collision = True
207 self._trg_cache.ec = \
208 portdb._repo_info[portdb.porttrees[0]].eclass_db
209 except AttributeError:
211 self._existing_nodes = set()
213 def _metadata_callback(self, cpv, ebuild_path, repo_path, metadata):
214 self._existing_nodes.add(cpv)
215 self._cp_missing.discard(cpv_getkey(cpv))
216 if metadata is not None:
217 if metadata.get('EAPI') == '0':
221 self._trg_cache[cpv] = metadata
222 except StatCollision as sc:
223 # If the content of a cache entry changes and neither the
224 # file mtime nor size changes, it will prevent rsync from
225 # detecting changes. Cache backends may raise this
226 # exception from _setitem() if they detect this type of stat
227 # collision. These exceptions are handled by bumping the
228 # mtime on the ebuild (and the corresponding cache entry).
231 for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
232 if max_mtime < ec_mtime:
234 if max_mtime == sc.mtime:
236 max_mtime = long(max_mtime)
238 os.utime(ebuild_path, (max_mtime, max_mtime))
242 "%s writing target: %s\n" % (cpv, e),
243 level=logging.ERROR, noiselevel=-1)
245 metadata['_mtime_'] = max_mtime
246 self._trg_cache[cpv] = metadata
247 self._portdb.auxdb[repo_path][cpv] = metadata
249 except CacheError as ce:
252 "%s writing target: %s\n" % (cpv, ce),
253 level=logging.ERROR, noiselevel=-1)
257 self.returncode |= self._regen.returncode
258 cp_missing = self._cp_missing
260 trg_cache = self._trg_cache
262 if self._global_cleanse:
264 for cpv in trg_cache:
269 "Unable to parse cp for '%s'\n" % (cpv,),
270 level=logging.ERROR, noiselevel=-1)
273 except CacheError as ce:
276 "Error listing cache entries for " + \
277 "'%s/metadata/cache': %s, continuing...\n" % \
278 (self._portdb.porttree_root, ce),
279 level=logging.ERROR, noiselevel=-1)
282 cp_set = self._cp_set
284 for cpv in trg_cache:
289 "Unable to parse cp for '%s'\n" % (cpv,),
290 level=logging.ERROR, noiselevel=-1)
292 cp_missing.discard(cp)
295 except CacheError as ce:
298 "Error listing cache entries for " + \
299 "'%s/metadata/cache': %s, continuing...\n" % \
300 (self._portdb.porttree_root, ce),
301 level=logging.ERROR, noiselevel=-1)
305 for cp in sorted(cp_missing):
307 "No ebuilds or cache entries found for '%s'\n" % (cp,),
308 level=logging.ERROR, noiselevel=-1)
311 dead_nodes.difference_update(self._existing_nodes)
317 except CacheError as ce:
320 "%s deleting stale cache: %s\n" % (k, ce),
321 level=logging.ERROR, noiselevel=-1)
323 if not trg_cache.autocommits:
326 except CacheError as ce:
329 "committing target: %s\n" % (ce,),
330 level=logging.ERROR, noiselevel=-1)
332 class GenUseLocalDesc(object):
333 def __init__(self, portdb, output=None,
334 preserve_comments=False):
335 self.returncode = os.EX_OK
336 self._portdb = portdb
337 self._output = output
338 self._preserve_comments = preserve_comments
341 repo_path = self._portdb.porttrees[0]
342 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
344 if self._output is None or self._output != '-':
345 if self._output is None:
346 prof_path = os.path.join(repo_path, 'profiles')
347 desc_path = os.path.join(prof_path, 'use.local.desc')
353 desc_path = self._output
356 if self._preserve_comments:
357 # Probe in binary mode, in order to avoid
358 # potential character encoding issues.
359 output = open(_unicode_encode(desc_path,
360 encoding=_encodings['fs'], errors='strict'), 'r+b')
362 output = codecs.open(_unicode_encode(desc_path,
363 encoding=_encodings['fs'], errors='strict'),
364 mode='w', encoding=_encodings['repo.content'],
368 "ERROR: failed to open output file %s: %s\n" % (desc_path,e,),
369 level=logging.ERROR, noiselevel=-1)
375 if self._preserve_comments:
378 if not output.readline().startswith(b'#'):
384 # Finished probing comments in binary mode, now append
386 output = codecs.open(_unicode_encode(desc_path,
387 encoding=_encodings['fs'], errors='strict'),
388 mode='a', encoding=_encodings['repo.content'],
393 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
394 # your descriptions to your package's metadata.xml ONLY.
395 # * generated automatically using egencache *
399 # The cmp function no longer exists in python3, so we'll
400 # implement our own here under a slightly different name
401 # since we don't want any confusion given that we never
402 # want to rely on the builtin cmp function.
404 return (a > b) - (a < b)
406 for cp in self._portdb.cp_all():
407 metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
409 metadata = xml.etree.ElementTree.parse(metadata_path)
412 except (ExpatError, EnvironmentError) as e:
414 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
415 level=logging.ERROR, noiselevel=-1)
419 usedict = parse_metadata_use(metadata)
420 except portage.exception.ParseError as e:
422 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
423 level=logging.ERROR, noiselevel=-1)
426 for flag in sorted(usedict):
427 def atomcmp(atoma, atomb):
428 # None is better than an atom, that's why we reverse the args
429 if atoma is None or atomb is None:
430 return cmp_func(atomb, atoma)
431 # Same for plain PNs (.operator is None then)
432 elif atoma.operator is None or atomb.operator is None:
433 return cmp_func(atomb.operator, atoma.operator)
435 elif atoma.cpv != atomb.cpv:
436 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
437 # Versions match, let's fallback to operator matching
439 return cmp_func(ops.get(atoma.operator, -1),
440 ops.get(atomb.operator, -1))
447 resdict = usedict[flag]
448 if len(resdict) == 1:
449 resdesc = next(iter(resdict.items()))[1]
452 reskeys = dict((_Atom(k), k) for k in resdict)
453 except portage.exception.InvalidAtom as e:
455 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
456 level=logging.ERROR, noiselevel=-1)
458 resdesc = next(iter(resdict.items()))[1]
460 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
461 resdesc = resdict[reskeys[resatoms[-1]]]
463 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
467 if sys.hexversion < 0x3000000:
468 _filename_base = unicode
472 class _special_filename(_filename_base):
474 Helps to sort file names by file type and other criteria.
476 def __new__(cls, status_change, file_name):
477 return _filename_base.__new__(cls, status_change + file_name)
479 def __init__(self, status_change, file_name):
480 _filename_base.__init__(status_change + file_name)
481 self.status_change = status_change
482 self.file_name = file_name
483 self.file_type = guessManifestFileType(file_name)
485 def file_type_lt(self, a, b):
487 Defines an ordering between file types.
494 if first == "EBUILD":
496 elif first == "MISC":
497 return second in ("EBUILD",)
499 return second in ("EBUILD", "MISC")
500 elif first == "DIST":
501 return second in ("EBUILD", "MISC", "AUX")
505 raise ValueError("Unknown file type '%s'" % first)
507 def __lt__(self, other):
509 Compare different file names, first by file type and then
510 for ebuilds by version and lexicographically for others.
511 EBUILD < MISC < AUX < DIST < None
513 if self.__class__ != other.__class__:
514 raise NotImplementedError
516 # Sort by file type as defined by file_type_lt().
517 if self.file_type_lt(self, other):
519 elif self.file_type_lt(other, self):
522 # Files have the same type.
523 if self.file_type == "EBUILD":
524 # Sort by version. Lowest first.
525 ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
526 other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
527 return vercmp(ver, other_ver) < 0
529 # Sort lexicographically.
530 return self.file_name < other.file_name
532 class GenChangeLogs(object):
533 def __init__(self, portdb):
534 self.returncode = os.EX_OK
535 self._portdb = portdb
536 self._wrapper = textwrap.TextWrapper(
538 initial_indent = ' ',
539 subsequent_indent = ' '
544 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
545 return _unicode_decode(p.communicate()[0],
546 encoding=_encodings['stdio'], errors='strict')
548 def generate_changelog(self, cp):
550 output = codecs.open('ChangeLog',
551 mode='w', encoding=_encodings['repo.content'],
555 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
556 level=logging.ERROR, noiselevel=-1)
562 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
565 ''' % (cp, time.strftime('%Y'))).lstrip())
567 # now grab all the commits
568 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
571 # Explaining the arguments:
572 # --name-status to get a list of added/removed files
573 # --no-renames to avoid getting more complex records on the list
574 # --format to get the timestamp, author and commit description
575 # --root to make it work fine even with the initial commit
576 # --relative to get paths relative to ebuilddir
577 # -r (recursive) to get per-file changes
578 # then the commit-id and path.
580 cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
581 '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
582 c, '--', '.']).rstrip('\n').split('\n')
585 # timestamp Author Name <author@email>
595 for n, l in enumerate(reversed(cinfo)):
601 if f[1] == 'Manifest':
602 pass # XXX: remanifest commits?
603 elif f[1] == 'ChangeLog':
605 elif f[0].startswith('A'):
606 changed.append(_special_filename("+", f[1]))
607 elif f[0].startswith('D'):
608 changed.append(_special_filename("-", f[1]))
609 elif f[0].startswith('M'):
610 changed.append(_special_filename("", f[1]))
613 "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
614 level=logging.ERROR, noiselevel=-1)
620 (ts, author) = cinfo[0].split(' ', 1)
621 date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
623 changed = [str(x) for x in sorted(changed)]
626 # Reverse the sort order for headers.
627 for c in reversed(changed):
628 if c.startswith('+') and c.endswith('.ebuild'):
629 output.write('*%s (%s)\n' % (c[1:-7], date))
634 # strip '<cp>: ', '[<cp>] ', and similar
635 body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
636 # strip trailing newline
640 if body[-1].startswith('git-svn-id:') and not body[-2]:
642 # strip the repoman version/manifest note
643 if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
645 if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
650 # don't break filenames on hyphens
651 self._wrapper.break_on_hyphens = False
652 output.write(self._wrapper.fill('%s; %s %s:' % (date, author, ', '.join(changed))))
653 # but feel free to break commit messages there
654 self._wrapper.break_on_hyphens = True
655 output.write('\n%s\n\n' % '\n'.join([self._wrapper.fill(x) for x in body]))
660 repo_path = self._portdb.porttrees[0]
663 if 'git' not in FindVCS():
665 "ERROR: --update-changelogs supported only in git repos\n",
666 level=logging.ERROR, noiselevel=-1)
667 self.returncode = 127
670 for cp in self._portdb.cp_all():
671 os.chdir(os.path.join(repo_path, cp))
672 # Determine whether ChangeLog is up-to-date by comparing
673 # the newest commit timestamp with the ChangeLog timestamp.
674 lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
676 # This cp has not been added to the repo.
680 cmod = os.stat('ChangeLog').st_mtime
684 if float(cmod) < float(lmod):
685 self.generate_changelog(cp)
687 def egencache_main(args):
688 parser, options, atoms = parse_args(args)
690 config_root = options.config_root
691 if config_root is None:
694 # The calling environment is ignored, so the program is
695 # completely controlled by commandline arguments.
698 if options.repo is None:
699 env['PORTDIR_OVERLAY'] = ''
701 if options.cache_dir is not None:
702 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
704 if options.portdir is not None:
705 env['PORTDIR'] = options.portdir
707 settings = portage.config(config_root=config_root,
708 target_root='/', local_config=False, env=env)
711 if not options.ignore_default_opts:
712 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
715 parser, options, args = parse_args(default_opts + args)
717 if options.config_root is not None:
718 config_root = options.config_root
720 if options.cache_dir is not None:
721 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
723 settings = portage.config(config_root=config_root,
724 target_root='/', local_config=False, env=env)
726 if not options.update and not options.update_use_local_desc \
727 and not options.update_changelogs:
728 parser.error('No action specified')
731 if options.update and 'metadata-transfer' not in settings.features:
732 writemsg_level("ecachegen: warning: " + \
733 "automatically enabling FEATURES=metadata-transfer\n",
734 level=logging.WARNING, noiselevel=-1)
735 settings.features.add('metadata-transfer')
739 portdb = portage.portdbapi(mysettings=settings)
740 if options.repo is not None:
741 repo_path = portdb.getRepositoryPath(options.repo)
742 if repo_path is None:
743 parser.error("Unable to locate repository named '%s'" % \
747 # Limit ebuilds to the specified repo.
748 portdb.porttrees = [repo_path]
755 cp_iter = iter(atoms)
757 gen_cache = GenCache(portdb, cp_iter=cp_iter,
758 max_jobs=options.jobs,
759 max_load=options.load_average,
762 ret.append(gen_cache.returncode)
764 if options.update_use_local_desc:
765 gen_desc = GenUseLocalDesc(portdb,
766 output=options.uld_output,
767 preserve_comments=options.preserve_comments)
769 ret.append(gen_desc.returncode)
771 if options.update_changelogs:
772 gen_clogs = GenChangeLogs(portdb)
774 ret.append(gen_clogs.returncode)
780 if __name__ == "__main__":
781 portage._disable_legacy_globals()
782 portage.util.noiselimit = -1
783 sys.exit(egencache_main(sys.argv[1:]))