egencache: add _mtime_ to metadata
[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 io
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.cache import metadata
42 from portage.manifest import guessManifestFileType
43 from portage.util import cmp_sort_key, writemsg_level
44 from portage import cpv_getkey
45 from portage.dep import Atom, isjustname
46 from portage.versions import pkgcmp, pkgsplit, vercmp
47
48 try:
49         from xml.etree import ElementTree
50 except ImportError:
51         pass
52 else:
53         try:
54                 from xml.parsers.expat import ExpatError
55         except ImportError:
56                 pass
57         else:
58                 from repoman.utilities import parse_metadata_use
59
60 from repoman.utilities import FindVCS
61
62 if sys.hexversion >= 0x3000000:
63         long = int
64
65 def parse_args(args):
66         usage = "egencache [options] <action> ... [atom] ..."
67         parser = optparse.OptionParser(usage=usage)
68
69         actions = optparse.OptionGroup(parser, 'Actions')
70         actions.add_option("--update",
71                 action="store_true",
72                 help="update metadata/cache/ (generate as necessary)")
73         actions.add_option("--update-use-local-desc",
74                 action="store_true",
75                 help="update the use.local.desc file from metadata.xml")
76         actions.add_option("--update-changelogs",
77                 action="store_true",
78                 help="update the ChangeLog files from SCM logs")
79         parser.add_option_group(actions)
80
81         common = optparse.OptionGroup(parser, 'Common options')
82         common.add_option("--repo",
83                 action="store",
84                 help="name of repo to operate on (default repo is located at $PORTDIR)")
85         common.add_option("--config-root",
86                 help="location of portage config files",
87                 dest="portage_configroot")
88         common.add_option("--portdir",
89                 help="override the portage tree location",
90                 dest="portdir")
91         common.add_option("--portdir-overlay",
92                 help="override the PORTDIR_OVERLAY variable (requires that --repo is also specified)",
93                 dest="portdir_overlay")
94         common.add_option("--tolerant",
95                 action="store_true",
96                 help="exit successfully if only minor errors occurred")
97         common.add_option("--ignore-default-opts",
98                 action="store_true",
99                 help="do not use the EGENCACHE_DEFAULT_OPTS environment variable")
100         parser.add_option_group(common)
101
102         update = optparse.OptionGroup(parser, '--update options')
103         update.add_option("--cache-dir",
104                 help="location of the metadata cache",
105                 dest="cache_dir")
106         update.add_option("--jobs",
107                 action="store",
108                 help="max ebuild processes to spawn")
109         update.add_option("--load-average",
110                 action="store",
111                 help="max load allowed when spawning multiple jobs",
112                 dest="load_average")
113         update.add_option("--rsync",
114                 action="store_true",
115                 help="enable rsync stat collision workaround " + \
116                         "for bug 139134 (use with --update)")
117         parser.add_option_group(update)
118
119         uld = optparse.OptionGroup(parser, '--update-use-local-desc options')
120         uld.add_option("--preserve-comments",
121                 action="store_true",
122                 help="preserve the comments from the existing use.local.desc file")
123         uld.add_option("--use-local-desc-output",
124                 help="output file for use.local.desc data (or '-' for stdout)",
125                 dest="uld_output")
126         parser.add_option_group(uld)
127
128         options, args = parser.parse_args(args)
129
130         if options.jobs:
131                 jobs = None
132                 try:
133                         jobs = int(options.jobs)
134                 except ValueError:
135                         jobs = -1
136
137                 if jobs < 1:
138                         parser.error("Invalid: --jobs='%s'" % \
139                                 (options.jobs,))
140
141                 options.jobs = jobs
142
143         else:
144                 options.jobs = None
145
146         if options.load_average:
147                 try:
148                         load_average = float(options.load_average)
149                 except ValueError:
150                         load_average = 0.0
151
152                 if load_average <= 0.0:
153                         parser.error("Invalid: --load-average='%s'" % \
154                                 (options.load_average,))
155
156                 options.load_average = load_average
157
158         else:
159                 options.load_average = None
160
161         options.config_root = options.portage_configroot
162         if options.config_root is not None and \
163                 not os.path.isdir(options.config_root):
164                 parser.error("Not a directory: --config-root='%s'" % \
165                         (options.config_root,))
166
167         if options.cache_dir is not None:
168                 if not os.path.isdir(options.cache_dir):
169                         parser.error("Not a directory: --cache-dir='%s'" % \
170                                 (options.cache_dir,))
171                 if not os.access(options.cache_dir, os.W_OK):
172                         parser.error("Write access denied: --cache-dir='%s'" % \
173                                 (options.cache_dir,))
174
175         if options.portdir_overlay is not None and \
176                 options.repo is None:
177                 parser.error("--portdir-overlay option requires --repo option")
178
179         for atom in args:
180                 try:
181                         atom = portage.dep.Atom(atom)
182                 except portage.exception.InvalidAtom:
183                         parser.error('Invalid atom: %s' % (atom,))
184
185                 if not isjustname(atom):
186                         parser.error('Atom is too specific: %s' % (atom,))
187
188         if options.update_use_local_desc:
189                 try:
190                         ElementTree
191                         ExpatError
192                 except NameError:
193                         parser.error('--update-use-local-desc requires python with USE=xml!')
194
195         if options.uld_output == '-' and options.preserve_comments:
196                 parser.error('--preserve-comments can not be used when outputting to stdout')
197
198         return parser, options, args
199
200 class GenCache(object):
201         def __init__(self, portdb, cp_iter=None, max_jobs=None, max_load=None,
202                 rsync=False):
203                 self._portdb = portdb
204                 # We can globally cleanse stale cache only if we
205                 # iterate over every single cp.
206                 self._global_cleanse = cp_iter is None
207                 if cp_iter is not None:
208                         self._cp_set = set(cp_iter)
209                         cp_iter = iter(self._cp_set)
210                         self._cp_missing = self._cp_set.copy()
211                 else:
212                         self._cp_set = None
213                         self._cp_missing = set()
214                 self._regen = MetadataRegen(portdb, cp_iter=cp_iter,
215                         consumer=self._metadata_callback,
216                         max_jobs=max_jobs, max_load=max_load)
217                 self.returncode = os.EX_OK
218                 conf = portdb.repositories.get_repo_for_location(portdb.porttrees[0])
219                 self._trg_cache = conf.get_pregenerated_cache(portage.auxdbkeys[:],
220                         force=True, readonly=False)
221                 if self._trg_cache is None:
222                         raise Exception("cache format %s isn't supported" % (conf.cache_format,))
223                 if rsync:
224                         self._trg_cache.raise_stat_collision = True
225                 try:
226                         self._trg_cache.ec = \
227                                 portdb._repo_info[portdb.porttrees[0]].eclass_db
228                 except AttributeError:
229                         pass
230                 self._existing_nodes = set()
231
232         def _metadata_callback(self, cpv, repo_path, metadata, ebuild_hash):
233                 self._existing_nodes.add(cpv)
234                 self._cp_missing.discard(cpv_getkey(cpv))
235                 if metadata is not None:
236                         if metadata.get('EAPI') == '0':
237                                 del metadata['EAPI']
238                         try:
239                                 chf = self._trg_cache.validation_chf
240                                 metadata['_%s_' % chf] = getattr(ebuild_hash, chf)
241                                 try:
242                                         self._trg_cache[cpv] = metadata
243                                 except StatCollision as sc:
244                                         # If the content of a cache entry changes and neither the
245                                         # file mtime nor size changes, it will prevent rsync from
246                                         # detecting changes. Cache backends may raise this
247                                         # exception from _setitem() if they detect this type of stat
248                                         # collision. These exceptions are handled by bumping the
249                                         # mtime on the ebuild (and the corresponding cache entry).
250                                         # See bug #139134.
251                                         max_mtime = sc.mtime
252                                         for ec, (loc, ec_mtime) in metadata['_eclasses_'].items():
253                                                 if max_mtime < ec_mtime:
254                                                         max_mtime = ec_mtime
255                                         if max_mtime == sc.mtime:
256                                                 max_mtime += 1
257                                         max_mtime = long(max_mtime)
258                                         try:
259                                                 os.utime(ebuild_hash.location, (max_mtime, max_mtime))
260                                         except OSError as e:
261                                                 self.returncode |= 1
262                                                 writemsg_level(
263                                                         "%s writing target: %s\n" % (cpv, e),
264                                                         level=logging.ERROR, noiselevel=-1)
265                                         else:
266                                                 metadata['_mtime_'] = max_mtime
267                                                 self._trg_cache[cpv] = metadata
268                                                 self._portdb.auxdb[repo_path][cpv] = metadata
269
270                         except CacheError as ce:
271                                 self.returncode |= 1
272                                 writemsg_level(
273                                         "%s writing target: %s\n" % (cpv, ce),
274                                         level=logging.ERROR, noiselevel=-1)
275
276         def run(self):
277
278                 received_signal = []
279
280                 def sighandler(signum, frame):
281                         signal.signal(signal.SIGINT, signal.SIG_IGN)
282                         signal.signal(signal.SIGTERM, signal.SIG_IGN)
283                         self._regen.terminate()
284                         received_signal.append(128 + signum)
285
286                 earlier_sigint_handler = signal.signal(signal.SIGINT, sighandler)
287                 earlier_sigterm_handler = signal.signal(signal.SIGTERM, sighandler)
288
289                 try:
290                         self._regen.run()
291                 finally:
292                         # Restore previous handlers
293                         if earlier_sigint_handler is not None:
294                                 signal.signal(signal.SIGINT, earlier_sigint_handler)
295                         else:
296                                 signal.signal(signal.SIGINT, signal.SIG_DFL)
297                         if earlier_sigterm_handler is not None:
298                                 signal.signal(signal.SIGTERM, earlier_sigterm_handler)
299                         else:
300                                 signal.signal(signal.SIGTERM, signal.SIG_DFL)
301
302                 if received_signal:
303                         sys.exit(received_signal[0])
304
305                 self.returncode |= self._regen.returncode
306                 cp_missing = self._cp_missing
307
308                 trg_cache = self._trg_cache
309                 dead_nodes = set()
310                 if self._global_cleanse:
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                                                 dead_nodes.add(cpv)
321                         except CacheError as ce:
322                                 self.returncode |= 1
323                                 writemsg_level(
324                                         "Error listing cache entries for " + \
325                                         "'%s/metadata/cache': %s, continuing...\n" % \
326                                         (self._portdb.porttree_root, ce),
327                                         level=logging.ERROR, noiselevel=-1)
328
329                 else:
330                         cp_set = self._cp_set
331                         try:
332                                 for cpv in trg_cache:
333                                         cp = cpv_getkey(cpv)
334                                         if cp is None:
335                                                 self.returncode |= 1
336                                                 writemsg_level(
337                                                         "Unable to parse cp for '%s'\n"  % (cpv,),
338                                                         level=logging.ERROR, noiselevel=-1)
339                                         else:
340                                                 cp_missing.discard(cp)
341                                                 if cp in cp_set:
342                                                         dead_nodes.add(cpv)
343                         except CacheError as ce:
344                                 self.returncode |= 1
345                                 writemsg_level(
346                                         "Error listing cache entries for " + \
347                                         "'%s/metadata/cache': %s, continuing...\n" % \
348                                         (self._portdb.porttree_root, ce),
349                                         level=logging.ERROR, noiselevel=-1)
350
351                 if cp_missing:
352                         self.returncode |= 1
353                         for cp in sorted(cp_missing):
354                                 writemsg_level(
355                                         "No ebuilds or cache entries found for '%s'\n"  % (cp,),
356                                         level=logging.ERROR, noiselevel=-1)
357
358                 if dead_nodes:
359                         dead_nodes.difference_update(self._existing_nodes)
360                         for k in dead_nodes:
361                                 try:
362                                         del trg_cache[k]
363                                 except KeyError:
364                                         pass
365                                 except CacheError as ce:
366                                         self.returncode |= 1
367                                         writemsg_level(
368                                                 "%s deleting stale cache: %s\n" % (k, ce),
369                                                 level=logging.ERROR, noiselevel=-1)
370
371                 if not trg_cache.autocommits:
372                         try:
373                                 trg_cache.commit()
374                         except CacheError as ce:
375                                 self.returncode |= 1
376                                 writemsg_level(
377                                         "committing target: %s\n" % (ce,),
378                                         level=logging.ERROR, noiselevel=-1)
379
380 class GenUseLocalDesc(object):
381         def __init__(self, portdb, output=None,
382                         preserve_comments=False):
383                 self.returncode = os.EX_OK
384                 self._portdb = portdb
385                 self._output = output
386                 self._preserve_comments = preserve_comments
387         
388         def run(self):
389                 repo_path = self._portdb.porttrees[0]
390                 ops = {'<':0, '<=':1, '=':2, '>=':3, '>':4}
391
392                 if self._output is None or self._output != '-':
393                         if self._output is None:
394                                 prof_path = os.path.join(repo_path, 'profiles')
395                                 desc_path = os.path.join(prof_path, 'use.local.desc')
396                                 try:
397                                         os.mkdir(prof_path)
398                                 except OSError:
399                                         pass
400                         else:
401                                 desc_path = self._output
402
403                         try:
404                                 if self._preserve_comments:
405                                         # Probe in binary mode, in order to avoid
406                                         # potential character encoding issues.
407                                         output = open(_unicode_encode(desc_path,
408                                                 encoding=_encodings['fs'], errors='strict'), 'r+b')
409                                 else:
410                                         output = io.open(_unicode_encode(desc_path,
411                                                 encoding=_encodings['fs'], errors='strict'),
412                                                 mode='w', encoding=_encodings['repo.content'],
413                                                 errors='backslashreplace')
414                         except IOError as e:
415                                 if not self._preserve_comments or \
416                                         os.path.isfile(desc_path):
417                                         writemsg_level(
418                                                 "ERROR: failed to open output file %s: %s\n" \
419                                                 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
420                                         self.returncode |= 2
421                                         return
422
423                                 # Open in r+b mode failed because the file doesn't
424                                 # exist yet. We can probably recover if we disable
425                                 # preserve_comments mode now.
426                                 writemsg_level(
427                                         "WARNING: --preserve-comments enabled, but " + \
428                                         "output file not found: %s\n" % (desc_path,),
429                                         level=logging.WARNING, noiselevel=-1)
430                                 self._preserve_comments = False
431                                 try:
432                                         output = io.open(_unicode_encode(desc_path,
433                                                 encoding=_encodings['fs'], errors='strict'),
434                                                 mode='w', encoding=_encodings['repo.content'],
435                                                 errors='backslashreplace')
436                                 except IOError as e:
437                                         writemsg_level(
438                                                 "ERROR: failed to open output file %s: %s\n" \
439                                                 % (desc_path, e), level=logging.ERROR, noiselevel=-1)
440                                         self.returncode |= 2
441                                         return
442                 else:
443                         output = sys.stdout
444
445                 if self._preserve_comments:
446                         while True:
447                                 pos = output.tell()
448                                 if not output.readline().startswith(b'#'):
449                                         break
450                         output.seek(pos)
451                         output.truncate()
452                         output.close()
453
454                         # Finished probing comments in binary mode, now append
455                         # in text mode.
456                         output = io.open(_unicode_encode(desc_path,
457                                 encoding=_encodings['fs'], errors='strict'),
458                                 mode='a', encoding=_encodings['repo.content'],
459                                 errors='backslashreplace')
460                         output.write(_unicode_decode('\n'))
461                 else:
462                         output.write(_unicode_decode('''
463 # This file is deprecated as per GLEP 56 in favor of metadata.xml. Please add
464 # your descriptions to your package's metadata.xml ONLY.
465 # * generated automatically using egencache *
466
467 '''.lstrip()))
468
469                 # The cmp function no longer exists in python3, so we'll
470                 # implement our own here under a slightly different name
471                 # since we don't want any confusion given that we never
472                 # want to rely on the builtin cmp function.
473                 def cmp_func(a, b):
474                         if a is None or b is None:
475                                 # None can't be compared with other types in python3.
476                                 if a is None and b is None:
477                                         return 0
478                                 elif a is None:
479                                         return -1
480                                 else:
481                                         return 1
482                         return (a > b) - (a < b)
483
484                 class _MetadataTreeBuilder(ElementTree.TreeBuilder):
485                         """
486                         Implements doctype() as required to avoid deprecation warnings
487                         since Python >=2.7
488                         """
489                         def doctype(self, name, pubid, system):
490                                 pass
491
492                 for cp in self._portdb.cp_all():
493                         metadata_path = os.path.join(repo_path, cp, 'metadata.xml')
494                         try:
495                                 metadata = ElementTree.parse(metadata_path,
496                                         parser=ElementTree.XMLParser(
497                                         target=_MetadataTreeBuilder()))
498                         except IOError:
499                                 pass
500                         except (ExpatError, EnvironmentError) as e:
501                                 writemsg_level(
502                                         "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
503                                         level=logging.ERROR, noiselevel=-1)
504                                 self.returncode |= 1
505                         else:
506                                 try:
507                                         usedict = parse_metadata_use(metadata)
508                                 except portage.exception.ParseError as e:
509                                         writemsg_level(
510                                                 "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
511                                                 level=logging.ERROR, noiselevel=-1)
512                                         self.returncode |= 1
513                                 else:
514                                         for flag in sorted(usedict):
515                                                 def atomcmp(atoma, atomb):
516                                                         # None is better than an atom, that's why we reverse the args
517                                                         if atoma is None or atomb is None:
518                                                                 return cmp_func(atomb, atoma)
519                                                         # Same for plain PNs (.operator is None then)
520                                                         elif atoma.operator is None or atomb.operator is None:
521                                                                 return cmp_func(atomb.operator, atoma.operator)
522                                                         # Version matching
523                                                         elif atoma.cpv != atomb.cpv:
524                                                                 return pkgcmp(pkgsplit(atoma.cpv), pkgsplit(atomb.cpv))
525                                                         # Versions match, let's fallback to operator matching
526                                                         else:
527                                                                 return cmp_func(ops.get(atoma.operator, -1),
528                                                                         ops.get(atomb.operator, -1))
529
530                                                 def _Atom(key):
531                                                         if key is not None:
532                                                                 return Atom(key)
533                                                         return None
534
535                                                 resdict = usedict[flag]
536                                                 if len(resdict) == 1:
537                                                         resdesc = next(iter(resdict.items()))[1]
538                                                 else:
539                                                         try:
540                                                                 reskeys = dict((_Atom(k), k) for k in resdict)
541                                                         except portage.exception.InvalidAtom as e:
542                                                                 writemsg_level(
543                                                                         "ERROR: failed parsing %s/metadata.xml: %s\n" % (cp, e),
544                                                                         level=logging.ERROR, noiselevel=-1)
545                                                                 self.returncode |= 1
546                                                                 resdesc = next(iter(resdict.items()))[1]
547                                                         else:
548                                                                 resatoms = sorted(reskeys, key=cmp_sort_key(atomcmp))
549                                                                 resdesc = resdict[reskeys[resatoms[-1]]]
550
551                                                 output.write(_unicode_decode(
552                                                         '%s:%s - %s\n' % (cp, flag, resdesc)))
553
554                 output.close()
555
556 if sys.hexversion < 0x3000000:
557         _filename_base = unicode
558 else:
559         _filename_base = str
560
561 class _special_filename(_filename_base):
562         """
563         Helps to sort file names by file type and other criteria.
564         """
565         def __new__(cls, status_change, file_name):
566                 return _filename_base.__new__(cls, status_change + file_name)
567
568         def __init__(self, status_change, file_name):
569                 _filename_base.__init__(status_change + file_name)
570                 self.status_change = status_change
571                 self.file_name = file_name
572                 self.file_type = guessManifestFileType(file_name)
573
574         def file_type_lt(self, a, b):
575                 """
576                 Defines an ordering between file types.
577                 """
578                 first = a.file_type
579                 second = b.file_type
580                 if first == second:
581                         return False
582
583                 if first == "EBUILD":
584                         return True
585                 elif first == "MISC":
586                         return second in ("EBUILD",)
587                 elif first == "AUX":
588                         return second in ("EBUILD", "MISC")
589                 elif first == "DIST":
590                         return second in ("EBUILD", "MISC", "AUX")
591                 elif first is None:
592                         return False
593                 else:
594                         raise ValueError("Unknown file type '%s'" % first)
595
596         def __lt__(self, other):
597                 """
598                 Compare different file names, first by file type and then
599                 for ebuilds by version and lexicographically for others.
600                 EBUILD < MISC < AUX < DIST < None
601                 """
602                 if self.__class__ != other.__class__:
603                         raise NotImplementedError
604
605                 # Sort by file type as defined by file_type_lt().
606                 if self.file_type_lt(self, other):
607                         return True
608                 elif self.file_type_lt(other, self):
609                         return False
610
611                 # Files have the same type.
612                 if self.file_type == "EBUILD":
613                         # Sort by version. Lowest first.
614                         ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
615                         other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
616                         return vercmp(ver, other_ver) < 0
617                 else:
618                         # Sort lexicographically.
619                         return self.file_name < other.file_name
620
621 class GenChangeLogs(object):
622         def __init__(self, portdb):
623                 self.returncode = os.EX_OK
624                 self._portdb = portdb
625                 self._wrapper = textwrap.TextWrapper(
626                                 width = 78,
627                                 initial_indent = '  ',
628                                 subsequent_indent = '  '
629                         )
630
631         @staticmethod
632         def grab(cmd):
633                 p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
634                 return _unicode_decode(p.communicate()[0],
635                                 encoding=_encodings['stdio'], errors='strict')
636
637         def generate_changelog(self, cp):
638                 try:
639                         output = io.open('ChangeLog',
640                                 mode='w', encoding=_encodings['repo.content'],
641                                 errors='backslashreplace')
642                 except IOError as e:
643                         writemsg_level(
644                                 "ERROR: failed to open ChangeLog for %s: %s\n" % (cp,e,),
645                                 level=logging.ERROR, noiselevel=-1)
646                         self.returncode |= 2
647                         return
648
649                 output.write(_unicode_decode('''
650 # ChangeLog for %s
651 # Copyright 1999-%s Gentoo Foundation; Distributed under the GPL v2
652 # $Header: $
653
654 ''' % (cp, time.strftime('%Y'))).lstrip())
655
656                 # now grab all the commits
657                 commits = self.grab(['git', 'rev-list', 'HEAD', '--', '.']).split()
658
659                 for c in commits:
660                         # Explaining the arguments:
661                         # --name-status to get a list of added/removed files
662                         # --no-renames to avoid getting more complex records on the list
663                         # --format to get the timestamp, author and commit description
664                         # --root to make it work fine even with the initial commit
665                         # --relative to get paths relative to ebuilddir
666                         # -r (recursive) to get per-file changes
667                         # then the commit-id and path.
668
669                         cinfo = self.grab(['git', 'diff-tree', '--name-status', '--no-renames',
670                                         '--format=%ct %cN <%cE>%n%B', '--root', '--relative', '-r',
671                                         c, '--', '.']).rstrip('\n').split('\n')
672
673                         # Expected output:
674                         # timestamp Author Name <author@email>
675                         # commit message l1
676                         # ...
677                         # commit message ln
678                         #
679                         # status1       filename1
680                         # ...
681                         # statusn       filenamen
682
683                         changed = []
684                         for n, l in enumerate(reversed(cinfo)):
685                                 if not l:
686                                         body = cinfo[1:-n-1]
687                                         break
688                                 else:
689                                         f = l.split()
690                                         if f[1] == 'Manifest':
691                                                 pass # XXX: remanifest commits?
692                                         elif f[1] == 'ChangeLog':
693                                                 pass
694                                         elif f[0].startswith('A'):
695                                                 changed.append(_special_filename("+", f[1]))
696                                         elif f[0].startswith('D'):
697                                                 changed.append(_special_filename("-", f[1]))
698                                         elif f[0].startswith('M'):
699                                                 changed.append(_special_filename("", f[1]))
700                                         else:
701                                                 writemsg_level(
702                                                         "ERROR: unexpected git file status for %s: %s\n" % (cp,f,),
703                                                         level=logging.ERROR, noiselevel=-1)
704                                                 self.returncode |= 1
705
706                         if not changed:
707                                 continue
708
709                         (ts, author) = cinfo[0].split(' ', 1)
710                         date = time.strftime('%d %b %Y', time.gmtime(float(ts)))
711
712                         changed = [str(x) for x in sorted(changed)]
713
714                         wroteheader = False
715                         # Reverse the sort order for headers.
716                         for c in reversed(changed):
717                                 if c.startswith('+') and c.endswith('.ebuild'):
718                                         output.write(_unicode_decode(
719                                                 '*%s (%s)\n' % (c[1:-7], date)))
720                                         wroteheader = True
721                         if wroteheader:
722                                 output.write(_unicode_decode('\n'))
723
724                         # strip '<cp>: ', '[<cp>] ', and similar
725                         body[0] = re.sub(r'^\W*' + re.escape(cp) + r'\W+', '', body[0])
726                         # strip trailing newline
727                         if not body[-1]:
728                                 body = body[:-1]
729                         # strip git-svn id
730                         if body[-1].startswith('git-svn-id:') and not body[-2]:
731                                 body = body[:-2]
732                         # strip the repoman version/manifest note
733                         if body[-1] == ' (Signed Manifest commit)' or body[-1] == ' (Unsigned Manifest commit)':
734                                 body = body[:-1]
735                         if body[-1].startswith('(Portage version:') and body[-1].endswith(')'):
736                                 body = body[:-1]
737                                 if not body[-1]:
738                                         body = body[:-1]
739
740                         # don't break filenames on hyphens
741                         self._wrapper.break_on_hyphens = False
742                         output.write(_unicode_decode(
743                                 self._wrapper.fill(
744                                 '%s; %s %s:' % (date, author, ', '.join(changed)))))
745                         # but feel free to break commit messages there
746                         self._wrapper.break_on_hyphens = True
747                         output.write(_unicode_decode(
748                                 '\n%s\n\n' % '\n'.join(self._wrapper.fill(x) for x in body)))
749
750                 output.close()
751
752         def run(self):
753                 repo_path = self._portdb.porttrees[0]
754                 os.chdir(repo_path)
755
756                 if 'git' not in FindVCS():
757                         writemsg_level(
758                                 "ERROR: --update-changelogs supported only in git repos\n",
759                                 level=logging.ERROR, noiselevel=-1)
760                         self.returncode = 127
761                         return
762
763                 for cp in self._portdb.cp_all():
764                         os.chdir(os.path.join(repo_path, cp))
765                         # Determine whether ChangeLog is up-to-date by comparing
766                         # the newest commit timestamp with the ChangeLog timestamp.
767                         lmod = self.grab(['git', 'log', '--format=%ct', '-1', '.'])
768                         if not lmod:
769                                 # This cp has not been added to the repo.
770                                 continue
771
772                         try:
773                                 cmod = os.stat('ChangeLog').st_mtime
774                         except OSError:
775                                 cmod = 0
776
777                         if float(cmod) < float(lmod):
778                                 self.generate_changelog(cp)
779
780 def egencache_main(args):
781         parser, options, atoms = parse_args(args)
782
783         config_root = options.config_root
784
785         # The calling environment is ignored, so the program is
786         # completely controlled by commandline arguments.
787         env = {}
788
789         if options.repo is None:
790                 env['PORTDIR_OVERLAY'] = ''
791         elif options.portdir_overlay:
792                 env['PORTDIR_OVERLAY'] = options.portdir_overlay
793
794         if options.cache_dir is not None:
795                 env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
796
797         if options.portdir is not None:
798                 env['PORTDIR'] = options.portdir
799
800         eprefix = os.environ.get("__PORTAGE_TEST_EPREFIX")
801
802         settings = portage.config(config_root=config_root,
803                 local_config=False, env=env, _eprefix=eprefix)
804
805         default_opts = None
806         if not options.ignore_default_opts:
807                 default_opts = settings.get('EGENCACHE_DEFAULT_OPTS', '').split()
808
809         if default_opts:
810                 parser, options, args = parse_args(default_opts + args)
811
812                 if options.cache_dir is not None:
813                         env['PORTAGE_DEPCACHEDIR'] = options.cache_dir
814
815                 settings = portage.config(config_root=config_root,
816                         local_config=False, env=env, _eprefix=eprefix)
817
818         if not options.update and not options.update_use_local_desc \
819                         and not options.update_changelogs:
820                 parser.error('No action specified')
821                 return 1
822
823         if options.update and 'metadata-transfer' not in settings.features:
824                 settings.features.add('metadata-transfer')
825
826         settings.lock()
827
828         portdb = portage.portdbapi(mysettings=settings)
829
830         if options.update:
831                 if options.cache_dir is not None:
832                         # already validated earlier
833                         pass
834                 else:
835                         # We check write access after the portdbapi constructor
836                         # has had an opportunity to create it. This ensures that
837                         # we don't use the cache in the "volatile" mode which is
838                         # undesirable for egencache.
839                         if not os.access(settings["PORTAGE_DEPCACHEDIR"], os.W_OK):
840                                 writemsg_level("ecachegen: error: " + \
841                                         "write access denied: %s\n" % (settings["PORTAGE_DEPCACHEDIR"],),
842                                         level=logging.ERROR, noiselevel=-1)
843                                 return 1
844
845         if options.repo is not None:
846                 repo_path = portdb.getRepositoryPath(options.repo)
847                 if repo_path is None:
848                         parser.error("Unable to locate repository named '%s'" % \
849                                 (options.repo,))
850                         return 1
851
852                 # Limit ebuilds to the specified repo.
853                 portdb.porttrees = [repo_path]
854
855         ret = [os.EX_OK]
856
857         if options.update:
858                 cp_iter = None
859                 if atoms:
860                         cp_iter = iter(atoms)
861
862                 gen_cache = GenCache(portdb, cp_iter=cp_iter,
863                         max_jobs=options.jobs,
864                         max_load=options.load_average,
865                         rsync=options.rsync)
866                 gen_cache.run()
867                 if options.tolerant:
868                         ret.append(os.EX_OK)
869                 else:
870                         ret.append(gen_cache.returncode)
871
872         if options.update_use_local_desc:
873                 gen_desc = GenUseLocalDesc(portdb,
874                         output=options.uld_output,
875                         preserve_comments=options.preserve_comments)
876                 gen_desc.run()
877                 ret.append(gen_desc.returncode)
878
879         if options.update_changelogs:
880                 gen_clogs = GenChangeLogs(portdb)
881                 gen_clogs.run()
882                 ret.append(gen_clogs.returncode)
883
884         return max(ret)
885
886 if __name__ == "__main__":
887         portage._disable_legacy_globals()
888         portage.util.noiselimit = -1
889         sys.exit(egencache_main(sys.argv[1:]))