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