summaryrefslogtreecommitdiff
path: root/unperish
blob: 33e8e8555343e3cafbfb476625be667b952b7782 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/python
# Copyright 2011  Lars Wirzenius
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import cliapp
import ConfigParser
import debian.changelog
import debian.deb822
import glob
import logging
import os
import re
import shutil
import subprocess
import tempfile


__version__ = '0.0'


class Unperish(cliapp.Application):

    def add_settings(self):
        self.settings.boolean(['verbose', 'v'], 
                              'print commands that are executed')
        self.settings.boolean(['no-act', 'dry-run', 'n'], 
                              'don\'t run commands')
        self.settings.string(['build-area'], 
                             'where should results go? (%default)',
                             default='../build-area')
        self.settings.string_list(['basetgz'], 
                                  'list of pbuilder basetgz tarballs to use, '
                                    'optionally prefix with upload target and '
                                    'architechture, separated by colons '
                                    '(%default)',
                                  default=['/var/cache/pbuilder/base.tgz'])
        self.settings.string(['dsc'], 
                             'Debian source package (for dget command)',
                             metavar='URL')
        self.settings.string(['debian-version'], 
                             'Debian version number (typically detected '
                                'from debian/changelog)')
        self.settings.string(['debian-source'], 
                             'Debian source package name (typically detected '
                                'from debian/control)')
        self.settings.string(['web-directory'],
                             'put files to go on the web in DIR',
                             metavar='DIR')
        self.settings.string_list(['rsync-glob'], 
                                  'publish files matching GLOB with rsync',
                                  metavar='GLOB')
        self.settings.string_list(['rsync-to'], 
                                  'publish files with rsync to LOCATION',
                                  metavar='LOCATION')
        self.settings.choice(['full-source'], ['auto', 'yes', 'no'],
                             'include full source in upload?')
        self.settings.boolean(['binary-arch'], 
                              'build arch-specific packages only, '
                                'not arch:all')
        self.settings.string(['upstream-name'], 'upstream name for project')
        self.settings.string(['upstream-version'], 
                             'upstream version for project')

        self.settings.boolean(['use-uncommitted'], 'use uncommited changes')

        self.settings.config_files += ['project.meta']
    
    def process_args(self, args):
        self.deduce_unset_settings()
        self.create_build_area()
        
        self.already = set()
        for arg in args:
            self.run_subcommand(arg)

    def run_subcommand(self, subcommand, force=False):
        if force or subcommand not in self.already:
            self.already.add(subcommand)

            if subcommand in self.subcommands:
                method = self.subcommands[subcommand]
                if self.settings['verbose']:
                    self.output.write('command: %s\n' % subcommand)
                if not self.settings['no-act']:
                    method([])
            else:
                raise cliapp.AppException('unknown command %s' % subcommand)

    def deduce_unset_settings(self):

        def deduce_upstream_name():
            if os.path.exists('setup.py'):
                return self.runcmd(['python', 'setup.py', '--name']).strip()
            return ''

        def deduce_upstream_version():
            if os.path.exists('setup.py'):
                return self.runcmd(['python', 'setup.py', '--version']).strip()
            return ''
            
        table = {
            'upstream-name': deduce_upstream_name,
            'upstream-version': deduce_upstream_version,
        }
        
        for name in table:
            if not self.settings[name]:
                self.settings[name] = table[name]()

    def create_build_area(self):
        if not os.path.exists(self.settings['build-area']):
            os.mkdir(self.settings['build-area'])

    @property
    def upstream_name(self):
        return self.settings['upstream-name']

    @property
    def upstream_version(self):
        return self.settings['upstream-version']

    @property
    def upstream_tarball(self):
        return '%s-%s.tar.gz' % (self.upstream_name, self.upstream_version)

    @property
    def debian_control(self):
        with open(self.join(self.dirname, 'debian', 'control')) as f:
            return debian.deb822.Deb822(f)

    @property
    def debian_changelog(self):
        with open(self.join(self.dirname, 'debian', 'changelog')) as f:
            return debian.changelog.Changelog(f)

    @property
    def debian_source_package(self):
        if self.settings['debian-source']:
            return self.settings['debian-source']
        return self.debian_control['Source']

    @property
    def debian_version(self):
        if self.settings['debian-version']:
            return self.settings['debian-version']
        return str(self.debian_changelog.get_version())

    @property
    def debian_tarball(self):
        is_native = '-' not in self.debian_version
        if is_native:
            pattern = '%s_%s.tar.gz'
        else:
            pattern = '%s_%s.orig.tar.gz'
        return pattern % (self.debian_source_package, self.upstream_version)

    @property
    def dirname(self):
        return '%s-%s' % (self.upstream_name, self.upstream_version)

    @property
    def dsc(self):
        return '%s_%s.dsc' % (self.debian_source_package, self.debian_version)

    @property
    def arch(self):
        return self.runcmd(['dpkg', '--print-architecture']).strip()

    def changes(self, arch):
        return '%s_%s_%s.changes' % (self.debian_source_package, 
                                      self.debian_version,
                                      arch)

    def already_exists(self, filename):
        '''Does a file already exist?'''
        if os.path.exists(filename):
            logging.debug('Already exists: %s' % filename)
            return True
        else:
            logging.debug('Does not already exist: %s' % filename)
            return False

    def cmd_committed(self, args):
        '''Check that all changes have been committed.'''
        
        if not self.settings['use-uncommitted']:
            out = self.runcmd(['bzr', 'status'])
            if out:
                raise cliapp.AppException('Uncommitted changes:\n\n%s' % out)

    def cmd_dget(self, args):
        '''Retrieve a Debian source package (.dsc and other files).
        
        Put the files in the build area.
        
        '''
        
        if not self.settings['dsc']:
            raise cliapp.AppException('Need --dsc option for dget')
        
        basename = os.path.basename(self.settings['dsc'])
        if not self.already_exists(self.join(basename)):
            self.runcmd(['dget', '--download-only', self.settings['dsc']],
                        cwd=self.settings['build-area'])

    def cmd_export(self, args):
        '''Export unpacked source directory to build area.'''
        self.run_subcommand('committed')
        if not self.already_exists(self.join(self.dirname)):
            self.runcmd(['bzr', 'export', self.join(self.dirname)])
            if self.settings['use-uncommitted']:
                out = self.runcmd(['bzr', 'status', '--versioned', '--short'])
                for line in out.splitlines():
                    status, name = line.split()
                    target = self.join(self.dirname, name)
                    shutil.copy2(name, target)

    def cmd_debian_tarball(self, args):
        '''Generate Debian tarball (.orig.tar.gz) in build area.'''
        self.run_subcommand('committed')
        origtar = self.join(self.debian_tarball)
        if not self.already_exists(origtar):
            tempdir = tempfile.mkdtemp()
            exported = os.path.join(tempdir, os.path.basename(self.dirname))
            self.runcmd(['bzr', 'export', exported])
            shutil.rmtree(os.path.join(exported, 'debian'))
            self.runcmd(['tar', '-C', tempdir, '-czf', origtar,
                         os.path.basename(exported)])
            shutil.rmtree(tempdir)

    def cmd_dsc(self, args):
        '''Create Debian source package (.dsc) in build area.'''
        self.run_subcommand('export')
        self.run_subcommand('debian-tarball')
        if not self.already_exists(self.join(self.dsc)):
            self.runcmd(['dpkg-source', '-b', self.dirname], 
                        cwd=self.settings['build-area'])

    def cmd_deb(self, args):
        '''Build Debian binary packages (.deb) in build area.'''
        
        self.run_subcommand('export')

        targets = {}
        for spec in self.settings['basetgz']:
            target, arch, path = self.parse_basetgz(spec)
            targets[target] = targets.get(target, []) + [(arch, path)]
        for target in sorted(targets.keys()):
            if target:
                self.add_debian_changelog_entry(target)
            for arch, path in targets[target]:
                self.run_subcommand('dsc', force=True)
                if not self.already_exists(self.join(self.changes(arch))):
                    argv = ['sudo', 
                            'pbuilder', 
                            '--build', 
                            '--basetgz', path,
                            '--buildresult', self.settings['build-area'],
                            '--logfile', self.join('pbuilder.log')]
                    if self.include_source():
                        argv.extend(['--debbuildopts', '-sa'])
                    if self.settings['binary-arch']:
                        argv.append('--binary-arch')
                    argv.append(self.join(self.dsc))
                    self.runcmd(argv, cwd=self.settings['build-area'])
                
    def include_source(self):
        '''Should the upload include full source?'''
        if self.settings['full-source'] == 'yes':
            return True
        if self.settings['full-source'] == 'no':
            return False

        pat = r'-1$|[a-z]1$|^[^-]*$'
        return re.search(pat, self.debian_version) is not None

    def parse_basetgz(self, spec):
        parts = spec.split(':', 3)
        n = len(parts)

        if n == 1 or '/' in parts[0]:
            target = None
            arch = self.arch
            path = parts[0]
        elif n == 2:
            target = parts[0]
            arch = self.arch
            path = parts[1]
        elif n == 3 and '/' in parts[1]:
            target = parts[0]
            arch = self.arch
            path = ':'.join(parts[1:])
        else:
            target = parts[0]
            arch = parts[1]
            path = parts[2]
            
        return target, arch, path                

    def cmd_lintian(self, args):
        '''Run lintian on .changes/.deb/.dsc files.'''
        
        def find_them(suffixes):
            return [os.path.join(self.settings['build-area'], x)
                     for x in os.listdir(self.settings['build-area'])
                     if os.path.splitext(x)[1] in suffixes]
        
        files = find_them(['.changes'])
        if not files:
            files = find_them(['.deb', '.dsc'])

        out = self.runcmd(['lintian', '-i'] + files, ignore_fail=True,
                          cwd=self.settings['build-area'])
        self.output.write(out)
        
    def cmd_publish_docs(self, args):
        '''Publish docs related to this project.'''

        def publish(source, target_base):
            target = os.path.join(self.settings['web-directory'], target_base)
            if self.settings['verbose']:
                print 'Copying %s to %s' % (source, target)
            shutil.copyfile(source, target)
        
        if not self.settings['web-directory']:
            raise cliapp.AppException('Need --web-directory '
                                       'for publish-docs.')

        docs = ['README', 'NEWS']
        for doc in docs:
            doc = os.path.join(self.dirname, doc)
            if os.path.exists(doc):
                publish(doc, doc + '.mdwn')

        env = dict(os.environ)
        env['LC_ALL'] = 'C'
        for manpage in glob.glob(os.path.join(self.dirname, '*.[1-8]')):
            fmt = self.runcmd(['man', '-l', manpage], env=env)
            text = self.runcmd(['col', '-b'], stdin=fmt)
            fd, name = tempfile.mkstemp()
            os.write(fd, text)
            os.close(fd)
            publish(name, manpage + '.txt')
            os.remove(name)

    def cmd_rsync_publish(self, args):
        '''Publish files via rsync.'''
        
        filenames = []
        for pattern in self.settings['rsync-glob']:
            filenames += glob.glob(pattern)
        logging.debug('filenames: %s' % filenames)
        
        self.runcmd(['rsync', '-av', '--delete-after'] + filenames +
                     self.settings['rsync-to'])

    def cmd_clean(self, args):
        '''Clean up the build-area (remove everything except the dir).'''
        area = self.settings['build-area']
        if os.path.isdir(area):
            for x in os.listdir(area):
                pathname = os.path.join(area, x)
                if os.path.isdir(pathname):
                    shutil.rmtree(pathname)
                else:
                    os.remove(pathname)

    def add_debian_changelog_entry(self, target):
        msg = 'Build for %s.' % target
        self.runcmd(['dch', 
                     '--force-distribution',
                     '--local', '~' + target,
                     '--distribution', target,
                     '--preserve',
                     msg],
                    cwd=self.join(self.dirname))

    def join(self, *components):
        components = (self.settings['build-area'],) + components
        return os.path.join(*components)

    def runcmd(self, argv, *args, **kwargs):
        logging.debug('runcmd: argv: %s' % repr(argv))
        logging.debug('runcmd: args: %s' % repr(args))
        logging.debug('runcmd: kwargs: %s' % repr(kwargs))
        if self.settings['verbose']:
            self.output.write('run: %s\n' % ' '.join(argv))
        return cliapp.Application.runcmd(self, argv, *args, **kwargs)


if __name__ == '__main__':
    Unperish(version=__version__).run()