Tweak PollScheduler signal handling.
[portage.git] / bin / egencache
1 #!/usr/bin/python
2 # Copyright 2009-2011 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
4
5 from __future__ import print_function
6
7 import signal
8 import sys
9 # This block ensures that ^C interrupts are handled quietly.
10 try:
11
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)
16
17         signal.signal(signal.SIGINT, exithandler)
18         signal.signal(signal.SIGTERM, exithandler)
19
20 except KeyboardInterrupt:
21         sys.exit(128 + signal.SIGINT)
22
23 import codecs
24 import logging
25 import optparse
26 import subprocess
27 import time
28 import textwrap
29 import re
30
31 try:
32         import portage
33 except ImportError:
34         from os import path as osp
35         sys.path.insert(0, osp.join(osp.dirname(osp.dirname(osp.realpath(__file__))), "pym"))
36         import portage
37
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
46
47 try:
48         from xml.etree import ElementTree
49 except ImportError:
50         pass
51 else:
52         try:
53                 from xml.parsers.expat import ExpatError
54         except ImportError:
55                 pass
56         else:
57                 from repoman.utilities import parse_metadata_use
58
59 from repoman.utilities import FindVCS
60
61 if sys.hexversion >= 0x3000000:
62         long = int
63
64 def parse_args(args):
65         usage = "egencache [options] <action> ... [atom] ..."
66         parser = optparse.OptionParser(usage=usage)
67
68         actions = optparse.OptionGroup(parser, 'Actions')
69         actions.add_option("--update",
70                 action="store_true",
71                 help="update metadata/cache/ (generate as necessary)")
72         actions.add_option("--update-use-local-desc",
73                 action="store_true",
74                 help="update the use.local.desc file from metadata.xml")
75         actions.add_option("--update-changelogs",
76                 action="store_true",
77                 help="update the ChangeLog files from SCM logs")
78         parser.add_option_group(actions)
79
80         common = optparse.OptionGroup(parser, 'Common options')
81         common.add_option("--repo",
82                 action="store",
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",
89                 dest="portdir")
90         common.add_option("--tolerant",
91                 action="store_true",
92                 help="exit successfully if only minor errors occurred")
93         common.add_option("--ignore-default-opts",
94                 action="store_true",
95                 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
96         parser.add_option_group(common)
97
98         update = optparse.OptionGroup(parser, '--update options')
99         update.add_option("--cache-dir",
100                 help="location of the metadata cache",
101                 dest="cache_dir")
102         update.add_option("--jobs",
103                 action="store",
104                 help="max ebuild processes to spawn")
105         update.add_option("--load-average",
106                 action="store",
107                 help="max load allowed when spawning multiple jobs",
108                 dest="load_average")
109         update.add_option("--rsync",
110                 action="store_true",
111                 help="enable rsync stat collision workaround " + \
112                         "for bug 139134 (use with --update)")
113         parser.add_option_group(update)
114
115         uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
116         uld.add_option("--preserve-comments",
117                 action="store_true",
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)",
121                 dest="uld_output")
122         parser.add_option_group(uld)
123
124         options, args = parser.parse_args(args)
125
126         if options.jobs:
127                 jobs = None
128                 try:
129                         jobs = int(options.jobs)
130                 except ValueError:
131                         jobs = -1
132
133                 if jobs < 1:
134                         parser.error("Invalid: --jobs='%s'" % \
135                                 (options.jobs,))
136
137                 options.jobs = jobs
138
139         else:
140                 options.jobs = None
141
142         if options.load_average:
143                 try:
144                         load_average = float(options.load_average)
145                 except ValueError:
146                         load_average = 0.0
147
148                 if load_average <= 0.0:
149                         parser.error("Invalid: --load-average='%s'" % \
150                                 (options.load_average,))
151
152                 options.load_average = load_average
153
154         else:
155                 options.load_average = None
156
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,))
162
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,))
166
167         for atom in args:
168                 try:
169                         atom = portage.dep.Atom(atom)
170                 except portage.exception.InvalidAtom:
171                         parser.error('Invalid atom: %s' % (atom,))
172
173                 if not isjustname(atom):
174                         parser.error('Atom is too specific: %s' % (atom,))
175
176         if options.update_use_local_desc:
177                 try:
178                         ElementTree
179                         ExpatError
180                 except NameError:
181                         parser.error('--update-use-local-desc requires python with USE=xml!')
182
183         if options.uld_output == '-' and options.preserve_comments:
184                 parser.error('--preserve-comments can not be used when outputting to stdout')
185
186         return parser, options, args
187
188 class GenCache(object):
189         def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
190                 rsync=False):
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()
199                 else:
200                         self._cp_set = None
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[:])
209                 if rsync:
210                         self._trg_cache.raise_stat_collision = True
211                 try:
212                         self._trg_cache.ec = \
213                                 portdb._repo_info[portdb.porttrees[0]].eclass_db
214                 except AttributeError:
215                         pass
216                 self._existing_nodes = set()
217
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':
223                                 del metadata['EAPI']
224                         try:
225                                 try:
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).
234                                         # See bug #139134.
235                                         max_mtime = sc.mtime
236                                         for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
237                                                 if max_mtime < ec_mtime:
238                                                         max_mtime = ec_mtime
239                                         if max_mtime == sc.mtime:
240                                                 max_mtime += 1
241                                         max_mtime = long(max_mtime)
242                                         try:
243                                                 os.utime(ebuild_path, (max_mtime, max_mtime))
244                                         except OSError as e:
245                                                 self.returncode |= 1
246                                                 writemsg_level(
247                                                         "%s writing target: %s\n" % (cpv, e),
248                                                         level=logging.ERROR, noiselevel=-1)
249                                         else:
250                                                 metadata['_mtime_'] = max_mtime
251                                                 self._trg_cache[cpv] = metadata
252                                                 self._portdb.auxdb[repo_path][cpv] = metadata
253
254                         except CacheError as ce:
255                                 self.returncode |= 1
256                                 writemsg_level(
257                                         "%s writing target: %s\n" % (cpv, ce),
258                                         level=logging.ERROR, noiselevel=-1)
259
260         def run(self):
261
262                 received_signal = []
263
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)
269
270                 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
271                 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
272
273                 try:
274                         self._regen.run()
275                 finally:
276                         # Restore previous handlers
277                         if earlier_sigint_handler is not None:
278                                 signal.signal(signal.SIGINT, earlier_sigint_handler)
279                         else:
280                                 signal.signal(signal.SIGINT, signal.SIG_DFL)
281                         if earlier_sigterm_handler is not None:
282                                 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
283                         else:
284                                 signal.signal(signal.SIGTERM, signal.SIG_DFL)
285
286                 if received_signal:
287                         sys.exit(received_signal[0])
288
289                 self.returncode |= self._regen.returncode
290                 cp_missing = self._cp_missing
291
292                 trg_cache = self._trg_cache
293                 dead_nodes = set()
294                 if self._global_cleanse:
295                         try:
296                                 for cpv in trg_cache:
297                                         cp = cpv_getkey(cpv)
298                                         if cp is None:
299                                                 self.returncode |= 1
300                                                 writemsg_level(
301                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
302                                                         level=logging.ERROR, noiselevel=-1)
303                                         else:
304                                                 dead_nodes.add(cpv)
305                         except CacheError as ce:
306                                 self.returncode |= 1
307                                 writemsg_level(
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)
312
313                 else:
314                         cp_set = self._cp_set
315                         try:
316                                 for cpv in trg_cache:
317                                         cp = cpv_getkey(cpv)
318                                         if cp is None:
319                                                 self.returncode |= 1
320                                                 writemsg_level(
321                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
322                                                         level=logging.ERROR, noiselevel=-1)
323                                         else:
324                                                 cp_missing.discard(cp)
325                                                 if cp in cp_set:
326                                                         dead_nodes.add(cpv)
327                         except CacheError as ce:
328                                 self.returncode |= 1
329                                 writemsg_level(
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)
334
335                 if cp_missing:
336                         self.returncode |= 1
337                         for cp in sorted(cp_missing):
338                                 writemsg_level(
339                                         "No ebuilds or cache entries found for '%s'\n"  % (cp,),
340                                         level=logging.ERROR, noiselevel=-1)
341
342                 if dead_nodes:
343                         dead_nodes.difference_update(self._existing_nodes)
344                         for k in dead_nodes:
345                                 try:
346                                         del trg_cache[k]
347                                 except KeyError:
348                                         pass
349                                 except CacheError as ce:
350                                         self.returncode |= 1
351                                         writemsg_level(
352                                                 "%s deleting stale cache: %s\n" % (k, ce),
353                                                 level=logging.ERROR, noiselevel=-1)
354
355                 if not trg_cache.autocommits:
356                         try:
357                                 trg_cache.commit()
358                         except CacheError as ce:
359                                 self.returncode |= 1
360                                 writemsg_level(
361                                         "committing target: %s\n" % (ce,),
362                                         level=logging.ERROR, noiselevel=-1)
363
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
371         
372         def run(self):
373                 repo_path = self._portdb.porttrees[0]
374                 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
375
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')
380                                 try:
381                                         os.mkdir(prof_path)
382                                 except OSError:
383                                         pass
384                         else:
385                                 desc_path = self._output
386
387                         try:
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')
393                                 else:
394                                         output = codecs.open(_unicode_encode(desc_path,
395                                                 encoding=_encodings['fs'], errors='strict'),
396                                                 mode='w', encoding=_encodings['repo.content'],
397                                                 errors='replace')
398                         except IOError as e:
399                                 writemsg_level(
400                                         "ERROR: failed to open output file %s: %s\n" % (desc_path,e,),
401                                         level=logging.ERROR, noiselevel=-1)
402                                 self.returncode |= 2
403                                 return
404                 else:
405                         output = sys.stdout
406
407                 if self._preserve_comments:
408                         while True:
409                                 pos = output.tell()
410                                 if not output.readline().startswith(b'#'):
411                                         break
412                         output.seek(pos)
413                         output.truncate()
414                         output.close()
415
416                         # Finished probing comments in binary mode, now append
417                         # in text mode.
418                         output = codecs.open(_unicode_encode(desc_path,
419                                 encoding=_encodings['fs'], errors='strict'),
420                                 mode='a', encoding=_encodings['repo.content'],
421                                 errors='replace')
422                         output.write('\n')
423                 else:
424                         output.write('''
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 *
428
429 '''.lstrip())
430
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.
435                 def cmp_func(a, b):
436                         return (a > b) - (a < b)
437
438                 for cp in self._portdb.cp_all():
439                         metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
440                         try:
441                                 metadata = ElementTree.parse(metadata_path)
442                         except IOError:
443                                 pass
444                         except (ExpatError, EnvironmentError) as e:
445                                 writemsg_level(
446                                         "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
447                                         level=logging.ERROR, noiselevel=-1)
448                                 self.returncode |= 1
449                         else:
450                                 try:
451                                         usedict = parse_metadata_use(metadata)
452                                 except portage.exception.ParseError as e:
453                                         writemsg_level(
454                                                 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
455                                                 level=logging.ERROR, noiselevel=-1)
456                                         self.returncode |= 1
457                                 else:
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)
466                                                         # Version matching
467                                                         elif atoma.cpv != atomb.cpv:
468                                                                 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
469                                                         # Versions match, let's fallback to operator matching
470                                                         else:
471                                                                 return cmp_func(ops.get(atoma.operator, -1),
472                                                                         ops.get(atomb.operator, -1))
473
474                                                 def _Atom(key):
475                                                         if key is not None:
476                                                                 return Atom(key)
477                                                         return None
478
479                                                 resdict = usedict[flag]
480                                                 if len(resdict) == 1:
481                                                         resdesc = next(iter(resdict.items()))[1]
482                                                 else:
483                                                         try:
484                                                                 reskeys = dict((_Atom(k), k) for k in resdict)
485                                                         except portage.exception.InvalidAtom as e:
486                                                                 writemsg_level(
487                                                                         "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
488                                                                         level=logging.ERROR, noiselevel=-1)
489                                                                 self.returncode |= 1
490                                                                 resdesc = next(iter(resdict.items()))[1]
491                                                         else:
492                                                                 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
493                                                                 resdesc = resdict[reskeys[resatoms[-1]]]
494
495                                                 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
496
497                 output.close()
498
499 if sys.hexversion < 0x3000000:
500         _filename_base = unicode
501 else:
502         _filename_base = str
503
504 class _special_filename(_filename_base):
505         """
506         Helps to sort file names by file type and other criteria.
507         """
508         def __new__(cls, status_change, file_name):
509                 return _filename_base.__new__(cls, status_change + file_name)
510
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)
516
517         def file_type_lt(self, a, b):
518                 """
519                 Defines an ordering between file types.
520                 """
521                 first = a.file_type
522                 second = b.file_type
523                 if first == second:
524                         return False
525
526                 if first == "EBUILD":
527                         return True
528                 elif first == "MISC":
529                         return second in ("EBUILD",)
530                 elif first == "AUX":
531                         return second in ("EBUILD", "MISC")
532                 elif first == "DIST":
533                         return second in ("EBUILD", "MISC", "AUX")
534                 elif first is None:
535                         return False
536                 else:
537                         raise ValueError("Unknown file type '%s'" % first)
538
539         def __lt__(self, other):
540                 """
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
544                 """
545                 if self.__class__ != other.__class__:
546                         raise NotImplementedError
547
548                 # Sort by file type as defined by file_type_lt().
549                 if self.file_type_lt(self, other):
550                         return True
551                 elif self.file_type_lt(other, self):
552                         return False
553
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
560                 else:
561                         # Sort lexicographically.
562                         return self.file_name < other.file_name
563
564 class GenChangeLogs(object):
565         def __init__(self, portdb):
566                 self.returncode = os.EX_OK
567                 self._portdb = portdb
568                 self._wrapper = textwrap.TextWrapper(
569                                 width = 78,
570                                 initial_indent = '  ',
571                                 subsequent_indent = '  '
572                         )
573
574         @staticmethod
575         def grab(cmd):
576                 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
577                 return _unicode_decode(p.communicate()[0],
578                                 encoding=_encodings['stdio'], errors='strict')
579
580         def generate_changelog(self, cp):
581                 try:
582                         output = codecs.open('ChangeLog',
583                                 mode='w', encoding=_encodings['repo.content'],
584                                 errors='replace')
585                 except IOError as e:
586                         writemsg_level(
587                                 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
588                                 level=logging.ERROR, noiselevel=-1)
589                         self.returncode |= 2
590                         return
591
592                 output.write(('''
593 # ChangeLog for %s
594 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
595 # $Header: $
596
597 ''' % (cp, time.strftime('%Y'))).lstrip())
598
599                 # now grab all the commits
600                 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
601
602                 for c in commits:
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.
611
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')
615
616                         # Expected output:
617                         # timestamp Author Name <author@email>
618                         # commit message l1
619                         # ...
620                         # commit message ln
621                         #
622                         # status1       filename1
623                         # ...
624                         # statusn       filenamen
625
626                         changed = []
627                         for n, l in enumerate(reversed(cinfo)):
628                                 if not l:
629                                         body = cinfo[1:-n-1]
630                                         break
631                                 else:
632                                         f = l.split()
633                                         if f[1] == 'Manifest':
634                                                 pass # XXX: remanifest commits?
635                                         elif f[1] == 'ChangeLog':
636                                                 pass
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]))
643                                         else:
644                                                 writemsg_level(
645                                                         "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
646                                                         level=logging.ERROR, noiselevel=-1)
647                                                 self.returncode |= 1
648
649                         if not changed:
650                                 continue
651
652                         (ts, author) = cinfo[0].split(' ', 1)
653                         date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
654
655                         changed = [str(x) for x in sorted(changed)]
656
657                         wroteheader = False
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))
662                                         wroteheader = True
663                         if wroteheader:
664                                 output.write('\n')
665
666                         # strip '<cp>: ', '[<cp>] ', and similar
667                         body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
668                         # strip trailing newline
669                         if not body[-1]:
670                                 body = body[:-1]
671                         # strip git-svn id
672                         if body[-1].startswith('git-svn-id:') and not body[-2]:
673                                 body = body[:-2]
674                         # strip the repoman version/manifest note
675                         if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
676                                 body = body[:-1]
677                         if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
678                                 body = body[:-1]
679                                 if not body[-1]:
680                                         body = body[:-1]
681
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]))
688
689                 output.close()
690
691         def run(self):
692                 repo_path = self._portdb.porttrees[0]
693                 os.chdir(repo_path)
694
695                 if 'git' not in FindVCS():
696                         writemsg_level(
697                                 "ERROR: --update-changelogs supported only in git repos\n",
698                                 level=logging.ERROR, noiselevel=-1)
699                         self.returncode = 127
700                         return
701
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', '.'])
707                         if not lmod:
708                                 # This cp has not been added to the repo.
709                                 continue
710
711                         try:
712                                 cmod = os.stat('ChangeLog').st_mtime
713                         except OSError:
714                                 cmod = 0
715
716                         if float(cmod) < float(lmod):
717                                 self.generate_changelog(cp)
718
719 def egencache_main(args):
720         parser, options, atoms = parse_args(args)
721
722         config_root = options.config_root
723         if config_root is None:
724                 config_root = '/'
725
726         # The calling environment is ignored, so the program is
727         # completely controlled by commandline arguments.
728         env = {}
729
730         if options.repo is None:
731                 env['PORTDIR_OVERLAY'] = ''
732
733         if options.cache_dir is not None:
734                 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
735
736         if options.portdir is not None:
737                 env['PORTDIR'] = options.portdir
738
739         settings = portage.config(config_root=config_root,
740                 target_root='/', local_config=False, env=env)
741
742         default_opts = None
743         if not options.ignore_default_opts:
744                 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
745
746         if default_opts:
747                 parser, options, args = parse_args(default_opts + args)
748
749                 if options.config_root is not None:
750                         config_root = options.config_root
751
752                 if options.cache_dir is not None:
753                         env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
754
755                 settings = portage.config(config_root=config_root,
756                         target_root='/', local_config=False, env=env)
757
758         if not options.update and not options.update_use_local_desc \
759                         and not options.update_changelogs:
760                 parser.error('No action specified')
761                 return 1
762
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')
768
769         settings.lock()
770
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'" % \
776                                 (options.repo,))
777                         return 1
778
779                 # Limit ebuilds to the specified repo.
780                 portdb.porttrees = [repo_path]
781
782         ret = [os.EX_OK]
783
784         if options.update:
785                 cp_iter = None
786                 if atoms:
787                         cp_iter = iter(atoms)
788
789                 gen_cache = GenCache(portdb, cp_iter=cp_iter,
790                         max_jobs=options.jobs,
791                         max_load=options.load_average,
792                         rsync=options.rsync)
793                 gen_cache.run()
794                 ret.append(gen_cache.returncode)
795
796         if options.update_use_local_desc:
797                 gen_desc = GenUseLocalDesc(portdb,
798                         output=options.uld_output,
799                         preserve_comments=options.preserve_comments)
800                 gen_desc.run()
801                 ret.append(gen_desc.returncode)
802
803         if options.update_changelogs:
804                 gen_clogs = GenChangeLogs(portdb)
805                 gen_clogs.run()
806                 ret.append(gen_clogs.returncode)
807
808         if options.tolerant:
809                 return ret[0]
810         return max(ret)
811
812 if __name__ == "__main__":
813         portage._disable_legacy_globals()
814         portage.util.noiselimit = -1
815         sys.exit(egencache_main(sys.argv[1:]))