示例#1
0
def find_changelog(t, merge, max_blocks=1):
    """Find the changelog in the given tree.

    First looks for 'debian/changelog'. If "merge" is true will also
    look for 'changelog'.

    The returned changelog is created with 'allow_empty_author=True'
    as some people do this but still want to build.
    'max_blocks' defaults to 1 to try and prevent old broken
    changelog entries from causing the command to fail, 

    "top_level" is a subset of "merge" mode. It indicates that the
    '.bzr' dir is at the same level as 'changelog' etc., rather
    than being at the same level as 'debian/'.

    :param t: the Tree to look in.
    :param merge: whether this is a "merge" package.
    :param max_blocks: Number of max_blocks to parse (defaults to 1). Use None
        to parse the entire changelog.
    :return: (changelog, top_level) where changelog is the Changelog,
        and top_level is a boolean indicating whether the file is
        located at 'changelog' (rather than 'debian/changelog') if
        merge was given, False otherwise.
    """
    top_level = False
    with t.lock_read():
        changelog_file = 'debian/changelog'
        if not t.has_filename(changelog_file):
            checked_files = ['debian/changelog']
            if merge:
                # Assume LarstiQ's layout (.bzr in debian/)
                changelog_file = 'changelog'
                top_level = True
                if not t.has_filename(changelog_file):
                    checked_files.append(changelog_file)
                    changelog_file = None
            else:
                changelog_file = None
            if changelog_file is None:
                if getattr(t, "abspath", None):
                    checked_files = [t.abspath(f) for f in checked_files]
                raise MissingChangelogError(" or ".join(checked_files))
        elif merge and t.has_filename('changelog'):
            # If it is a "top_level" package and debian is a symlink to
            # "." then it will have found debian/changelog. Try and detect
            # this.
            if (t.is_versioned('debian') and
                t.kind('debian') == 'symlink' and
                t.get_symlink_target('debian') == '.'):
                changelog_file = 'changelog'
                top_level = True
        mutter("Using '%s' to get package information", changelog_file)
        if not t.is_versioned(changelog_file):
            raise AddChangelogError(changelog_file)
        contents = t.get_file_text(changelog_file)
    changelog = Changelog()
    try:
        changelog.parse_changelog(contents, max_blocks=max_blocks, allow_empty_author=True)
    except ChangelogParseError, e:
        raise UnparseableChangelog(str(e))
示例#2
0
def _parse_deb_project(changelog='debian/changelog'):
    clog = Changelog()
    try:
        clog.parse_changelog(open(changelog), max_blocks=1)
        return clog.package
    except ChangelogParseError:
        raise LGPException("Malformed Debian changelog '%s'" % changelog)
示例#3
0
    def reload(self):
        changelog = open(self.debian_changelog_path).read()

        self.debian_changelog = Changelog(changelog)
        self.debian = self.debian_changelog.full_version

        self.setup_py_text = open(self.setup_py_path).read()
        setup_py_results = re.findall(r'version\s*=\s*["\']([0-9]*\.[0-9]*\.[0-9]*)',
                                      self.setup_py_text)
        assert len(setup_py_results) == 1
        self.setup_py = setup_py_results[0]

        self.package_json_json = json.load(open(self.package_json_path),
                                           object_pairs_hook=collections.OrderedDict)
        self.package_json = self.package_json_json['version']

        build = minidom.parse(self.build_ant_path)
        self.build_ant_et = build
        build_ant_versions = [x.attributes['value'].value for x in
                              build.getElementsByTagName('property')
                              if x.attributes['name'].value == 'pkg_version']
        assert len(build_ant_versions) == 1
        self.build_ant = build_ant_versions[0]

        self.bower_json_json = json.load(open(self.bower_json_path),
                                            object_pairs_hook=collections.OrderedDict)
        self.bower_json = self.bower_json_json['version']

        self.version = self.debian
示例#4
0
 def __init__(self,
              name,
              version,
              native=False,
              version3=False,
              multiple_upstream_tarballs=None):
     """
     :param name: Package name
     :param version: Package version
     :param native: Whether to build a native source package
     :param version3: Whether to build a version 3.0 source package
     :param multiple_upstream_tarballs: A list of each top-level directory
         within the upstream tree which is to be packed as a source format
         3.0 (quilt) additional upstream tarball
     """
     self.upstream_files = {}
     self.upstream_symlinks = {}
     self.debian_files = {}
     self.name = name
     self.native = native
     self.version3 = version3
     self.multiple_upstream_tarballs = multiple_upstream_tarballs
     if multiple_upstream_tarballs and not (version3 and not native):
         raise AssertionError("Multiple upstream tarballs are only "
                              "possible with 3.0 (quilt) format")
     self._cl = Changelog()
     self.new_version(version)
示例#5
0
 def create_changelog(self, *distributions):
     changelog = Changelog()
     changes = ["  [ A. Hacker ]", "  * Something"]
     author = "J. Maintainer <*****@*****.**"
     for distro in distributions:
         changelog.new_block(changes=changes, author=author,
                             distributions=distro)
     return changelog
示例#6
0
 def make_changelog(self, versions_and_distributions):
     cl = Changelog()
     changes = ["  [ A. Hacker ]", "  * Something"]
     author = "J. Maintainer <*****@*****.**>"
     for version, distro in versions_and_distributions:
         cl.new_block(changes=changes, author=author,
                             distributions=distro, version=version)
     return cl
示例#7
0
文件: utils.py 项目: sipwise/repoapi
def parse_changelog(path):
    changelog = Changelog()
    with open(path, 'r') as file_changelog:
        changelog.parse_changelog(file_changelog.read())
    set_ids = set()
    for block in changelog:
        for change in block.changes():
            set_ids = set_ids.union(WorkfrontNoteInfo.getIds(change))
    return (set_ids, changelog)
示例#8
0
def _parse_deb_version(changelog='debian/changelog'):
    try:
        clog = Changelog()
        clog.parse_changelog(open(changelog), max_blocks=1)
        return clog.full_version
    except IOError:
        raise LGPException("Debian changelog '%s' cannot be found" % changelog)
    except ChangelogParseError:
        raise LGPException("Malformed Debian changelog '%s'" % changelog)
示例#9
0
def tree_set_changelog_version(tree: WorkingTree, build_version: Version,
                               subpath: str) -> None:
    cl_path = osutils.pathjoin(subpath, "debian/changelog")
    with tree.get_file(cl_path) as f:
        cl = Changelog(f)
    if Version(str(cl.version) + "~") > build_version:
        return
    cl.version = build_version
    with open(tree.abspath(cl_path), "w") as f:
        cl.write_to_open_file(f)
示例#10
0
def _parse_deb_distrib(changelog='debian/changelog'):
    clog = Changelog()
    try:
        clog.parse_changelog(open(changelog), max_blocks=1)
        return clog.distributions
    except IOError:
        raise DistributionException("Debian changelog '%s' cannot be found" %
                                    changelog)
    except ChangelogParseError:
        raise DistributionException("Malformed Debian changelog '%s'" %
                                    changelog)
示例#11
0
 def assertUnicodeCommitInfo(self, changes):
     wt = self.make_branch_and_tree(".")
     changelog = Changelog()
     author = "J. Maintainer <*****@*****.**>"
     changelog.new_block(changes=changes, author=author)
     message, authors, thanks, bugs = get_commit_info_from_changelog(
         changelog, wt.branch, _lplib=MockLaunchpad())
     self.assertEqual(
         u'[ \xc1. Hacker ]\n'
         u'* First ch\xe1nge, LP: #12345\n'
         u'* Second change, thanks to \xde. Hacker', message)
     self.assertEqual([author, u'\xc1. Hacker'], authors)
     self.assertEqual(text_type, type(authors[0]))
     self.assertEqual([u'\xde. Hacker'], thanks)
     self.assertEqual(['https://launchpad.net/bugs/12345 fixed'], bugs)
示例#12
0
def munge_lp_bug_numbers(repo):
    debian_changelog = os.path.join(repo.working_dir, 'debian', 'changelog')
    with ExitStack() as resources:
        infp = resources.enter_context(
            open(debian_changelog, 'r', encoding='utf-8'))
        outfp = resources.enter_context(atomic(debian_changelog))
        changelog = Changelog(infp)
        # Iterate through every line in the top changelog block.  Because we
        # want to modify the existing LP bug numbers, and because the API
        # doesn't give us direct access to those lines, we need to pop the
        # hood, reach in, and manipulate them ourselves.
        for i, line in enumerate(changelog[0]._changes):
            munged = re.sub('LP: #([0-9]+)', 'LP:\\1', line)
            changelog[0]._changes[i] = munged
        changelog.write_to_open_file(outfp)
示例#13
0
 def test_get_commit_message_info(self):
     wt = self.make_branch_and_tree(".")
     changelog = Changelog()
     changes = ["  [ A. Hacker ]", "  * First change, LP: #12345",
                "  * Second change, thanks to B. Hacker"]
     author = "J. Maintainer <*****@*****.**"
     changelog.new_block(changes=changes, author=author)
     message, authors, thanks, bugs = \
             get_commit_info_from_changelog(changelog, wt.branch,
                     _lplib=MockLaunchpad())
     self.assertEqual("\n".join(strip_changelog_message(changes)), message)
     self.assertEqual([author]+find_extra_authors(changes), authors)
     self.assertEqual(unicode, type(authors[0]))
     self.assertEqual(find_thanks(changes), thanks)
     self.assertEqual(find_bugs_fixed(changes, wt.branch,
                 _lplib=MockLaunchpad()), bugs)
示例#14
0
def find_patch_base(tree):
    """Find the base revision to apply patches to.

    Args:
      tree: Tree to find the patch base for
    Returns:
      A revision string
    """
    with tree.get_file("debian/changelog") as f:
        cl = Changelog(f, max_blocks=1)
        package = cl.package
        upstream_version = cl.version.upstream_version
    possible_tags = [
        "upstream-%s" % upstream_version,
        "upstream/%s" % upstream_version,
        "%s" % upstream_version,
        "v%s" % upstream_version,
        "%s-%s" % (package, upstream_version),
    ]
    tags = tree.branch.tags.get_tag_dict()
    for possible_tag in possible_tags:
        if possible_tag in tags:
            return tags[possible_tag]
    # TODO(jelmer): Do something clever, like look for the last merge?
    return None
示例#15
0
def get_latest_changelog_entry(local_tree, subpath=""):
    if control_files_in_root(local_tree, subpath):
        path = os.path.join(subpath, "changelog")
    else:
        path = os.path.join(subpath, "debian", "changelog")
    with local_tree.get_file(path) as f:
        cl = Changelog(f, max_blocks=1)
        return cl[0]
示例#16
0
 def test_get_commit_info_none(self):
     wt = self.make_branch_and_tree(".")
     changelog = Changelog()
     message, authors, thanks, bugs = get_commit_info_from_changelog(
         changelog, wt.branch, _lplib=MockLaunchpad())
     self.assertEqual(None, message)
     self.assertEqual([], authors)
     self.assertEqual([], thanks)
     self.assertEqual([], bugs)
def assertChangelogPackage(changelog_filename):
    with open(changelog_filename) as f:
        package = Changelog(f).get_package()

    image_dir = os.path.basename(os.path.dirname(changelog_filename))

    assert package == image_dir, \
        'Changelog package name %s matches directory name %s' % (
            package, image_dir)
示例#18
0
 def test_matches_package_version(self):
     if not os.path.exists("debian/changelog"):
         self.skipTest("no debian/changelog available. "
                       "Running outside of source tree?")
     with open("debian/changelog", "r") as f:
         cl = Changelog(f, max_blocks=1)
     package_version = str(cl.version)
     package_version = re.match(r'^\d+\.\d+', package_version)[0]
     self.assertEqual(package_version, version_string)
示例#19
0
    def get_debian_version(self, path: str) -> "Version":
        try:
            fn_changelog = join(path, 'debian', 'changelog')
            with open(fn_changelog, 'r') as fd:
                changelog = Changelog(fd)

            return Version(changelog.version.full_version)
        except (EnvironmentError, ChangelogParseError) as ex:
            self.debug('Failed open %r: %s' % (fn_changelog, ex))
            return Version('0')
def check_4_1_5():
    # If epoch has changed
    with open('debian/changelog', 'r') as f:
        cl = Changelog(f, max_blocks=2)
        epochs = set()
        for block in cl:
            epochs.add(block.version.epoch)
        if len(epochs) > 1:
            # Maybe they did email debian-devel@; we don't know.
            raise UpgradeCheckUnable("5.6.12", "last release changes epoch")
示例#21
0
 def make_changes(self, local_tree):
     # TODO(jelmer): Don't call UI implementation, refactor brz-debian
     cmd_merge_upstream().run(directory=local_tree.basedir,
                              snapshot=self._snapshot)
     if self._build_verify:
         build(local_tree.basedir)
     with local_tree.get_file('debian/changelog') as f:
         cl = Changelog(f.read())
         self._upstream_version = cl.version.upstream_version
     subprocess.check_call(["debcommit", "-a"], cwd=local_tree.basedir)
示例#22
0
    def distill(self, target):
        """Extract the source to a tree rooted at the given location.

        The passed location cannot already exist. If it does then
        FileExists will be raised.

        :param target: a string containing the location at which to
            place the tree containing the buildable source.
        """
        from debmutate.debcargo import parse_debcargo_source_name
        if os.path.exists(target):
            raise bzr_errors.FileExists(target)
        with self.tree.get_file(
                os.path.join(
                    self.subpath,
                    'debian/changelog' if not self.top_level else 'changelog'),
                'r') as f:
            cl = Changelog(f, max_blocks=1)
            package = cl.package
            version = cl.version

        if not package.startswith('rust-'):
            raise NotImplementedError

        debcargo_path = [self.subpath]
        if not self.top_level:
            debcargo_path.append('debian')
        debcargo_path.append('debcargo.toml')
        try:
            debcargo_text = self.tree.get_file_text(
                os.path.join(*debcargo_path))
        except bzr_errors.NoSuchFile:
            semver_suffix = False
        else:
            from toml.decoder import loads as loads_toml
            debcargo = loads_toml(debcargo_text.decode())
            semver_suffix = debcargo.get('semver_suffix')
        crate, crate_semver_version = parse_debcargo_source_name(
            package, semver_suffix)
        if '-' in crate:
            crate = cargo_translate_dashes(crate)
        crate_version = unmangle_debcargo_version(version.upstream_version)
        if crate_semver_version is not None:
            note('Using crate name: %s, version %s (semver: %s)', crate,
                 crate_version, crate_semver_version)
        else:
            note('Using crate name: %s, version %s', crate, crate_version)
        try:
            subprocess.check_call([
                'debcargo', 'package', '--changelog-ready', '--config',
                self.tree.abspath(os.path.join(
                    *debcargo_path)), '--directory', target, crate
            ] + ([crate_version] if crate_version else []))
        except subprocess.CalledProcessError:
            raise DebcargoError()
示例#23
0
def debcommit_release(tree, committer=None, subpath="", message=None):
    tag_name = tree_debian_tag_name(tree, tree.branch, subpath=subpath)
    cl_path = posixpath.join(subpath, "debian/changelog")
    if tag_name is None:
        raise UnreleasedChanges(cl_path)
    if message is None:
        cl = Changelog(tree.get_file(cl_path), max_blocks=1)
        message = "releasing package %s version %s" % (cl[0].package,
                                                       cl[0].version)
    revid = tree.commit(committer=committer, message=message)
    tree.branch.tags.set_tag(tag_name, revid)
    return tag_name
def assertChangelogPackage(image_dir):
    try:
        with open(os.path.join(image_dir, 'changelog')) as f:
            package = Changelog(f).get_package()
    except IOError as io_e:
        if io_e.errno == 2:
            raise AssertionError('%s must have a changelog file' % image_dir)
        raise

    assert package == os.path.basename(image_dir), \
        'Changelog package name %s matches directory name %s' % (
            package, os.path.basename(image_dir))
    def check(self, path: str) -> None:
        """ the real check """
        super(UniventionPackageCheck, self).check(path)

        fn = os.path.join(path, 'debian', 'changelog')
        try:
            with open(fn, 'r') as stream:
                changelog = Changelog(stream, strict=True)
        except EnvironmentError as ex:
            self.addmsg('0007-1', 'failed to open and read file: %s' % ex, fn)
            return
        except ChangelogParseError as ex:
            self.addmsg('0007-1', ex, fn)
            return

        for change in changelog[0].changes():
            if REticket.search(change):
                break
        else:
            self.addmsg(
                '0007-2',
                'latest changelog entry does not contain bug/ticket/issue number',
                fn)

        last = None
        for nr, block in enumerate(changelog):
            if last:
                if mktime_tz(parsedate_tz(last.date)) <= mktime_tz(
                        parsedate_tz(block.date)):
                    if nr < RECENT_ENTRIES:
                        self.addmsg(
                            '0007-3',
                            'not strict-monotonically increasing by time: %s <= %s'
                            % (last.date, block.date), fn)
                    else:
                        self.addmsg(
                            '0007-5',
                            'old not strict-monotonically increasing by time: %s <= %s'
                            % (last.date, block.date), fn)

                if last.version <= block.version:
                    if nr < RECENT_ENTRIES:
                        self.addmsg(
                            '0007-4',
                            'not strict-monotonically increasing by version: %s <= %s'
                            % (last.version, block.version), fn)
                    else:
                        self.addmsg(
                            '0007-6',
                            'old not strict-monotonically increasing by version: %s <= %s'
                            % (last.version, block.version), fn)

            last = block
示例#26
0
 def test_add_new(self):
     tree = self.make_branch_and_tree(".")
     tree.lock_write()
     self.addCleanup(tree.unlock)
     tree.mkdir("debian")
     changelog_add_new_version(tree, "1.0", "sid", None, "somepkg")
     # changelog_add_new_version will version the changelog if it was created
     cl = Changelog(open('debian/changelog'))
     self.assertEquals(cl._blocks[0].package, "somepkg")
     self.assertEquals(cl._blocks[0].distributions, "UNRELEASED")
     self.assertEquals(cl._blocks[0].version, Version("1.0-1"))
     self.assertEquals([], list(tree.filter_unversioned_files(["debian/changelog"])))
示例#27
0
def link_upstream_tarball(releaseType):
    #Find out the tarball link name
    upstream_name = os.path.basename( os.getcwd() )
    #paragraphs = deb822.Packages.iter_paragraphs(open('./debian/copyright', 'r'));
    #upstream_name = next(paragraphs)['Upstream-Name']
    
    changelog = Changelog()
    changelog.parse_changelog(open('./debian/changelog', 'r'))
    src_package_name = changelog.get_package()
    upstream_version = changelog.get_version().upstream_version
    #Handle packages with updated tarballs
    #e.g. 5.0.0a version instead of 5.0.0
    last_char = upstream_version[-1]
    if last_char.isalpha():
        real_upstream_version = upstream_version.rstrip(last_char)
    else:
        real_upstream_version = upstream_version
    
    link_name = '../' + src_package_name + '_' + upstream_version + '.orig.tar.xz'
    #Find out the tarball link target path
    cwd = os.path.dirname(os.path.realpath(__file__))
    config_tarball_loc = json.load(open(cwd + "/../conf/tarball-locations.json"))
    config_versions = json.load(open(cwd + "/../conf/versions.json"))
    link_target = os.path.expanduser(config_tarball_loc[releaseType]) 
    link_target += '/' + config_versions[releaseType] + '/'
    link_target += upstream_name + '-' + real_upstream_version + ".tar.xz"
    #Create the link
    try:
        os.symlink(link_target,link_name)
    except:
        pass
示例#28
0
def only_changes_last_changelog_block(
    tree: WorkingTree, basis_tree: Tree, changelog_path: str, changes
) -> bool:
    """Check whether the only change in a tree is to the last changelog entry.

    Args:
      tree: Tree to analyze
      changelog_path: Path to the changelog file
      changes: Changes in the tree
    Returns:
      boolean
    """
    with tree.lock_read(), basis_tree.lock_read():
        changes_seen = False
        for change in changes:
            if change.path[1] == "":
                continue
            if change.path[1] == changelog_path:
                changes_seen = True
                continue
            if not tree.has_versioned_directories() and is_inside(
                change.path[1], changelog_path
            ):
                continue
            return False
        if not changes_seen:
            return False
        try:
            new_cl = Changelog(tree.get_file_text(changelog_path))
        except NoSuchFile:
            return False
        try:
            old_cl = Changelog(basis_tree.get_file_text(changelog_path))
        except NoSuchFile:
            return True
        if old_cl.distributions != "UNRELEASED":
            return False
        del new_cl._blocks[0]
        del old_cl._blocks[0]
        return str(new_cl) == str(old_cl)
示例#29
0
 def generate_changelog_file(self):
     changes = Changelog()
     for version, scheduled_at, change, distribution in \
             self.db.changelog_entries(self.build.id):
         changes.new_block(
             package=self.deb_name,
             version=version,
             distributions=distribution,
             urgency='low',
             author=config.maintainer,
             date=scheduled_at.strftime('%a, %d %b %Y %H:%M:%S %z'))
         changes.add_change('\n  * ' + change + '\n')
     with open(self.debian_file('changelog'), 'w') as f:
         changes.write_to_open_file(f)
示例#30
0
def get_package_version(dirname):
    try:
        from debian.changelog import Changelog
    except ImportError:
        from debian_bundle.changelog import Changelog

    changelog = os.path.join(dirname, 'debian', 'changelog')

    ch = Changelog(open(changelog))
    package = ch.package
    version = str(ch.version).split(':')[-1]

    return package, version
示例#31
0
    def generate_changelog(self, package):
        """Generate a Debian changelog for the catkin package.

        Args:
            package (catkin_pkg.package.Package)

        Returns:
            debian.Changelog
        """
        package_path = self.get_package_path(package)
        package_changelog = catkin_changelog.get_changelog_from_path(package_path)

        debian_changelog = Changelog()

        package_name = self.catkin_to_apt_name(package.name)
        maintainer = '{} <{}>'.format(
            package.maintainers[0].name,
            package.maintainers[0].email
        )

        def transfer_version_change(change):
            debian_changelog.add_change(str(change))

        def transfer_version_block(v):
            version = v[0]
            date = v[1]
            changes = v[2]
            full_version = version + '-0' + self.ros_os_version
            debian_changelog.new_block(
                package=package_name,
                version=Version(full_version),
                distributions=self.ros_os_version,
                urgency='high',
                author=maintainer,
                date=self._datetime_to_rfc2822(date),
            )
            debian_changelog.add_change('')
            map(transfer_version_change, changes)
            debian_changelog.add_change('')

        if package_changelog is not None:
            map(transfer_version_block, package_changelog.foreach_version())
        else:
            # If CHANGELOG.rst is missing, generate a bare changelog
            version = str(package.version)
            date = datetime.datetime.now()
            changes = []
            block = (version, date, changes)
            transfer_version_block(block)

        return debian_changelog
示例#32
0
# stdlib
from sys import stdout

# 3rd party
from debian.changelog import Changelog, Version

changelog = Changelog()

# from tagim import __version__
changelog.new_block(package='python-tagim',  # will likely need a tagim package that depends on this library
                    version=Version('0.1'),
                    distributions='unstable',
                    urgency='low',
                    author='Hobson Lane <*****@*****.**>', # name and e-mail must match your GPG key
                    date='Thu, 26 Jan 2012 08:29:40 +1100', # must be in the format of `date -R`
                    )

changelog.add_change('')
changelog.add_change('  * Welcome to tagim')
changelog.add_change('  * Features')
changelog.add_change('    - tag images with text embedded in EXIF comment field')
changelog.add_change('    - chose random image from selected folder or tree of folders and display on desktop background at prescribed intervals')
changelog.add_change('')

stdout.write(changelog)

示例#33
0
文件: util.py 项目: Rhizi/rhizi
class Versions(object):
    def __init__(self):
        self.setup_py_path = os.path.join(RHIZI_SOURCE_REPO, 'setup.py')
        self.debian_changelog_path = os.path.join(RHIZI_SOURCE_REPO, 'res/debian/pkg__rhizi-common/changelog')
        self.package_json_path = os.path.join(RHIZI_SOURCE_REPO, 'package.json')
        self.build_ant_path = os.path.join(RHIZI_SOURCE_REPO, 'build.ant')
        self.bower_json_path = os.path.join(RHIZI_SOURCE_REPO, 'bower.json')
        self.filenames = [self.setup_py_path, self.debian_changelog_path,
                          self.package_json_path, self.build_ant_path,
                          self.bower_json_path]
        self.reload()

    def reload(self):
        changelog = open(self.debian_changelog_path).read()

        self.debian_changelog = Changelog(changelog)
        self.debian = self.debian_changelog.full_version

        self.setup_py_text = open(self.setup_py_path).read()
        setup_py_results = re.findall(r'version\s*=\s*["\']([0-9]*\.[0-9]*\.[0-9]*)',
                                      self.setup_py_text)
        assert len(setup_py_results) == 1
        self.setup_py = setup_py_results[0]

        self.package_json_json = json.load(open(self.package_json_path),
                                           object_pairs_hook=collections.OrderedDict)
        self.package_json = self.package_json_json['version']

        build = minidom.parse(self.build_ant_path)
        self.build_ant_et = build
        build_ant_versions = [x.attributes['value'].value for x in
                              build.getElementsByTagName('property')
                              if x.attributes['name'].value == 'pkg_version']
        assert len(build_ant_versions) == 1
        self.build_ant = build_ant_versions[0]

        self.bower_json_json = json.load(open(self.bower_json_path),
                                            object_pairs_hook=collections.OrderedDict)
        self.bower_json = self.bower_json_json['version']

        self.version = self.debian

    def ensure_synced(self):
        """
        setup.py
        debian - res/debian/pkg__rhizi-common/changelog
        package.json
        """
        if self.setup_py != self.debian:
            print("setup.py {} != debian {}".format(self.setup_py, self.debian))
            raise SystemExit
        if self.package_json != self.debian:
            print("package.json {} != debian {}".format(self.package_json, self.debian))
            raise SystemExit
        if self.build_ant != self.debian:
            print("build.ant {} != debian {}".format(self.build_ant, self.debian))
            raise SystemExit
        if self.bower_json != self.debian:
            print("bower.json {} != debian {}".format(self.bower_json, self.debian))
            raise SystemExit

    def bump_version(self, debian_changelog):
        old_ver = self.setup_py
        new_ver = self.next_micro()
        # debian changelog
        now = datetime.now(tz=tzlocal()).strftime("%a, %d %b %Y %H:%M:%S %z")
        self.debian_changelog.new_block(
            version=new_ver,
            author='{} <{}>'.format(check_output('git config user.name'.split()).strip().decode('utf-8'),
                                    check_output('git config user.email'.split()).strip().decode('utf-8')),
            package="rhizi",
            distributions="unstable",
            urgency='low',
            changes=['  * {}'.format(c.decode('utf-8')) for c in debian_changelog],
            date=now)
        with open(self.debian_changelog_path, 'w+') as fd:
            fd.write(str(self.debian_changelog))

        # build.ant - not using minidom since it doesn't keep whitespace, too
        # much churn
        replace(self.build_ant_path, old_ver, new_ver)

        # setup.py
        replace(self.setup_py_path, old_ver, new_ver)

        # package.json
        self.package_json_json['version'] = new_ver
        with open(self.package_json_path, 'w+') as fd:
            json.dump(self.package_json_json, fd,
                      indent=2, separators=(',', ': '))

        # bower.json
        self.bower_json_json['version'] = new_ver
        with open(self.bower_json_path, 'w+') as fd:
            json.dump(self.bower_json_json, fd,
                      indent=2, separators=(',', ': '))

        # update internal versions
        self.reload()

    def next_micro(self):
        major, minor, micro = map(int, self.setup_py.split('.'))
        return '{}.{}.{}'.format(major, minor, micro + 1)

    def by_tag(self):
        all = [x.strip() for x in check_output('git tag'.split()).split()]
        return sorted([x for x in all if x.startswith(b'v-')],
                      key=lambda v: list(map(int, v[2:].split(b'.'))))[-1][2:].decode('utf-8')
示例#34
0
 def _create_changelog(self, temp_dir, *args, **kwargs):
     changelog = Changelog()
     changelog.new_block()
     changelog.set_version(self.version)
     changelog.set_package(self.package)
     changelog.set_distributions('all')
     changelog.set_urgency('low')
     changelog.set_author(self.maintainer)
     changelog.set_date(_format_debian_date(self.date))
     changelog.add_change('  * Release of %s' % self.version)
     return changelog
示例#35
0
def generate_debian_package(args, config):
    debfile = Deb822(
        open("debian/control"),
        fields=["Build-Depends", "Build-Depends-Indep"])

    rel_str = debfile.get("Build-Depends")
    if debfile.has_key("Build-Depends-Indep"):
        rel_str = rel_str + "," + debfile.get("Build-Depends-Indep")

    relations = PkgRelation.parse_relations(rel_str)

    cache = Cache()

    # Check if all required packages are installed
    for dep in relations:
        if not check_deb_dependency_installed(cache, dep):
            # Install not found dependencies
            print("Dependency not matched: " + str(dep))
            if not install_dependency(cache, dep):
                print("Dependency cannot be installed: " + PkgRelation.str([dep
                                                                            ]))
                exit(1)

    changelog = Changelog(open("debian/changelog"))
    old_changelog = Changelog(open("debian/changelog"))

    dist = os.popen("lsb_release -c").read()
    dist = dist[dist.rfind(":") + 1::].replace("\n", "").replace(
        "\t", "").replace(" ", "")

    new_version = get_debian_version(args, dist)

    changelog.new_block(version=new_version,
                        package=changelog.package,
                        distributions="testing",
                        changes=["\n  Generating new package version\n"],
                        author=changelog.author,
                        date=strftime("%a, %d %b %Y %H:%M:%S %z"),
                        urgency=changelog.urgency)

    changelog.write_to_open_file(open("debian/changelog", 'w'))

    # Execute commands defined in config:
    if config.has_key("prebuild-command"):
        print("Executing prebuild-command: " + str(config["prebuild-command"]))
        if os.system(config["prebuild-command"]) != 0:
            print("Failed to execute prebuild command")
            exit(1)

    if os.system("dpkg-buildpackage -uc -us") != 0:
        print("Error generating package")
        exit(1)

    if os.system("sudo dpkg -i ../*" + new_version + "_*.deb") != 0:
        print("Packages are not installable")
        exit(1)

    files = glob.glob("../*" + new_version + "_*.deb")
    if args.command == "upload":
        for f in files:
            if f is files[-1]:
                is_last = True
            else:
                is_last = False
            if new_version.find("~") == -1:
                upload_package(args, config, dist, f)
            upload_package(args, config, dist + "-dev", f, publish=is_last)

    if args.clean:
        files = glob.glob("../*" + new_version + "*")
        for f in files:
            os.remove(f)

    # Write old changelog to let everything as it was
    old_changelog.write_to_open_file(open("debian/changelog", 'w'))
示例#36
0
 def parse_changelog(self):
     c = Changelog()
     with open(self.changelog_file, 'r') as f:
         c.parse_changelog(f)
     return c
示例#37
0
def changelog(dpath, ctx, env):
    change = ctx.get('message', 'Autogenerated by py2dsp v{}'.format(VERSION))
    version = "{}-{}".format(ctx['version'], ctx['debian_revision'])
    distribution = ctx.get('distribution', 'UNRELEASED')

    fpath = join(dpath, 'debian', 'changelog')
    if exists(fpath):
        with open(fpath, encoding='utf-8') as fp:
            line = fp.readline()
            if ctx['version'] in line or 'UNRELEASED' in line:
                log.debug('changelog doesn\'t need an update')
                return
            else:
                yield from execute(['dch', '--force-distribution', '--distribution', distribution,
                                    '--newversion', version, '-m', change], cwd=dpath)
        return

    now = datetime.utcnow()
    changelog = Changelog()
    changelog.new_block(package=ctx['src_name'],
                        version=Version(version),
                        distributions=distribution,
                        urgency='low',
                        author=ctx['creator'],
                        date=now.strftime('%a, %d %b %Y %H:%M:%S +0000'))
    changelog.add_change('')
    changelog.add_change('  * {}'.format(change))
    changelog.add_change('')

    with open(fpath, 'w', encoding='utf-8') as fp:
        changelog.write_to_open_file(fp)
    return True