Add PollScheduler.terminate() for interruption.
[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
276                         if received_signal:
277                                 sys.exit(received_signal[0])
278                 finally:
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)
284
285                 self.returncode |= self._regen.returncode
286                 cp_missing = self._cp_missing
287
288                 trg_cache = self._trg_cache
289                 dead_nodes = set()
290                 if self._global_cleanse:
291                         try:
292                                 for cpv in trg_cache:
293                                         cp = cpv_getkey(cpv)
294                                         if cp is None:
295                                                 self.returncode |= 1
296                                                 writemsg_level(
297                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
298                                                         level=logging.ERROR, noiselevel=-1)
299                                         else:
300                                                 dead_nodes.add(cpv)
301                         except CacheError as ce:
302                                 self.returncode |= 1
303                                 writemsg_level(
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)
308
309                 else:
310                         cp_set = self._cp_set
311                         try:
312                                 for cpv in trg_cache:
313                                         cp = cpv_getkey(cpv)
314                                         if cp is None:
315                                                 self.returncode |= 1
316                                                 writemsg_level(
317                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
318                                                         level=logging.ERROR, noiselevel=-1)
319                                         else:
320                                                 cp_missing.discard(cp)
321                                                 if cp in cp_set:
322                                                         dead_nodes.add(cpv)
323                         except CacheError as ce:
324                                 self.returncode |= 1
325                                 writemsg_level(
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)
330
331                 if cp_missing:
332                         self.returncode |= 1
333                         for cp in sorted(cp_missing):
334                                 writemsg_level(
335                                         "No ebuilds or cache entries found for '%s'\n"  % (cp,),
336                                         level=logging.ERROR, noiselevel=-1)
337
338                 if dead_nodes:
339                         dead_nodes.difference_update(self._existing_nodes)
340                         for k in dead_nodes:
341                                 try:
342                                         del trg_cache[k]
343                                 except KeyError:
344                                         pass
345                                 except CacheError as ce:
346                                         self.returncode |= 1
347                                         writemsg_level(
348                                                 "%s deleting stale cache: %s\n" % (k, ce),
349                                                 level=logging.ERROR, noiselevel=-1)
350
351                 if not trg_cache.autocommits:
352                         try:
353                                 trg_cache.commit()
354                         except CacheError as ce:
355                                 self.returncode |= 1
356                                 writemsg_level(
357                                         "committing target: %s\n" % (ce,),
358                                         level=logging.ERROR, noiselevel=-1)
359
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
367         
368         def run(self):
369                 repo_path = self._portdb.porttrees[0]
370                 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
371
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')
376                                 try:
377                                         os.mkdir(prof_path)
378                                 except OSError:
379                                         pass
380                         else:
381                                 desc_path = self._output
382
383                         try:
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')
389                                 else:
390                                         output = codecs.open(_unicode_encode(desc_path,
391                                                 encoding=_encodings['fs'], errors='strict'),
392                                                 mode='w', encoding=_encodings['repo.content'],
393                                                 errors='replace')
394                         except IOError as e:
395                                 writemsg_level(
396                                         "ERROR: failed to open output file %s: %s\n" % (desc_path,e,),
397                                         level=logging.ERROR, noiselevel=-1)
398                                 self.returncode |= 2
399                                 return
400                 else:
401                         output = sys.stdout
402
403                 if self._preserve_comments:
404                         while True:
405                                 pos = output.tell()
406                                 if not output.readline().startswith(b'#'):
407                                         break
408                         output.seek(pos)
409                         output.truncate()
410                         output.close()
411
412                         # Finished probing comments in binary mode, now append
413                         # in text mode.
414                         output = codecs.open(_unicode_encode(desc_path,
415                                 encoding=_encodings['fs'], errors='strict'),
416                                 mode='a', encoding=_encodings['repo.content'],
417                                 errors='replace')
418                         output.write('\n')
419                 else:
420                         output.write('''
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 *
424
425 '''.lstrip())
426
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.
431                 def cmp_func(a, b):
432                         return (a > b) - (a < b)
433
434                 for cp in self._portdb.cp_all():
435                         metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
436                         try:
437                                 metadata = ElementTree.parse(metadata_path)
438                         except IOError:
439                                 pass
440                         except (ExpatError, EnvironmentError) as e:
441                                 writemsg_level(
442                                         "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
443                                         level=logging.ERROR, noiselevel=-1)
444                                 self.returncode |= 1
445                         else:
446                                 try:
447                                         usedict = parse_metadata_use(metadata)
448                                 except portage.exception.ParseError as e:
449                                         writemsg_level(
450                                                 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
451                                                 level=logging.ERROR, noiselevel=-1)
452                                         self.returncode |= 1
453                                 else:
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)
462                                                         # Version matching
463                                                         elif atoma.cpv != atomb.cpv:
464                                                                 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
465                                                         # Versions match, let's fallback to operator matching
466                                                         else:
467                                                                 return cmp_func(ops.get(atoma.operator, -1),
468                                                                         ops.get(atomb.operator, -1))
469
470                                                 def _Atom(key):
471                                                         if key is not None:
472                                                                 return Atom(key)
473                                                         return None
474
475                                                 resdict = usedict[flag]
476                                                 if len(resdict) == 1:
477                                                         resdesc = next(iter(resdict.items()))[1]
478                                                 else:
479                                                         try:
480                                                                 reskeys = dict((_Atom(k), k) for k in resdict)
481                                                         except portage.exception.InvalidAtom as e:
482                                                                 writemsg_level(
483                                                                         "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
484                                                                         level=logging.ERROR, noiselevel=-1)
485                                                                 self.returncode |= 1
486                                                                 resdesc = next(iter(resdict.items()))[1]
487                                                         else:
488                                                                 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
489                                                                 resdesc = resdict[reskeys[resatoms[-1]]]
490
491                                                 output.write('%s:%s - %s\n' % (cp, flag, resdesc))
492
493                 output.close()
494
495 if sys.hexversion < 0x3000000:
496         _filename_base = unicode
497 else:
498         _filename_base = str
499
500 class _special_filename(_filename_base):
501         """
502         Helps to sort file names by file type and other criteria.
503         """
504         def __new__(cls, status_change, file_name):
505                 return _filename_base.__new__(cls, status_change + file_name)
506
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)
512
513         def file_type_lt(self, a, b):
514                 """
515                 Defines an ordering between file types.
516                 """
517                 first = a.file_type
518                 second = b.file_type
519                 if first == second:
520                         return False
521
522                 if first == "EBUILD":
523                         return True
524                 elif first == "MISC":
525                         return second in ("EBUILD",)
526                 elif first == "AUX":
527                         return second in ("EBUILD", "MISC")
528                 elif first == "DIST":
529                         return second in ("EBUILD", "MISC", "AUX")
530                 elif first is None:
531                         return False
532                 else:
533                         raise ValueError("Unknown file type '%s'" % first)
534
535         def __lt__(self, other):
536                 """
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
540                 """
541                 if self.__class__ != other.__class__:
542                         raise NotImplementedError
543
544                 # Sort by file type as defined by file_type_lt().
545                 if self.file_type_lt(self, other):
546                         return True
547                 elif self.file_type_lt(other, self):
548                         return False
549
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
556                 else:
557                         # Sort lexicographically.
558                         return self.file_name < other.file_name
559
560 class GenChangeLogs(object):
561         def __init__(self, portdb):
562                 self.returncode = os.EX_OK
563                 self._portdb = portdb
564                 self._wrapper = textwrap.TextWrapper(
565                                 width = 78,
566                                 initial_indent = '  ',
567                                 subsequent_indent = '  '
568                         )
569
570         @staticmethod
571         def grab(cmd):
572                 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
573                 return _unicode_decode(p.communicate()[0],
574                                 encoding=_encodings['stdio'], errors='strict')
575
576         def generate_changelog(self, cp):
577                 try:
578                         output = codecs.open('ChangeLog',
579                                 mode='w', encoding=_encodings['repo.content'],
580                                 errors='replace')
581                 except IOError as e:
582                         writemsg_level(
583                                 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
584                                 level=logging.ERROR, noiselevel=-1)
585                         self.returncode |= 2
586                         return
587
588                 output.write(('''
589 # ChangeLog for %s
590 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
591 # $Header: $
592
593 ''' % (cp, time.strftime('%Y'))).lstrip())
594
595                 # now grab all the commits
596                 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
597
598                 for c in commits:
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.
607
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')
611
612                         # Expected output:
613                         # timestamp Author Name <author@email>
614                         # commit message l1
615                         # ...
616                         # commit message ln
617                         #
618                         # status1       filename1
619                         # ...
620                         # statusn       filenamen
621
622                         changed = []
623                         for n, l in enumerate(reversed(cinfo)):
624                                 if not l:
625                                         body = cinfo[1:-n-1]
626                                         break
627                                 else:
628                                         f = l.split()
629                                         if f[1] == 'Manifest':
630                                                 pass # XXX: remanifest commits?
631                                         elif f[1] == 'ChangeLog':
632                                                 pass
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]))
639                                         else:
640                                                 writemsg_level(
641                                                         "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
642                                                         level=logging.ERROR, noiselevel=-1)
643                                                 self.returncode |= 1
644
645                         if not changed:
646                                 continue
647
648                         (ts, author) = cinfo[0].split(' ', 1)
649                         date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
650
651                         changed = [str(x) for x in sorted(changed)]
652
653                         wroteheader = False
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))
658                                         wroteheader = True
659                         if wroteheader:
660                                 output.write('\n')
661
662                         # strip '<cp>: ', '[<cp>] ', and similar
663                         body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
664                         # strip trailing newline
665                         if not body[-1]:
666                                 body = body[:-1]
667                         # strip git-svn id
668                         if body[-1].startswith('git-svn-id:') and not body[-2]:
669                                 body = body[:-2]
670                         # strip the repoman version/manifest note
671                         if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
672                                 body = body[:-1]
673                         if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
674                                 body = body[:-1]
675                                 if not body[-1]:
676                                         body = body[:-1]
677
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]))
684
685                 output.close()
686
687         def run(self):
688                 repo_path = self._portdb.porttrees[0]
689                 os.chdir(repo_path)
690
691                 if 'git' not in FindVCS():
692                         writemsg_level(
693                                 "ERROR: --update-changelogs supported only in git repos\n",
694                                 level=logging.ERROR, noiselevel=-1)
695                         self.returncode = 127
696                         return
697
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', '.'])
703                         if not lmod:
704                                 # This cp has not been added to the repo.
705                                 continue
706
707                         try:
708                                 cmod = os.stat('ChangeLog').st_mtime
709                         except OSError:
710                                 cmod = 0
711
712                         if float(cmod) < float(lmod):
713                                 self.generate_changelog(cp)
714
715 def egencache_main(args):
716         parser, options, atoms = parse_args(args)
717
718         config_root = options.config_root
719         if config_root is None:
720                 config_root = '/'
721
722         # The calling environment is ignored, so the program is
723         # completely controlled by commandline arguments.
724         env = {}
725
726         if options.repo is None:
727                 env['PORTDIR_OVERLAY'] = ''
728
729         if options.cache_dir is not None:
730                 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
731
732         if options.portdir is not None:
733                 env['PORTDIR'] = options.portdir
734
735         settings = portage.config(config_root=config_root,
736                 target_root='/', local_config=False, env=env)
737
738         default_opts = None
739         if not options.ignore_default_opts:
740                 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
741
742         if default_opts:
743                 parser, options, args = parse_args(default_opts + args)
744
745                 if options.config_root is not None:
746                         config_root = options.config_root
747
748                 if options.cache_dir is not None:
749                         env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
750
751                 settings = portage.config(config_root=config_root,
752                         target_root='/', local_config=False, env=env)
753
754         if not options.update and not options.update_use_local_desc \
755                         and not options.update_changelogs:
756                 parser.error('No action specified')
757                 return 1
758
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')
764
765         settings.lock()
766
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'" % \
772                                 (options.repo,))
773                         return 1
774
775                 # Limit ebuilds to the specified repo.
776                 portdb.porttrees = [repo_path]
777
778         ret = [os.EX_OK]
779
780         if options.update:
781                 cp_iter = None
782                 if atoms:
783                         cp_iter = iter(atoms)
784
785                 gen_cache = GenCache(portdb, cp_iter=cp_iter,
786                         max_jobs=options.jobs,
787                         max_load=options.load_average,
788                         rsync=options.rsync)
789                 gen_cache.run()
790                 ret.append(gen_cache.returncode)
791
792         if options.update_use_local_desc:
793                 gen_desc = GenUseLocalDesc(portdb,
794                         output=options.uld_output,
795                         preserve_comments=options.preserve_comments)
796                 gen_desc.run()
797                 ret.append(gen_desc.returncode)
798
799         if options.update_changelogs:
800                 gen_clogs = GenChangeLogs(portdb)
801                 gen_clogs.run()
802                 ret.append(gen_clogs.returncode)
803
804         if options.tolerant:
805                 return ret[0]
806         return max(ret)
807
808 if __name__ == "__main__":
809         portage._disable_legacy_globals()
810         portage.util.noiselimit = -1
811         sys.exit(egencache_main(sys.argv[1:]))