예제 #1
0
    def spawn_dch(msg=[], author=None, email=None, newversion=False, version=None,
                  release=False, distribution=None, dch_options=[]):
        """
        Spawn dch

        @param author: committers name
        @type author: C{str}
        @param email: committers email
        @type email: C{str}
        @param newversion: start a new version
        @type newversion: C{bool}
        @param version: the verion to use
        @type version: C{str}
        @param release: finalize changelog for releaze
        @type release: C{bool}
        @param distribution: distribution to use
        @type distribution: C{str}
        @param dch_options: options passed verbatim to dch
        @type dch_options: C{list}
        """
        env = {}
        args = ['--no-auto-nmu']
        if newversion:
            if version:
                try:
                    args.append(version['increment'])
                except KeyError:
                    args.append('--newversion=%s' % version['version'])
            else:
                args.append('-i')
        elif release:
            args.extend(["--release", "--no-force-save-on-release"])
            msg = None

        if author and email:
            env = {'DEBFULLNAME': author, 'DEBEMAIL': email}

        if distribution:
            args.append("--distribution=%s" % distribution)

        args.extend(dch_options)
        args.append('--')
        if msg:
            args.append('[[[insert-git-dch-commit-message-here]]]')
        else:
            args.append('')
        dch = Command('dch', args, extra_env=env)
        dch.call([])
        if msg:
            old_cl = open("debian/changelog", "r")
            new_cl = open("debian/changelog.bak", "w")
            for line in old_cl:
                if line == "  * [[[insert-git-dch-commit-message-here]]]\n":
                    print >> new_cl, "  * " + msg[0]
                    for line in msg[1:]:
                        print >> new_cl, "    " + line
                else:
                    print >> new_cl, line,
            os.rename("debian/changelog.bak", "debian/changelog")
 def test_log_quote_format(self, create_mock):
     self.false = Command('/does/{not}/matter')
     self.false.capture_stderr = True
     with self.assertRaises(CommandExecFailed):
         self.false.__call__()
     self.log_tester._check_log(0, "gbp:error: '/does/{not}/matter' failed: it exited with 1")
     self.assertEqual(self.false.retcode, 1)
     self.assertEqual(self.false.stderr, 'we have a problem')
     self.assertEqual(self.false.stdout, '')
예제 #3
0
def apt_showsrc(pkg):
    try:
        aptsrc = Command("apt-cache", ["showsrc", pkg], capture_stdout=True)
        aptsrc(quiet=True)
        return aptsrc.stdout
    except CommandExecFailed:
        return ''
예제 #4
0
    def setUpClass(cls):
        """Initializations only made once per test run"""
        super(RpmRepoTestBase, cls).setUpClass()

        # Initialize test data repositories
        cmd = Command('./manage.py',
                      cwd=RPM_TEST_DATA_DIR,
                      capture_stderr=True)
        cmd(['import-repo', '-o', cls._tmproot])

        cls.orig_repos = {}
        for path in glob(cls._tmproot + '/*.repo'):
            prj = os.path.basename(path).rsplit('.', 1)[0]
            cls.orig_repos[prj] = ComponentTestGitRepository(path)
예제 #5
0
class TestCommandWrapperFailures(unittest.TestCase, GbpLogTester):
    def setUp(self):
        self.false = Command('/does/not/matter')
        self.log_tester = GbpLogTester()
        self.log_tester._capture_log(True)

    def tearDown(self):
        self.log_tester._capture_log(False)

    @patch_popen(stdout='', stderr='', returncode=1)
    def test_log_default_error_msg(self, create_mock):
        with self.assertRaises(CommandExecFailed):
            self.false.__call__()
        self.log_tester._check_log(
            0, "gbp:error: '/does/not/matter' failed: it exited with 1")
        self.assertEqual(self.false.retcode, 1)
        self.assertEqual(self.false.stderr, '')
        self.assertEqual(self.false.stdout, '')

    @patch_popen(stdout='', stderr='we have a problem', returncode=1)
    def test_log_use_stderr_for_err_message(self, create_mock):
        self.false.capture_stderr = True
        self.false.run_error = "Erpel {stderr}"
        with self.assertRaises(CommandExecFailed):
            self.false.__call__()
        self.log_tester._check_log(0, "gbp:error: Erpel we have a problem")
        self.assertEqual(self.false.retcode, 1)
        self.assertEqual(self.false.stderr, 'we have a problem')
        self.assertEqual(self.false.stdout, '')

    @patch_popen(stdout='we have a problem', stderr='', returncode=1)
    def test_log_use_stdout_for_err_message(self, create_mock):
        self.false.capture_stdout = True
        self.false.run_error = "Erpel {stdout}"
        with self.assertRaises(CommandExecFailed):
            self.false.__call__()
        self.log_tester._check_log(0, "gbp:error: Erpel we have a problem")
        self.assertEqual(self.false.retcode, 1)
        self.assertEqual(self.false.stderr, '')
        self.assertEqual(self.false.stdout, 'we have a problem')

    @patch_popen(returncode=0)
    def test_no_log_on_success(self, create_mock):
        self.false.__call__()
        self.log_tester._check_log_empty()
        self.assertEqual(self.false.retcode, 0)
예제 #6
0
def clean_working_tree(options, repo):
    """
    Clean the working tree.

    :param options: Program run-time options, as an `optparse.OptionContainer`.
    :param repo: The Git repository, as a `DebianGitRepository`.
    :raise GbpError: When the working tree has uncommitted changes.
    :return: None.
    """
    Command(options.cleaner, shell=True)()
    if not options.ignore_new:
        (ret, out) = repo.is_clean()
        if not ret:
            gbp.log.err("You have uncommitted changes in your source tree:")
            gbp.log.err(out)
            raise GbpError("Use --git-ignore-new to ignore.")
class TestCommandWrapperFailures(unittest.TestCase, GbpLogTester):
    def setUp(self):
        self.false = Command('/does/not/matter')
        self.log_tester = GbpLogTester()
        self.log_tester._capture_log(True)

    def tearDown(self):
        self.log_tester._capture_log(False)

    @patch_popen(stdout='', stderr='', returncode=1)
    def test_log_default_error_msg(self, create_mock):
        with self.assertRaises(CommandExecFailed):
            self.false.__call__()
        self.log_tester._check_log(0, "gbp:error: '/does/not/matter' failed: it exited with 1")
        self.assertEqual(self.false.retcode, 1)
        self.assertEqual(self.false.stderr, '')
        self.assertEqual(self.false.stdout, '')

    @patch_popen(stdout='', stderr='we have a problem', returncode=1)
    def test_log_use_stderr_for_err_message(self, create_mock):
        self.false.capture_stderr = True
        self.false.run_error = "Erpel {stderr}"
        with self.assertRaises(CommandExecFailed):
            self.false.__call__()
        self.log_tester._check_log(0, "gbp:error: Erpel we have a problem")
        self.assertEqual(self.false.retcode, 1)
        self.assertEqual(self.false.stderr, 'we have a problem')
        self.assertEqual(self.false.stdout, '')

    @patch_popen(stdout='we have a problem', stderr='', returncode=1)
    def test_log_use_stdout_for_err_message(self, create_mock):
        self.false.capture_stdout = True
        self.false.run_error = "Erpel {stdout}"
        with self.assertRaises(CommandExecFailed):
            self.false.__call__()
        self.log_tester._check_log(0, "gbp:error: Erpel we have a problem")
        self.assertEqual(self.false.retcode, 1)
        self.assertEqual(self.false.stderr, '')
        self.assertEqual(self.false.stdout, 'we have a problem')

    @patch_popen(returncode=0)
    def test_no_log_on_success(self, create_mock):
        self.false.__call__()
        self.log_tester._check_log_empty()
        self.assertEqual(self.false.retcode, 0)
 def setUp(self):
     self.false = Command('/does/not/matter')
     self.log_tester = GbpLogTester()
     self.log_tester._capture_log(True)
예제 #9
0
    def spawn_dch(msg=[], author=None, email=None, newversion=False, version=None,
                  release=False, distribution=None, dch_options=[]):
        """
        Spawn dch

        @param author: committers name
        @type author: C{str}
        @param email: committers email
        @type email: C{str}
        @param newversion: start a new version
        @type newversion: C{bool}
        @param version: the verion to use
        @type version: C{str}
        @param release: finalize changelog for releaze
        @type release: C{bool}
        @param distribution: distribution to use
        @type distribution: C{str}
        @param dch_options: options passed verbatim to dch
        @type dch_options: C{list}
        """
        env = {}
        args = ['--no-auto-nmu']
        if newversion:
            if version:
                try:
                    args.append(version['increment'])
                except KeyError:
                    args.append('--newversion=%s' % version['version'])
            else:
                args.append('-i')
        elif release:
            args.extend(["--release", "--no-force-save-on-release"])
            msg = None

        if author:
            env['DEBFULLNAME'] = author
        if email:
            env['DEBEMAIL'] = email

        if distribution:
            args.append("--distribution=%s" % distribution)

        args.extend(dch_options)
        args.append('--')
        if msg:
            args.append('[[[insert-git-dch-commit-message-here]]]')
        else:
            args.append('')
        dch = Command('debchange', args, extra_env=env)
        dch([], quiet=True)
        if msg:
            old_cl = open("debian/changelog", "r")
            new_cl = open("debian/changelog.bak", "w")
            for line in old_cl:
                if line == "  * [[[insert-git-dch-commit-message-here]]]\n":
                    print("  * " + msg[0], file=new_cl)
                    for line in msg[1:]:
                        print("    " + line, file=new_cl)
                else:
                    print(line, end='', file=new_cl)
            os.rename("debian/changelog.bak", "debian/changelog")
def main(argv):
    """Entry point for gbp-buildpackage-rpm"""
    retval = 0
    prefix = "git-"
    spec = None

    options, gbp_args, builder_args = parse_args(argv, prefix)

    if not options:
        return 1

    try:
        repo = RpmGitRepository(os.path.curdir)
    except GitRepositoryError:
        gbp.log.err("%s is not a git repository" % (os.path.abspath('.')))
        return 1

    # Determine tree-ish to be exported
    try:
        tree = get_tree(repo, options.export)
    except GbpError as err:
        gbp.log.err('Failed to determine export treeish: %s' % err)
        return 1
    # Re-parse config options with using the per-tree config file(s) from the
    # exported tree-ish
    options, gbp_args, builder_args = parse_args(argv, prefix, tree)

    branch = get_current_branch(repo)

    try:
        init_tmpdir(options.tmp_dir, prefix='buildpackage-rpm_')

        tree = get_tree(repo, options.export)
        spec = parse_spec(options, repo, treeish=tree)

        Command(options.cleaner, shell=True)()
        if not options.ignore_new:
            ret, out = repo.is_clean()
            if not ret:
                gbp.log.err(
                    "You have uncommitted changes in your source tree:")
                gbp.log.err(out)
                raise GbpError("Use --git-ignore-new to ignore.")

        if not options.ignore_new and not options.ignore_branch:
            if branch != options.packaging_branch:
                gbp.log.err("You are not on branch '%s' but on '%s'" %
                            (options.packaging_branch, branch))
                raise GbpError(
                    "Use --git-ignore-branch to ignore or "
                    "--git-packaging-branch to set the branch name.")

        # Dump from git to a temporary directory:
        packaging_tree = '%s:%s' % (tree, options.packaging_dir)
        dump_dir = tempfile.mkdtemp(prefix='packaging_')
        gbp.log.debug("Dumping packaging files to '%s'" % dump_dir)
        if not dump_tree(repo, dump_dir, packaging_tree, False, False):
            raise GbpError
        # Re-parse spec from dump dir to get version etc.
        spec = rpm.SpecFile(os.path.join(dump_dir, spec.specfile))

        if not options.tag_only:
            # Setup builder opts
            setup_builder(options, builder_args)
            if options.use_mock:
                setup_mock(options)

            # Prepare final export dirs
            export_dir = makedir(options.export_dir)
            source_dir = makedir(
                os.path.join(export_dir, options.export_sourcedir))
            spec_dir = makedir(os.path.join(export_dir,
                                            options.export_specdir))

            # Move packaging files to final export dir
            gbp.log.debug("Exporting packaging files from '%s' to '%s'" %
                          (dump_dir, export_dir))
            for fname in os.listdir(dump_dir):
                src = os.path.join(dump_dir, fname)
                if fname == spec.specfile:
                    dst = os.path.join(spec_dir, fname)
                else:
                    dst = os.path.join(source_dir, fname)
                try:
                    shutil.copy2(src, dst)
                except IOError as err:
                    raise GbpError("Error exporting packaging files: %s" % err)
            spec.specdir = os.path.abspath(spec_dir)

            # Get/build the orig tarball
            if is_native(repo, options):
                if spec.orig_src and not options.no_create_orig:
                    # Just build source archive from the exported tree
                    gbp.log.info(
                        "Creating (native) source archive %s from '%s'" %
                        (spec.orig_src['filename'], tree))
                    if spec.orig_src['compression']:
                        gbp.log.debug(
                            "Building source archive with "
                            "compression '%s -%s'" %
                            (spec.orig_src['compression'], options.comp_level))
                    orig_prefix = spec.orig_src['prefix']
                    if not git_archive(repo, spec, source_dir, tree,
                                       orig_prefix, options.comp_level,
                                       options.with_submodules):
                        raise GbpError("Cannot create source tarball at '%s'" %
                                       source_dir)
            # Non-native packages: create orig tarball from upstream
            elif spec.orig_src:
                prepare_upstream_tarball(repo, spec, options, source_dir)

            # Run postexport hook
            if options.postexport:
                RunAtCommand(options.postexport,
                             shell=True,
                             extra_env={
                                 'GBP_GIT_DIR': repo.git_dir,
                                 'GBP_TMP_DIR': export_dir
                             })(dir=export_dir)
            # Do actual build
            if not options.no_build and not options.tag_only:
                if options.prebuild:
                    RunAtCommand(options.prebuild,
                                 shell=True,
                                 extra_env={
                                     'GBP_GIT_DIR': repo.git_dir,
                                     'GBP_BUILD_DIR': export_dir
                                 })(dir=export_dir)

                # Finally build the package:
                if options.builder.startswith("rpmbuild"):
                    builder_args.append(
                        os.path.join(spec.specdir, spec.specfile))
                else:
                    builder_args.append(spec.specfile)
                RunAtCommand(options.builder,
                             builder_args,
                             shell=True,
                             extra_env={'GBP_BUILD_DIR':
                                        export_dir})(dir=export_dir)
                if options.postbuild:
                    changes = os.path.abspath("%s/%s.changes" %
                                              (source_dir, spec.name))
                    gbp.log.debug("Looking for changes file %s" % changes)
                    Command(options.postbuild,
                            shell=True,
                            extra_env={
                                'GBP_CHANGES_FILE': changes,
                                'GBP_BUILD_DIR': export_dir
                            })()

        # Tag (note: tags the exported version)
        if options.tag or options.tag_only:
            gbp.log.info("Tagging %s" % rpm.compose_version_str(spec.version))
            tag = create_packaging_tag(repo, tree, spec.name, spec.version,
                                       options)
            vcs_info = get_vcs_info(repo, tag)
            if options.posttag:
                sha = repo.rev_parse("%s^{}" % tag)
                Command(options.posttag,
                        shell=True,
                        extra_env={
                            'GBP_TAG': tag,
                            'GBP_BRANCH': branch,
                            'GBP_SHA1': sha
                        })()
        else:
            vcs_info = get_vcs_info(repo, tree)

    except CommandExecFailed:
        retval = 1
    except GitRepositoryError as err:
        gbp.log.err("Git command failed: %s" % err)
        retval = 1
    except GbpAutoGenerateError as err:
        if len(err.__str__()):
            gbp.log.err(err)
        retval = 2
    except GbpError as err:
        if len(err.__str__()):
            gbp.log.err(err)
        retval = 1
    finally:
        drop_index()
        del_tmpdir()

    if not options.tag_only:
        if spec and options.notify:
            summary = "Gbp-rpm %s" % ["failed", "successful"][not retval]
            message = ("Build of %s %s %s" %
                       (spec.name, rpm.compose_version_str(
                           spec.version), ["failed", "succeeded"][not retval]))
            if not gbp.notifications.notify(summary, message, options.notify):
                gbp.log.err("Failed to send notification")
                retval = 1

    return retval
예제 #11
0
def main(argv):
    retval = 0
    current = None

    (options, args) = parse_args(argv)
    if not options:
        return 1

    gbp.log.setup(options.color, options.verbose, options.color_scheme)

    try:
        repo = GitRepository(os.path.curdir)
    except GitRepositoryError:
        gbp.log.err("%s is not a git repository" % (os.path.abspath('.')))
        return 1

    try:
        branches = set()
        try:
            current = repo.get_branch()
        except GitRepositoryError:
            # Not being on any branch is o.k. with --git-ignore-branch
            if options.ignore_branch:
                current = repo.head
                gbp.log.info("Found detached head at '%s'" % current)
            else:
                raise

        for branch in [options.packaging_branch, options.upstream_branch]:
            if repo.has_branch(branch):
                branches.add(branch)

        if repo.has_pristine_tar_branch() and options.pristine_tar:
            branches.add(repo.pristine_tar_branch)

        if options.all:
            current_remote = repo.get_merge_branch(current)
            if current_remote:
                fetch_remote = current_remote.split('/')[0]
            else:
                fetch_remote = 'origin'
            for branch in repo.get_local_branches():
                merge_branch = repo.get_merge_branch(branch)
                if merge_branch:
                    rem, rem_br = merge_branch.split('/', 1)
                    if rem == fetch_remote and branch == rem_br:
                        branches.add(branch)

        (ret, out) = repo.is_clean()
        if not ret:
            gbp.log.err("You have uncommitted changes in your source tree:")
            gbp.log.err(out)
            raise GbpError

        repo.fetch(depth=options.depth)
        repo.fetch(depth=options.depth, tags=True)
        for branch in branches:
            if not update_branch(branch, repo, options):
                retval = 2

        if options.redo_pq:
            repo.set_branch(options.packaging_branch)
            Command("gbp-pq")(["drop"])
            Command("gbp-pq")(["import"])

        repo.set_branch(current)
    except CommandExecFailed:
        retval = 1
    except (GbpError, GitRepositoryError) as err:
        if len(err.__str__()):
            gbp.log.err(err)
        retval = 1

    return retval
def main(argv):
    """Entry point for git-buildpackage-bb"""
    retval = 0
    prefix = "git-"
    bbfile = None
    dump_dir = None

    if not bb:
        return 1

    options, gbp_args, builder_args = parse_args(argv, prefix)
    if not options:
        return 1

    try:
        repo = RpmGitRepository(os.path.curdir)
    except GitRepositoryError:
        gbp.log.err("%s is not a git repository" % (os.path.abspath('.')))
        return 1

    # Determine tree-ish to be exported
    try:
        tree = get_tree(repo, options.export)
    except GbpError as err:
        gbp.log.err('Failed to determine export treeish: %s' % err)
        return 1
    # Re-parse config options with using the per-tree config file(s) from the
    # exported tree-ish
    options, gbp_args, builder_args = parse_args(argv, prefix, tree)

    branch = get_current_branch(repo)

    try:
        tinfoil = init_tinfoil(config_only=True)
        #bb_cfg_data = bb.data.createCopy(tinfoil.config_data)
    except GbpError:
        tinfoil = None

    # Use naive parsing because repository might only have .bb file
    gbp.log.info("Using naive standalone parsing of recipes in package repo.")
    bb_cfg_data = None

    try:
        tree = guess_export_params(repo, options)

        Command(options.cleaner, shell=True)()
        if not options.ignore_new:
            (ret, out) = repo.is_clean(options.ignore_untracked)
            if not ret:
                gbp.log.err("You have uncommitted changes in your source tree:")
                gbp.log.err(out)
                raise GbpError("Use --git-ignore-new or --git-ignore-untracked "
                               "to ignore.")

        if not options.ignore_new and not options.ignore_branch:
            if branch != options.packaging_branch:
                gbp.log.err("You are not on branch '%s' but on '%s'" %
                            (options.packaging_branch, branch))
                raise GbpError("Use --git-ignore-branch to ignore or "
                               "--git-packaging-branch to set the branch name.")

        if not options.tag_only:
            # Dump/parse meta to export dir
            if options.export_dir:
                export_dir = os.path.abspath(options.export_dir)
            else:
                export_dir = guess_export_dir(options, tinfoil, repo, tree)
            gbp.log.info("Dumping meta from tree '%s' to '%s'" %
                            (options.export, export_dir))
            bbfile = dump_meta(bb_cfg_data, options, repo, tree,
                                 export_dir)

            # Setup builder opts
            setup_builder(options, builder_args)

            if is_native(repo, options) and bbfile.getVar('SRCREV') == 'HEAD':
                # Update SRCREV for native packages that are exported from
                # pristine repository
                BBFile.set_var_val(bbfile.bb_path, 'SRCREV',
                                   repo.rev_parse(tree))

                # TODO: Re-design the handling of native packages. Updating
                #       SRCREV must probably be more explicit
            if options.patch_export:
                # Generate patches, if requested
                if options.patch_export_rev:
                    patch_tree = get_tree(repo, options.patch_export_rev)
                else:
                    patch_tree = tree
                export_patches(repo, bbfile, patch_tree, options)

            # Run postexport hook
            if options.postexport:
                RunAtCommand(options.postexport, shell=True,
                             extra_env={'GBP_GIT_DIR': repo.git_dir,
                                        'GBP_TMP_DIR': export_dir}
                             )(dir=export_dir)
            # Do actual build
            if not options.no_build:
                if options.prebuild:
                    RunAtCommand(options.prebuild, shell=True,
                                 extra_env={'GBP_GIT_DIR': repo.git_dir,
                                            'GBP_BUILD_DIR': export_dir}
                                 )(dir=export_dir)

                # Unlock cooker so that we are able to run external bitbake
                if options.builder == 'bitbake' and tinfoil:
                    bb.utils.unlockfile(tinfoil.cooker.lock)

                # Finally build the package:
                bb_path = bbfile.getVar('FILE', True)
                builder_args.extend(['-b', bb_path])
                RunAtCommand(options.builder, builder_args, shell=True,
                             extra_env={'GBP_BUILD_DIR': export_dir})()

                if options.postbuild:
                    Command(options.postbuild, shell=True,
                            extra_env={'GBP_BUILD_DIR': export_dir})()
        else:
            # Tag-only: we just need to parse the meta
            bbfile = parse_bb(bb_cfg_data, options, repo, tree)

        # Tag (note: tags the exported version)
        if options.tag or options.tag_only:
            version = pkg_version(bbfile)
            gbp.log.info("Tagging %s" %
                         RpmPkgPolicy.compose_full_version(version))
            commit_info = repo.get_commit_info(tree)
            tag = packaging_tag_name(repo, version, commit_info, options)
            if options.retag and repo.has_tag(tag):
                repo.delete_tag(tag)
            create_packaging_tag(repo, tag, commit=tree, version=version,
                                 options=options)
            vcs_info = get_vcs_info(repo, tag)
            if options.posttag:
                sha = repo.rev_parse("%s^{}" % tag)
                Command(options.posttag, shell=True,
                        extra_env={'GBP_TAG': tag,
                                   'GBP_BRANCH': branch,
                                   'GBP_SHA1': sha})()
        else:
            vcs_info = get_vcs_info(repo, tree)
        # TODO: Put VCS information to recipe
        if options.bb_vcs_info:
            raise GbpError("Injecting VCS info into recipe not yet supported")

    except CommandExecFailed:
        retval = 1
    except GitRepositoryError as err:
        gbp.log.err("Git command failed: %s" % err)
        retval = 1
    except GbpAutoGenerateError as err:
        if len(err.__str__()):
            gbp.log.err(err)
        retval = 2
    except GbpError, err:
        if len(err.__str__()):
            gbp.log.err(err)
        retval = 1
예제 #13
0
    options, gbp_args, builder_args = parse_args(argv, prefix, tree)

    try:
        # Create base temporary directory for this run
        options.tmp_dir = tempfile.mkdtemp(dir=options.tmp_dir,
                                           prefix='buildpackage-rpm_')
    except GbpError, err:
        gbp.log.err(err)
        return 1

    branch = get_current_branch(repo)

    try:
        tree, relative_spec_path = guess_export_params(repo, options)

        Command(options.cleaner, shell=True)()
        if not options.ignore_new:
            (ret, out) = repo.is_clean(options.ignore_untracked)
            if not ret:
                gbp.log.err(
                    "You have uncommitted changes in your source tree:")
                gbp.log.err(out)
                raise GbpError, "Use --git-ignore-new or --git-ignore-untracked to ignore."

        if not options.ignore_new and not options.ignore_branch:
            if branch != options.packaging_branch:
                gbp.log.err("You are not on branch '%s' but on '%s'" %
                            (options.packaging_branch, branch))
                raise GbpError, "Use --git-ignore-branch to ignore or --git-packaging-branch to set the branch name."

        # Dump from git to a temporary directory:
예제 #14
0
    def spawn_dch(
        msg=[],
        author=None,
        email=None,
        newversion=False,
        version=None,
        release=False,
        distribution=None,
        dch_options=[],
    ):
        """
        Spawn dch

        @param author: committers name
        @type author: C{str}
        @param email: committers email
        @type email: C{str}
        @param newversion: start a new version
        @type newversion: C{bool}
        @param version: the verion to use
        @type version: C{str}
        @param release: finalize changelog for releaze
        @type release: C{bool}
        @param distribution: distribution to use
        @type distribution: C{str}
        @param dch_options: options passed verbatim to dch
        @type dch_options: C{list}
        """
        env = {}
        args = ["--no-auto-nmu"]
        if newversion:
            if version:
                try:
                    args.append(version["increment"])
                except KeyError:
                    args.append("--newversion=%s" % version["version"])
            else:
                args.append("-i")
        elif release:
            args.extend(["--release", "--no-force-save-on-release"])
            msg = None

        if author:
            env["DEBFULLNAME"] = author
        if email:
            env["DEBEMAIL"] = email

        if distribution:
            args.append("--distribution=%s" % distribution)

        args.extend(dch_options)
        args.append("--")
        if msg:
            args.append("[[[insert-git-dch-commit-message-here]]]")
        else:
            args.append("")
        dch = Command("debchange", args, extra_env=env)
        dch.call([])
        if msg:
            old_cl = open("debian/changelog", "r")
            new_cl = open("debian/changelog.bak", "w")
            for line in old_cl:
                if line == "  * [[[insert-git-dch-commit-message-here]]]\n":
                    print("  * " + msg[0], file=new_cl)
                    for line in msg[1:]:
                        print("    " + line, file=new_cl)
                else:
                    print(line, end="", file=new_cl)
            os.rename("debian/changelog.bak", "debian/changelog")
예제 #15
0
def main(argv):
    retval = 0
    prefix = "git-"
    source = None
    branch = None

    options, gbp_args, dpkg_args = parse_args(argv, prefix)

    if not options:
        return 1

    try:
        repo = DebianGitRepository(os.path.curdir)
    except GitRepositoryError:
        gbp.log.err("%s is not a git repository" % (os.path.abspath('.')))
        return 1
    else:
        repo_dir = os.path.abspath(os.path.curdir)

    try:
        Command(options.cleaner, shell=True)()
        if not options.ignore_new:
            (ret, out) = repo.is_clean()
            if not ret:
                gbp.log.err(
                    "You have uncommitted changes in your source tree:")
                gbp.log.err(out)
                raise GbpError("Use --git-ignore-new to ignore.")

        try:
            branch = repo.get_branch()
        except GitRepositoryError:
            # Not being on any branch is o.k. with --git-ignore-branch
            if not options.ignore_branch:
                raise

        if not options.ignore_new and not options.ignore_branch:
            if branch != options.debian_branch:
                gbp.log.err("You are not on branch '%s' but on '%s'" %
                            (options.debian_branch, branch))
                raise GbpError(
                    "Use --git-ignore-branch to ignore or --git-debian-branch to set the branch name."
                )

        tree = write_tree(repo, options)
        source = source_vfs(repo, options, tree)
        if not options.tag_only:
            output_dir = prepare_output_dir(options.export_dir)
            tarball_dir = options.tarball_dir or output_dir

            # Get/build the upstream tarball if necessary. We delay this in
            # case of a postexport hook so the hook gets a chance to modify the
            # sources and create different tarballs (#640382)
            # We don't delay it in general since we want to fail early if the
            # tarball is missing.
            if not source.is_native():
                if options.postexport:
                    gbp.log.info(
                        "Postexport hook set, delaying tarball creation")
                else:
                    prepare_upstream_tarball(repo, source.changelog, options,
                                             tarball_dir, output_dir)

            # Export to another build dir if requested:
            if options.export_dir:
                tmp_dir = os.path.join(output_dir, "%s-tmp" % source.sourcepkg)
                export_source(repo, tree, source, options, tmp_dir, output_dir)

                # Run postexport hook
                if options.postexport:
                    RunAtCommand(options.postexport,
                                 shell=True,
                                 extra_env={
                                     'GBP_GIT_DIR': repo.git_dir,
                                     'GBP_TMP_DIR': tmp_dir
                                 })(dir=tmp_dir)

                major = (source.changelog.debian_version if source.is_native()
                         else source.changelog.upstream_version)
                export_dir = os.path.join(output_dir,
                                          "%s-%s" % (source.sourcepkg, major))
                gbp.log.info("Moving '%s' to '%s'" % (tmp_dir, export_dir))
                move_old_export(export_dir)
                os.rename(tmp_dir, export_dir)

                # Delayed tarball creation in case a postexport hook is used:
                if not source.is_native() and options.postexport:
                    prepare_upstream_tarball(repo, source.changelog, options,
                                             tarball_dir, output_dir)

            if options.export_dir:
                build_dir = export_dir
            else:
                build_dir = repo_dir

            if options.prebuild:
                RunAtCommand(options.prebuild,
                             shell=True,
                             extra_env={
                                 'GBP_GIT_DIR': repo.git_dir,
                                 'GBP_BUILD_DIR': build_dir
                             })(dir=build_dir)

            setup_pbuilder(options)
            # Finally build the package:
            RunAtCommand(options.builder,
                         dpkg_args,
                         shell=True,
                         extra_env={'GBP_BUILD_DIR': build_dir})(dir=build_dir)
            if options.postbuild:
                changes = os.path.abspath(
                    "%s/../%s_%s_%s.changes" %
                    (build_dir, source.sourcepkg, source.changelog.noepoch,
                     changes_file_suffix(dpkg_args)))
                gbp.log.debug("Looking for changes file %s" % changes)
                Command(options.postbuild,
                        shell=True,
                        extra_env={
                            'GBP_CHANGES_FILE': changes,
                            'GBP_BUILD_DIR': build_dir
                        })()
        if options.tag or options.tag_only:
            gbp.log.info("Tagging %s" % source.changelog.version)
            tag = repo.version_to_tag(options.debian_tag,
                                      source.changelog.version)
            if options.retag and repo.has_tag(tag):
                repo.delete_tag(tag)
            repo.create_tag(name=tag,
                            msg="%s Debian release %s" %
                            (source.sourcepkg, source.changelog.version),
                            sign=options.sign_tags,
                            keyid=options.keyid)
            if options.posttag:
                sha = repo.rev_parse("%s^{}" % tag)
                Command(options.posttag,
                        shell=True,
                        extra_env={
                            'GBP_TAG': tag,
                            'GBP_BRANCH': branch or '(no branch)',
                            'GBP_SHA1': sha
                        })()
    except CommandExecFailed:
        retval = 1
    except (GbpError, GitRepositoryError) as err:
        if len(err.__str__()):
            gbp.log.err(err)
        retval = 1
    except DebianSourceError as err:
        gbp.log.err(err)
        source = None
        retval = 1
    finally:
        drop_index()

    if not options.tag_only:
        if options.export_dir and options.purge and not retval:
            RemoveTree(export_dir)()

        if source and not gbp.notifications.notify(source.changelog,
                                                   not retval, options.notify):
            gbp.log.err("Failed to send notification")
            retval = 1

    return retval
예제 #16
0
def main(argv):
    retval = 0
    current = None
    rem_repo = None

    (options, args) = parse_args(argv)
    if not options:
        return ExitCodes.parse_error

    gbp.log.setup(options.color, options.verbose, options.color_scheme)

    if len(args) == 2:
        rem_repo = args[1]
        gbp.log.info("Fetching from '%s'" % rem_repo)
    else:
        gbp.log.info("Fetching from default remote for each branch")

    try:
        repo = DebianGitRepository(os.path.curdir)
    except GitRepositoryError:
        gbp.log.err("%s is not a git repository" % (os.path.abspath('.')))
        return 1

    try:
        branches = []
        try:
            current = repo.get_branch()
        except GitRepositoryError:
            # Not being on any branch is o.k. with --git-ignore-branch
            if options.ignore_branch:
                current = repo.head
                gbp.log.info("Found detached head at '%s'" % current)
            else:
                raise

        for branch in [options.debian_branch, options.upstream_branch]:
            if repo.has_branch(branch):
                branches += [branch]

        if repo.has_pristine_tar_branch() and options.pristine_tar:
            branches += [repo.pristine_tar_branch]

        (ret, out) = repo.is_clean()
        if not ret:
            gbp.log.err("You have uncommitted changes in your source tree:")
            gbp.log.err(out)
            raise GbpError

        repo.fetch(rem_repo, depth=options.depth)
        repo.fetch(rem_repo, depth=options.depth, tags=True)
        for branch in branches:
            if not fast_forward_branch(rem_repo, branch, repo, options):
                retval = 2

        if options.redo_pq:
            repo.set_branch(options.debian_branch)
            Command("gbp-pq")(["drop"])
            Command("gbp-pq")(["import"])

        repo.set_branch(current)
    except KeyboardInterrupt:
        retval = 1
        gbp.log.err("Interrupted. Aborting.")
    except CommandExecFailed:
        retval = 1
    except (GbpError, GitRepositoryError) as err:
        if str(err):
            gbp.log.err(err)
        retval = 1

    return retval
예제 #17
0
    def spawn_dch(msg=[], author=None, email=None, newversion=False, version=None,
                  release=False, distribution=None, dch_options=None):
        """
        Spawn dch

        @param author: committers name
        @type author: C{str}
        @param email: committers email
        @type email: C{str}
        @param newversion: start a new version
        @type newversion: C{bool}
        @param version: the verion to use
        @type version: C{str}
        @param release: finalize changelog for releaze
        @type release: C{bool}
        @param distribution: distribution to use
        @type distribution: C{str}
        @param dch_options: options passed verbatim to dch
        @type dch_options: C{list}
        """
        env = {}
        args = ['--no-auto-nmu']
        if newversion:
            if version:
                try:
                    args.append(version['increment'])
                except KeyError:
                    args.append('--newversion=%s' % version['version'])
            else:
                args.append('-i')
        elif release:
            args.extend(["--release", "--no-force-save-on-release"])
            msg = None

        if author:
            env['DEBFULLNAME'] = author.encode('utf-8')
        if email:
            env['DEBEMAIL'] = email.encode('utf-8')

        if distribution:
            args.append("--distribution=%s" % distribution)

        args.extend(dch_options or [])

        if '--create' in args:
            env['EDITOR'] = env['VISUAL'] = '/bin/true'

        args.append('--')
        if msg:
            args.append('[[[insert-git-dch-commit-message-here]]]')
        else:
            args.append('')
        dch = Command('debchange', args, extra_env=env, capture_stderr=True)
        dch.run_error = Command._f("Dch failed: {stderr_or_reason}")
        dch([], quiet=True)
        if msg:
            old_cl = open("debian/changelog", "r", encoding='utf-8')
            new_cl = open("debian/changelog.bak", "w", encoding='utf-8')
            for line in old_cl:
                if line == "  * [[[insert-git-dch-commit-message-here]]]\n":
                    print("  * " + msg[0], file=new_cl)
                    for line in msg[1:]:
                        print("    " + line, file=new_cl)
                else:
                    print(line, end='', file=new_cl)
            os.rename("debian/changelog.bak", "debian/changelog")