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