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