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