2 #emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
3 #ex: set sts=4 ts=4 sw=4 noet:
4 """Script to help maintaining package definitions within Debian blends
7 Often it becomes necessary to duplicate the same information about a
8 package within debian packaging and multiple blends task files,
9 possibly of different blends. This script allows to automate:
11 - construction of entries
12 - injection into task files
13 - modification of existing entries if things changed
14 - removal of previously injected entries
19 * For every package the same task file might be re-read/written (if
20 entry changed/added) from disk.
21 That allows to replace easily original entry for 'source' package
22 (listed as Ignore:) with actual first listed binary package.
23 This should be taken into consideration if current per-package
32 Paths to the blends top directories, containing tasks directories are
33 specified in ~/.blends-inject.cfg file, e.g.::
36 path = /home/yoh/deb/debian-med/
39 path = /home/yoh/deb/debian-science/
42 Definition of the fields for task files by default are looked up
43 within debian/blends, or files provided in the command line.
45 Format of debian/blends
46 -----------------------
50 ; If originally filed using project source name, and it is different
51 ; from the primary (first) binary package name, keep 'Source' to be
52 ; able to adopt previously included tasks entry
55 ; Define the format on how entries should be handled.
57 ; extended -- whenever package is not in Debian and additional
58 ; fields should be obtained from debian/*:
65 ; plain [default] -- only fields listed here should be mentioned.
66 ; Common use -- whenever package is already known to UDD.
68 ; By default, all fields specified previously propagate into following
69 ; packages as well. If that is not desired, add suffix '-clean' to
73 Tasks: debian-science/neuroscience-modeling
75 ; Could have Depends/Recommends/Suggests and Ignore
76 ; All those define Pkg-Name field which is not included
77 ; in the final "rendering" but is available as Pkg-Name item
79 Pkg-URL: http://neuro.debian.net/pkgs/%(Pkg-Name)s.html
81 Published-Authors: Goodman D.F. and Brette R.
82 Published-Title: Brian: a simulator for spiking neural networks in Python
83 Published-In: Front. Neuroinform
85 Published-DOI: 10.3389/neuro.11.005.2008
87 ; May be some previous entry should be removed, thus say so
88 Removed: python-brian-doc
90 ;Tasks: debian-med/imaging-dev
91 ;Why: Allows interactive development/scripting
93 ; ; It should be possible to switch between formats,
94 ; ; e.g. if some component is not yet in Debian
97 ; ; Now some bogus one but with customizations
98 ;Tasks: debian-med/documentation
99 ;Recommends: python-brian-doc
108 from os.path import join, exists, expanduser, dirname, basename
110 from ConfigParser import ConfigParser
111 from optparse import OptionParser, Option
113 from copy import deepcopy
114 #from debian_bundle import deb822
115 from debian import deb822
117 from debian.changelog import Changelog
119 # all files we are dealing with should be UTF8, thus
124 return codecs.open(f, *args, encoding='utf-8')
126 __author__ = 'Yaroslav Halchenko'
127 __prog__ = os.path.basename(sys.argv[0])
128 __version__ = '0.0.2'
129 __copyright__ = 'Copyright (c) 2010 Yaroslav Halchenko'
132 # What fields initiate new package description
133 PKG_FIELDS = ('depends', 'recommends', 'suggests', 'ignore', 'removed')
135 # We might need to resort to assure some what a canonical order
136 FIELDS_ORDER = ('depends', 'recommends', 'suggests', 'ignore',
137 'homepage', 'language', 'wnpp', 'responsible', 'license',
138 'vcs-', 'pkg-url', 'pkg-description',
139 'published-', 'x-', 'registration', 'remark')
143 def error(msg, exit_code=1):
144 sys.stderr.write(msg + '\n')
147 def verbose(level, msg):
148 if level <= verbosity:
152 def parse_debian_blends(f='debian/blends'):
153 """Parses debian/blends file
155 Returns unprocessed list of customized Deb822 entries
157 # Linearize all the paragraphs since we are not using them
159 for p in deb822.Deb822.iter_paragraphs(open(f)):
162 verbose(6, "Got items %s" % items)
163 # Traverse and collect things
165 format_clean = False # do not propagate fields into a new pkg if True
166 pkg, source = None, None
170 def new_pkg(prev_pkg, bname, sname, tasks):
171 """Helper function to create a new package
173 if format_clean or prev_pkg is None:
174 pkg = deb822.Deb822()
176 pkg = deepcopy(prev_pkg)
177 for k_ in PKG_FIELDS: # prune older depends
179 pkg['Pkg-Name'] = pkg[k] = bname
180 pkg['Pkg-Source'] = sname
182 pkg.tasks = dict( (t.strip(), deb822.Deb822Dict()) for t in tasks )
193 format_clean = format_.endswith('-clean')
195 format_ = format_[:-6]
198 newtasks = True # either we need to provide tune-ups
199 # for current package
200 elif kl in PKG_FIELDS: # new package
203 pkg = new_pkg(pkg, v, source, tasks)
208 # So we had just source?
210 error("No package or source is known where to add %s" % (k,), 1)
211 # TODO: just deduce source from DebianMaterials
212 pkg = new_pkg(pkg, source, source, tasks)
213 # Since only source is available, it should be Ignore:-ed
214 pkg['Ignore'] = source
218 if not t in pkg.tasks:
219 pkg.tasks[t] = deb822.Deb822Dict()
222 # just store the key in the pkg itself
227 def expand_pkgs(pkgs, topdir='.'):
228 """In-place modification of pkgs taking if necessary additional
229 information from Debian materials, and pruning empty fields
231 verbose(4, "Expanding content for %d packages" % len(pkgs))
233 # Expand packages which format is extended
235 if pkg.format == 'extended':
236 # expanding, for that we need debian/control
238 debianm = DebianMaterials(topdir)
239 for k, m in (('License', lambda: debianm.get_license(pkg['Pkg-Name'])),
240 ('WNPP', debianm.get_wnpp),
242 lambda: debianm.get_description(pkg['Pkg-Name'])),
243 ('Responsible', debianm.get_responsible),
244 ('Homepage', lambda: debianm.source.get('Homepage', None))):
251 pkg.update(debianm.get_vcsfields())
253 def key_prefix_compare(x, y, order, strict=False, case=False):
254 """Little helper to help with sorting
256 Sorts according to the order of string prefixes as given by
257 `order`. If `strict`, then if no matching prefix found, would
258 raise KeyError; otherwise provides least priority to those keys
259 which were not found in `order`
262 order = [v.lower() for v in order]
264 def prefix_index(t, order, strict=True, case=False):
268 for i, v in enumerate(order):
274 "Could not find location for %s as specified by %s" %
276 return 10000 # some large number ;)
278 cmp_res = cmp(prefix_index(x, order, strict, case),
279 prefix_index(y, order, strict, case))
280 if not cmp_res: # still unknown
285 def group_packages_into_tasks(pkgs):
286 """Given a list of packages (with .tasks) group them per each
287 task and perform necessary customizations stored in .tasks
289 # Time to take care about packages and tasks
290 # Unroll pkgs into a collection of pkgs per known task
293 # Lets just create deepcopies with tune-ups for each task
294 for itask, (task, fields) in enumerate(pkg.tasks.iteritems()):
298 # Perform string completions and removals
299 for k,v in pkg_.iteritems():
301 if v is None or not len(v.strip()):
304 # Sort the fields according to FIELDS_ORDER. Unfortunately
305 # silly Deb822* cannot create from list of tuples, so will do
307 pkg__ = deb822.Deb822()
308 for k,v in sorted(pkg_.items(),
310 key_prefix_compare(x, y, order=FIELDS_ORDER)):
313 # Move Pkg-source/name into attributes
314 pkg__.source = pkg__.pop('Pkg-Source')
315 pkg__.name = pkg__.pop('Pkg-name')
317 tasks[task] = tasks.get(task, []) + [pkg__]
318 verbose(4, "Grouped %d packages into %d tasks: %s" %
319 (len(pkgs), len(tasks), ', '.join(tasks.keys())))
322 def inject_tasks(tasks, config):
323 # Now go through task files and replace/add entries
324 for task, pkgs in tasks.iteritems():
325 verbose(2, "Task %s with %d packages" % (task, len(pkgs)))
326 blend, puretask = task.split('/')
327 taskfile = join(config.get(blend, 'path'), 'tasks', puretask)
330 stats = dict(Added=[], Modified=[])
332 msgs = {'Name': pkg.name.strip(), 'Action': None}
333 # Find either it is known to the task file already
335 # Load entirely so we could simply manipulate
336 entries = open(taskfile).readlines()
338 # We need to search by name and by source
339 # We need to search for every possible type of dependecy
340 regexp = re.compile('^ *(%s) *: *(%s) *$' %
341 ('|'.join(PKG_FIELDS),
342 '|'.join((pkg.name, pkg.source))),
344 for istart, e in enumerate(entries):
346 verbose(4, "Found %s in position %i: %s" %
347 (pkg.name, istart, e.rstrip()))
351 descr = ' ; Added by %s %s. [Please note here if modified manually]\n' % \
352 (__prog__, __version__)
353 # Replace existing entry
355 # TODO: Check if previous copy does not have our preceding comment
356 # Find the previous end
359 while entries[istart+icount].strip() != '':
361 except IndexError, e:
362 pass # if we go beyond
364 # Lets not change file without necessity, if entry is identical --
367 old_entry = entries[istart:istart+icount]
369 if u''.join(old_entry) == entry:
371 else: # Rewrite the entry
372 if __prog__ in entries[istart-1]:
375 if not 'Removed' in pkg.keys():
376 entries = entries[:istart] + [descr + entry] + entries[istart+icount:]
377 msgs['Action'] = 'Changed'
379 while entries[istart-1].strip() == '':
382 entries = entries[:istart] + entries[istart+icount:]
383 msgs['Action'] = 'Removed'
384 output = ''.join(entries) # 'compute' first
385 open(taskfile, 'w').write(output) # then only overwrite
386 elif not 'removed' in pkg: # or Append one
387 msgs['Action'] = 'Added'
388 # could be as simple as
389 output = '\n%s%s' % (descr, pkg.dump(),)
390 open(taskfile, 'a').write(output)
393 verbose(3, "%(Action)s %(Name)s" % msgs)
396 class DebianMaterials(object):
397 """Extract selected information from an existing debian/
399 _WNPP_RE = re.compile('^ *\* *Initial release.*closes:? #(?P<bug>[0-9]*).*', re.I)
401 def __init__(self, topdir):
402 #self.topdir = topdir
403 self._debiandir = join(topdir, 'debian')
405 self._binaries = None
409 if self._source is None:
410 self._assign_packages()
415 if self._binaries is None:
416 self._assign_packages()
417 return self._binaries
419 def fpath(self, name):
420 return join(self._debiandir, name)
422 def _assign_packages(self):
424 control = deb822.Deb822.iter_paragraphs(
425 open(self.fpath('control')))
428 "Cannot parse %s file necessary for the %s package entry. Error: %s"
429 % (control_file, pkg['Pkg-Name'], str(e)))
433 if v.get('Source', None):
436 self._binaries[v['Package']] = v
438 def get_license(self, package=None, first_only=True):
439 """Return a license(s). Parsed out from debian/copyright if it is
440 in machine readable format
443 # may be package should carry custom copyright file
444 copyright_file_ = self.fpath('%s.copyright' % package)
445 if package and exists(copyright_file_):
446 copyright_file = copyright_file_
448 copyright_file = self.fpath('copyright')
451 for p in deb822.Deb822.iter_paragraphs(open(copyright_file)):
452 if not 'Files' in p or p['Files'].strip().startswith('debian/'):
455 # Take only the short version of first line
456 l = re.sub('\n.*', '', l).strip()
459 if not l in licenses:
466 return ', '.join(licenses)
469 """Search for a template changelog entry closing "Initial bug
471 for l in open(self.fpath('changelog')):
472 rr = self._WNPP_RE.match(l)
474 return rr.groupdict()['bug']
477 def get_responsible(self):
478 """Returns responsible, atm -- maintainer
480 return self.source['Maintainer']
482 def get_vcsfields(self):
483 vcs = deb822.Deb822()
484 for f,v in self._source.iteritems():
485 if f.lower().startswith('vcs-'):
489 def get_description(self, pkg_name):
490 """Some logic to extract description.
492 If binary package matching pkg_name is found -- gets it description.
493 If no binary package with such name, and name matches source name,
494 obtain description of the first binary package.
496 if pkg_name in self.binaries:
498 elif pkg_name.lower() == self.source['Source'].lower():
499 pkg_name = self.binaries.keys()[0]
501 error("Name %s does not match any binary, nor source package in %s"
503 return self.binaries[pkg_name]['Description']
508 usage="%s [OPTIONS] [blends_files]\n\n" % __prog__ + __doc__,
509 version="%prog " + __version__)
512 Option("-d", "--topdir", action="store",
513 dest="topdir", default=None,
514 help="Top directory of a Debian package. It is used to locate "
515 "'debian/blends' if none is specified, and where to look for "
516 "extended information."))
519 Option("-c", "--config-file", action="store",
520 dest="config_file", default=join(expanduser('~'), '.%s.cfg' % __prog__),
521 help="Noise level."))
524 Option("-v", "--verbosity", action="store", type="int",
525 dest="verbosity", default=1, help="Noise level."))
527 (options, infiles) = p.parse_args()
528 global verbosity; verbosity = options.verbosity
531 infiles = [join(options.topdir or './', 'debian/blends')] # default one
534 config = ConfigParser()
535 config.read(options.config_file)
537 for blends_file in infiles:
538 verbose(1, "Processing %s" % blends_file)
539 if not exists(blends_file):
540 error("Cannot find a file %s. Either provide a file or specify top "
541 "debian directory with -d." % blends_file, 1)
542 pkgs = parse_debian_blends(blends_file)
543 if options.topdir is None:
544 if dirname(blends_file).endswith('/debian'):
545 topdir = dirname(dirname(blends_file))
547 topdir = '.' # and hope for the best ;)
549 topdir = options.topdir
550 expand_pkgs(pkgs, topdir=topdir)
551 tasks = group_packages_into_tasks(pkgs)
552 inject_tasks(tasks, config)
555 if __name__ == '__main__':