aboutsummaryrefslogtreecommitdiff
path: root/bootstrap.py
blob: 08506be0d975a1bc5d88b56b3ad3f44b49bf8ec0 (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
#!/usr/bin/python
# vim:fileencoding=utf-8:et:ts=4:sw=4:sts=4
#
# Copyright (C) 2013 Intel Corporation <markus.lehtonen@linux.intel.com>
#
# 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 2
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
"""Script for bootstrapping and updating the unittest data"""

import argparse
from fnmatch import fnmatch
from glob import glob
import logging
import os
import shutil
import subprocess
import sys
import tempfile

from tests.component.rpm import RepoManifest

LOG = logging.getLogger(os.path.basename(sys.argv[0]))
TEST_PKGS = {'gbp-test-native': {'build_branches': ['master'],
                                  'export_branches': ['master']},
             'gbp-test-native2': {'build_branches': ['master'],
                                  'export_branches': ['master']},
             'gbp-test': {'build_branches': ['master', 'fork'],
                          'export_branches': ['master', 'upstream']},
             'gbp-test2': {'build_branches': ['master'],
                           'export_branches': ['master', 'master-orphan',
                           'upstream']}}


class GitError(Exception):
    """Exception for git errors"""
    pass


class TestDataRepoManifest(RepoManifest):
    """Test repo manifest"""
    def add_project(self, name, branches):
        """Add new project to the manifest"""
        prj_e = self._doc.createElement('project')
        prj_e.setAttribute('name', name)
        for branch, revision in branches.iteritems():
            br_e = self._doc.createElement('branch')
            br_e.setAttribute('name', branch)
            br_e.setAttribute('revision', revision)
            prj_e.appendChild(br_e)
        self._doc.firstChild.appendChild(prj_e)


def run_cmd(cmd, opts=None, capture_stdout=False, capture_stderr=False):
    """Run command"""
    args = [cmd] + opts if opts else [cmd]
    stdout = subprocess.PIPE if capture_stdout else None
    stderr = subprocess.PIPE if capture_stderr else None
    LOG.debug("Running command: '%s'" % ' '.join(args))
    popen = subprocess.Popen(args, stdout=stdout, stderr=stderr)
    stdout, stderr = popen.communicate()
    ret_out = stdout.splitlines() if stdout else stdout
    ret_err = stderr.splitlines() if stderr else stderr
    return (popen.returncode, ret_out, ret_err)

def git_cmd(cmd, opts=None, capture_stdout=False):
    """Run git command"""
    git_opts = [cmd] + opts if opts else [cmd]
    ret, stdout, _stderr = run_cmd('git', git_opts, capture_stdout, True)
    if ret:
        raise GitError("Git cmd ('%s') failed!" % ('git ' + ' '.join(git_opts)))
    return stdout

def parse_args(argv=None):
    """Argument parser"""
    parser = argparse.ArgumentParser()
    parser.add_argument('--verbose', '-v', action='store_true',
                        help="Verbose output")
    parser.add_argument('--overwrite', '-o', action='store_true',
                        help="Overwrite existing files")
    parser.add_argument('--update-branches', choices=['no', 'yes', 'force'],
                        default='no',
                        help="Update branches from remote")
    parser.add_argument('--no-build', action='store_true',
                        help="Do not build the packages")
    parser.add_argument('--keep-tmp', '-k', action='store_true',
                        help="Do not remove the temporary data dir")
    parser.add_argument('--silent-build', '-s', action='store_true',
                        help="Silent build, i.e. no rpmbuild output shown")
    return parser.parse_args(argv)

def do_build(tag, builddir, silent_build=False):
    """Run git-buildpackage-rpm"""
    gbp_opts =  ['--git-ignore-new','--git-export=%s' % tag,
                 '--git-export-dir=%s' % builddir, '--git-ignore-branch']
    ret, out, _err = run_cmd('git-buildpackage-rpm', gbp_opts, True,
                             silent_build)
    if ret:
        for line in out:
            print line
        raise Exception('Building %s failed! Builddata can be found '
                        'in %s' % (tag, builddir))

def build_test_pkg(pkg_name, branch, outdir, silent_build=False):
    """Build the test package and extract unit test data"""
    LOG.info('Building package %s' % pkg_name)
    if branch == 'master':
        tag_pattern = 'srcdata/%s/release/*' % pkg_name
    else:
        tag_pattern = 'srcdata/%s/%s/release/*' % (pkg_name, branch)

    build_branch = 'srcdata/%s/%s' % (pkg_name, branch)
    # Check for hooks
    hooks = {}
    try:
        hook_py = git_cmd('show', ['%s:.bootstrap_hooks.py' % build_branch],
                          True)
        LOG.info('Loading bootstrap hooks')
        exec('.bootstrap_hooks.py', hooks, hooks)
    except GitError:
        LOG.debug('No hooks found for %s' % build_branch)
    tags = git_cmd('tag', ['-l', tag_pattern], True)
    for ind, tag in enumerate(tags):
        builddir = tempfile.mkdtemp(dir='.',
                                    prefix='build-%s-%s_' % (pkg_name, ind))
        do_build(tag, builddir, silent_build)

        # Run postbuild_all hook
        if 'postbuild' in hooks:
            LOG.info('Running postbuild_all() hook for %s / %s' %
                        (pkg_name, tag))
            hooks['postbuild'](builddir, tag, LOG)

        # Create subdirs
        orig_dir = '%s/%s' % (outdir, 'orig')
        if not os.path.isdir(orig_dir):
            os.mkdir(orig_dir)

        for fname in glob('%s/SRPMS/*rpm' % builddir):
            LOG.debug('Copying %s -> %s' % (fname, outdir))
            shutil.copy(fname, outdir)
        for fname in os.listdir('%s/SOURCES' % builddir):
            if (fnmatch(fname, 'gbp*tar.gz') or fnmatch(fname, 'gbp*tar.bz2') or
                    fnmatch(fname, 'gbp*zip')):
                LOG.debug('Copying %s -> %s' % (fname, orig_dir))

                shutil.copy('%s/SOURCES/%s' % (builddir, fname), orig_dir)
        shutil.rmtree(builddir)


def update_testrepo_manifest(manifest, pkg_name, branches):
    """
    Update a manifest file describing the branches/sha1s of a test git repo
    used by the gbp buildpackage-rpm and pq unit tests.
    """
    out_branches = {}
    for branch in branches:
        in_branch = 'srcdata/%s/%s' % (pkg_name, branch)
        sha = git_cmd('rev-parse', ['%s^0' % in_branch], True)[0]
        out_branches[branch] = sha.strip()
    manifest.add_project(pkg_name, out_branches)


def update_pkg_branches(pkg_name, remote, force=False):
    """Update srcdata branches"""
    brs = git_cmd('branch', ['-r', '--list', '%s/srcdata/%s/*' %
                    (remote, pkg_name)], True)
    branches = [brn.strip().split()[0].replace(remote + '/', '') for brn in brs]
    LOG.info("Updating local branches %s from '%s'" % (branches, remote))

    for branch in branches:
        git_cmd('checkout', [branch])
        remote_branch = '%s/%s' % (remote, branch)
        try:
            git_cmd('merge', ['--ff-only', remote_branch], True)
        except GitError:
            if force:
                LOG.warning('Doing hard reset for branch %s' % branch)
                git_cmd('reset', ['--hard', remote_branch], True)
            else:
                raise Exception('Failed to do fast-forward on %s' % branch)

def update_from_remote(remote, force=False):
    """Update srcdata branches from remote repo"""
    git_cmd('fetch', [remote])
    for pkg in TEST_PKGS:
        update_pkg_branches(pkg, remote, force=force)


def main(argv=None):
    """The main routine"""
    LOG.addHandler(logging.StreamHandler())
    LOG.setLevel(logging.INFO)

    args = parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)

    outdatadir = tempfile.mkdtemp(prefix='gbp_unittest_outdata_')

    # Get current branch / revision
    try:
        _cur_ref = git_cmd('symbolic-ref', ['HEAD'], True)[0].strip()
        orig_rev = _cur_ref.replace('refs/heads/', '')
    except GitError:
        orig_rev = git_cmd('rev-parse', ['HEAD'], True)[0].strip()

    try:
        if args.update_branches != 'no':
            force = True if args.update_branches == 'force' else False
            update_from_remote('origin', force=force)
        test_manifest = TestDataRepoManifest()
        for pkg, pkgconf in TEST_PKGS.iteritems():
            if 'export_branches' in pkgconf:
                update_testrepo_manifest(test_manifest, pkg,
                                         pkgconf['export_branches'])
            if not args.no_build:
                for branch in pkgconf['build_branches']:
                    build_test_pkg(pkg, branch, outdatadir, args.silent_build)

        # Copy all data
        test_manifest.write('test-repo-manifest.xml')
        for root, dirs, files in os.walk(outdatadir):
            relroot = os.path.relpath(root, outdatadir)
            for dname in dirs:
                relpath = '%s/%s' % (relroot, dname)
                if not os.path.isdir(relpath):
                    os.makedirs(relpath)
            for fname in files:
                relpath = '%s/%s' % (relroot, fname)
                if not os.path.exists(relpath) or args.overwrite:
                    shutil.copy('%s/%s' % (root, fname), relpath)
                else:
                    LOG.debug('Skipping %s' % relpath)
    finally:
        if args.keep_tmp:
            LOG.info('Sparing temporary directory: %s' % outdatadir)
        else:
            shutil.rmtree(outdatadir)
        git_cmd('checkout', [orig_rev])


if __name__ == '__main__':
    main()