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