Example #1
0
    def make_unpacked_source(self):
        """Create an unpacked source tree in a branch. Return the working tree"""
        tree = self.make_branch_and_tree('.')
        cl_file = 'debian/changelog'
        source_files = ['debian/'] + [cl_file]
        self.build_tree(source_files)
        c = self.make_changelog()
        with open(cl_file, 'w') as f:
            c.write_to_open_file(f)
        tree.add(source_files)
        source = Deb822()
        source['Source'] = self.package_name
        binary = Deb822()
        binary['Package'] = self.package_name
        binary['Architecture'] = 'all'
        with open('debian/control', 'wb') as f:
            source.dump(f)
            f.write(b'\n')
            binary.dump(f)
        tree.add('debian/control')

        self.build_tree(['debian/test-file'])
        tree.add('debian/test-file')

        return tree
Example #2
0
    def generate_control_file(self):
        dsc = Dsc()
        build_deps = []
        packages = OrderedDict()
        self.installs = {}
        self.symlinks = {}

        for item in self.generate_control_content():
            log.debug(repr(item))
            if isinstance(item, SourceControl):
                for key, value in item.items():
                    key = '-'.join([k.capitalize() for k in key.split('_')])
                    if key == 'Description':
                        value = value.strip() \
                                     .replace('\n\n', '\n.\n') \
                                     .replace('\n', '\n ')
                    dsc[key] = value
            elif isinstance(item, BuildDependency):
                build_deps.append(item.dependency)
            elif isinstance(item, Package):
                control = Deb822()
                for key, value in item._asdict().items():
                    key = '-'.join([k.capitalize() for k in key.split('_')])
                    if key == 'Description':
                        value = value.strip() \
                                     .replace('\n\n', '\n.\n') \
                                     .replace('\n', '\n ')
                    control[key] = value
                packages[item.package] = (control, [], [])
                self.installs[item.package] = []
                self.symlinks[item.package] = []
            elif isinstance(item, Dependency):
                packages[item.package][1].append(item.dependency)
            elif isinstance(item, Provide):
                packages[item.package][2].append(item.provide)
            elif isinstance(item, Symlink):
                self.symlinks[item.package].append((item.dest, item.src))
            elif isinstance(item, FastBuild):
                if self.fast_build is None:
                    self.fast_build = item.possible
                else:
                    self.fast_build = self.fast_build and item.possible
            else:
                raise NotImplementedError(
                    'Got unexcepted action item'
                    ' on control generation {!r}'.format(item))
        if self.installs:
            build_deps.append('dh-exec')

        with open(self.debian_file('control'), 'wb') as control_file:
            dsc['Build-Depends'] = ', '.join(build_deps)
            dsc.dump(control_file)

            for control, deps, provides in packages.values():
                if deps:
                    control['Depends'] = ', '.join(deps)
                if provides:
                    control['Provides'] = ', '.join(provides)
                control_file.write(b'\n')
                control.dump(control_file)
def main():
    module = AnsibleModule(
        argument_spec={
            'path': {'type': 'path', 'required': True}
        }
    )

    if not HAS_DEB_PKG_TOOLS:
        module.fail_json(msg='The deb_pkg_tools is required for this module')

    with open(module.params['path']) as f:
        paragraphs = list(Deb822.iter_paragraphs(f))

    return_data = {
        'sources': {},
        'packages': {}
    }

    for paragraph in paragraphs:
        data = control.parse_control_fields(paragraph)
        package = data.get('Package')
        source = data.get('Source')
        key = 'packages' if package else 'sources'

        return_data[key][package or source] = item = {}

        for field in control.DEPENDS_LIKE_FIELDS:
            item[field] = list(getattr(data.get(field), 'names', []))

        for field in data:
            if field in control.DEPENDS_LIKE_FIELDS:
                continue
            item[field] = data.get(field)

    module.exit_json(**return_data)
Example #4
0
    def listBin(self, arch, component, idrel, name):
        """
		Return an iterator over packages.
		arch, component and relese can all be either None, meaning
		no restriction, a string or number (in case of idrel),
		or an iterable.
		"""
        (sqlj, sqlw, sqlparams) = makeQuery(arch, component, idrel, name)
        sql = 'SELECT b.*,rel.Codename AS release, r.component, r.Filename ' \
           + sqlj \
           + ' JOIN  releases rel on r.idrel = rel.id ' \
           + sqlw \
           + ' ORDER BY rel.Codename, r.component, b.name, b.Architecture'
        logger.debug("Query for list = %s", sql)
        self.dbc.execute(sql, sqlparams)
        while True:
            r = self.dbc.fetchone()
            if r is None: return
            # make a dict from the query in the usual way
            p = collections.defaultdict(lambda: '', zip(r.keys(), r))
            # update with keys from control file
            p.update(Deb822(p['control']))
            del p['control']
            p['shortdesc'] = (p['Description'].partition('\n'))[0]
            yield p
Example #5
0
 def test_control_field_parsing(self):
     deb822_package = Deb822([
         'Package: python-py2deb',
         'Depends: python-deb-pkg-tools, python-pip, python-pip-accel',
         'Installed-Size: 42'
     ])
     parsed_info = parse_control_fields(deb822_package)
     self.assertEqual(
         parsed_info, {
             'Package':
             'python-py2deb',
             'Depends':
             RelationshipSet(Relationship(name=u'python-deb-pkg-tools'),
                             Relationship(name=u'python-pip'),
                             Relationship(name=u'python-pip-accel')),
             'Installed-Size':
             42
         })
     # Test backwards compatibility with the old interface where `Depends'
     # like fields were represented as a list of strings (shallow parsed).
     parsed_info['Depends'] = [unicode(r) for r in parsed_info['Depends']]
     self.assertEqual(unparse_control_fields(parsed_info), deb822_package)
     # Test compatibility with fields like `Depends' containing a string.
     parsed_info['Depends'] = deb822_package['Depends']
     self.assertEqual(unparse_control_fields(parsed_info), deb822_package)
Example #6
0
async def add_to_cache(url: URLObject):
    package = app.registry.get_or_create(url)
    if package.status == Status.UNSEEN:
        package_archive = await app.http.get(url)

        if not package_archive.status == 200:
            return

        fileobj = io.BytesIO(await package_archive.read())
        fileobj.seek(0)
        untarred = tarfile.open(fileobj=fileobj, mode="r:*")
        meta = {}

        try:
            for f in untarred.getmembers():
                if f.name.endswith("DESCRIPTION"):
                    logger.debug(f"add_to_cache:found {f.name}")
                    meta = Deb822(
                        untarred.extractfile(f).read().decode("utf8"))

            logger.debug(meta)
            package.name = meta.get("Package")
            package.version = meta.get("Version")
            if meta.get("NeedsCompilation") == "yes":
                temp_dir = tempfile.mkdtemp()
                untarred.extractall(temp_dir)
                package.fs_path = pathlib.Path(temp_dir) / meta.get("Package")
                package.status = Status.TOBUILD
                await app.compile_queue.put(package)
            else:
                package.status = Status.NONBINARY
        finally:
            untarred.close()
            fileobj.close()
Example #7
0
 def update(self, repo):
     repo_dict = dict([(str(k), str(v)) for (k, v) in repo.items()])
     repo_dict['id'] = repo.id
     self.repos822[:] = [
         repo822 if repo822['id'] != repo.id else Deb822(repo_dict)
         for repo822 in self.repos822
     ]
    def handle(self, *args, **options):
        if not args:
            raise CommandError("Require a tag, e.g. sid, wheezy, squeeze, etc...")
        tag = args[0]
        filenames = args[1:]
        if not tag.isalpha() or not tag.islower():
            raise CommandError("First argument must be tag, e.g. sid, wheezy, squeeze, etc...")

        self.session = db.get_db_session()
#        self.session.bind.echo=False

        self.descr_text_map = {}
        self.descr_map = {}
        self.stats = defaultdict(int)

        for file in filenames:
            self.stderr.write('Processing %s\n' % file)
            f = self._open(file)
            for para in Deb822.iter_paragraphs(f):
                if 'Description-en' in para:
                    self._handle_translation_en(para)
                if 'Version' in para:
                    try:
                        self._handle_packages(tag, para)
                    except Exception, e:
                        self.stdout.write("Problem processing %r\n%s\n" % (para, e))
            self.session.commit()
Example #9
0
def apt_get_source_package(name: str) -> Deb822:
    """Get source package metadata.

    Args:
      name: Name of the source package
    Returns:
      A `Deb822` object
    """
    import apt_pkg

    apt_pkg.init()

    try:
        sources = apt_pkg.SourceRecords()
    except apt_pkg.Error as e:
        if e.args[0] == (
                "E:You must put some 'deb-src' URIs in your sources.list"):
            raise NoAptSources()
        raise

    by_version: Dict[str, Deb822] = {}
    while sources.lookup(name):
        by_version[sources.version] = sources.record  # type: ignore

    if len(by_version) == 0:
        raise NoSuchPackage(name)

    # Try the latest version
    version = sorted(by_version, key=Version)[-1]

    return Deb822(by_version[version])
Example #10
0
 def test_control_field_merging(self):
     """Test the merging of control file fields."""
     defaults = Deb822(['Package: python-py2deb',
                        'Depends: python-deb-pkg-tools',
                        'Architecture: all'])
     # The field names of the dictionary with overrides are lower case on
     # purpose; control file merging should work properly regardless of
     # field name casing.
     overrides = Deb822(dict(version='1.0',
                             depends='python-pip, python-pip-accel',
                             architecture='amd64'))
     assert merge_control_fields(defaults, overrides) == \
         Deb822(['Package: python-py2deb',
                 'Version: 1.0',
                 'Depends: python-deb-pkg-tools, python-pip, python-pip-accel',
                 'Architecture: amd64'])
Example #11
0
def get_newqueue_available(package,
                           timeout,
                           dists=None,
                           http_proxy=None,
                           arch='i386'):
    if dists is None:
        dists = ('unstable (new queue)', )
    try:
        page = open_url(NEWQUEUE_URL, http_proxy, timeout)
    except NoNetwork:
        return {}
    except urllib.error.HTTPError as x:
        print("Warning:", x, file=sys.stderr)
        return {}
    if not page:
        return {}

    versions = {}

    # iter over the entries, one paragraph at a time
    for para in Deb822.iter_paragraphs(page):
        if para['Source'] == package:
            k = para['Distribution'] + ' (' + para['Queue'] + ')'
            # in case of multiple versions, choose the bigger
            versions[k] = max(para['Version'].split())

    return versions
    def handle(self, *args, **options):
        if len(args) != 3:
            raise CommandError(
                "Requires a language, a tag and an output filename")
        lang = args[0]
        tag = args[1]
        filename = args[2]

        f = open(filename, "w")

        session = db.get_db_session()
        session.bind.echo = False

        output = False
        for trans, descr, descr_tag in session.query(ddtp.Translation, ddtp.Description, ddtp.DescriptionTag). \
                                          filter(ddtp.Translation.description_id == ddtp.Description.description_id). \
                                          filter(ddtp.Description.description_id == ddtp.DescriptionTag.description_id). \
                                          filter(ddtp.Translation.language == lang). \
                                          filter(ddtp.DescriptionTag.date_end >= date.today()-timedelta(days=7)). \
                                          filter(ddtp.DescriptionTag.tag == tag). \
                                          order_by(ddtp.Description.package). \
                                          yield_per(100):
            trans_para = Deb822()
            trans_para['Package'] = descr.package
            trans_para['Description-md5'] = descr.description_md5
            trans_para['Description-%s' % lang] = trans.translation

            # Minor nagic here: the translation has an extra newline here,
            # which we use to seperate the paragraphs
            f.write(trans_para.dump().encode('utf-8'))
            output = True

        if not output:
            self.stderr.write("WARNING: No output for tag %r, language %r\n" %
                              (tag, lang))
def check_4_4_1():
    # Check that there is only one Vcs field.
    vcs_fields = []
    with open('debian/control') as f:
        source = next(Deb822.iter_paragraphs(f))
        for name in source:
            if name.lower() == 'vcs-browser':
                continue
            if name.lower().startswith('vcs-'):
                vcs_fields.append(name)
    if len(vcs_fields) > 1:
        raise UpgradeCheckFailure(
            "5.6.26", "package has more than one Vcs-<type> field")

    # Check that Files entries don't refer to directories.
    # They must be wildcards *in* the directories.
    try:
        with open('debian/copyright', 'r') as f:
            copyright = Copyright(f, strict=False)
            for para in copyright.all_files_paragraphs():
                for glob in para.files:
                    if os.path.isdir(glob):
                        raise UpgradeCheckFailure(
                            "copyright-format",
                            "Wildcards are required to match the contents of "
                            "directories")
    except FileNotFoundError:
        pass
    except NotMachineReadableError:
        pass
Example #14
0
def getBinFromDb(db, pckid):
    """
	Get a binary package from a database
	"""
    pdict = db.getbinary(pckid)
    pdict['cdict'] = Deb822(pdict['control'])
    return BinPackageDb(**pdict)
Example #15
0
 def removesrc(self, path, components=None):
     # pylint: disable=undefined-variable
     for p in Deb822.iter_paragraphs(file(path)):
         if 'Source' in p:
             self._removesrc(p['Source'],
                             self.repo_attr.codename,
                             components)
Example #16
0
def new_build():
    metadata = request.files['metadata']
    buildinfo = request.files['buildinfo']
    source = None
    version = None
    for paragraph in Deb822.iter_paragraphs(buildinfo):
        for item in paragraph.items():
            if item[0] == 'Source':
                source = item[1]
            if item[0] == 'Version':
                version = item[1]
    buildinfo.seek(0)
    id = uuid.uuid4()
    pkg = db.get_or_create(Package, name=source)
    ver = db.get_or_create(Version, version=version, package=pkg)
    db.get_or_create(LinkMetadata, version=ver, text=metadata.read(), uuid=id)
    db.get_or_create(Buildinfo, version=ver, text=buildinfo.read(), uuid=id)
    db.session.commit()
    j = {
        "type": "inclusion",
        "package": source,
        "version": source,
        "linkmetadata": metadata.read(),
        "buildinfo": buildinfo.read()
    }
    try:
        node = append(j)
    except:
        return {"status": "Could not append"}, 400
    return {"status": "ok", "node": node.to_json()}, 200
    return
Example #17
0
def update_control():
    """Update the debian control file.
    """
    from debian.deb822 import Deb822, PkgRelation
    f = open('debian/control', 'r')
    iter = Deb822.iter_paragraphs(f)
    source = iter.next()

    def update_deps(control, field, package, min_version):
        bdi = PkgRelation.parse_relations(control[field])
        update_relation(bdi, package, ">=", "%d.%d.%d~" % min_version)
        control[field] = PkgRelation.str(bdi)

    talloc_version = find_version(os.path.join(tree, "lib/talloc/wscript"))

    eq_config = LibraryEquivalents('debian/library-equivalents')
    min_talloc_version = eq_config.find_oldest_compatible("talloc", talloc_version)
    update_deps(source, "Build-Depends", "libtalloc-dev", min_talloc_version)
    update_deps(source, "Build-Depends", "python-talloc-dev", min_talloc_version)

    o = open("debian/control", "w+")
    source.dump(o)

    for binary in iter:
        o.write("\n")
        binary.dump(o)

    o.close()
Example #18
0
 def test_control_field_parsing(self):
     """Test the parsing of control file fields."""
     deb822_package = Deb822([
         'Package: python-py2deb',
         'Depends: python-deb-pkg-tools, python-pip, python-pip-accel',
         'Installed-Size: 42'
     ])
     parsed_info = parse_control_fields(deb822_package)
     assert parsed_info == {
         'Package':
         'python-py2deb',
         'Depends':
         RelationshipSet(Relationship(name=u'python-deb-pkg-tools'),
                         Relationship(name=u'python-pip'),
                         Relationship(name=u'python-pip-accel')),
         'Installed-Size':
         42
     }
     # Test backwards compatibility with the old interface where `Depends'
     # like fields were represented as a list of strings (shallow parsed).
     parsed_info['Depends'] = [text_type(r) for r in parsed_info['Depends']]
     assert unparse_control_fields(parsed_info) == deb822_package
     # Test compatibility with fields like `Depends' containing a string.
     parsed_info['Depends'] = deb822_package['Depends']
     assert unparse_control_fields(parsed_info) == deb822_package
Example #19
0
    def parse_info(self, docfile):
        '''This function reads a doc-base registry file. We use the
        sectionedfile object to get the individual sections from the
        file, and rfc822 object to parse them.'''

        with open(docfile, 'rb') as fp:
            part_iter = Deb822.iter_paragraphs(fp)

            header = next(part_iter)
            self.title = header["Title"]
            if "Author" in header:
                self.author = header["Author"]
            if "Abstract" in header:
                self.abstract = self._parse_abstract(header["Abstract"])
            if "Section" in header:
                self.section = header["Section"]

            for part in part_iter:
                if "Format" not in part:
                    continue
                format = part["Format"].lower()
                if "Index" in part:
                    self.docs[format] = part["Index"]
                else:
                    self.docs[format] = part["Files"]
Example #20
0
 def _remove(self, path, codename, component):
     os.environ['GNUPGHOME'] = "/var/cache/elbe/gnupg"
     for p in Deb822.iter_paragraphs(file(path)):
         if 'Source' in p:
             self._removesrc(p['Source'], codename, component)
         elif 'Package' in p:
             self._removedeb(p['Package'], codename, component)
Example #21
0
 def test_repository_creation(self, preserve=False):
     """Test the creation of trivial repositories."""
     if SKIP_SLOW_TESTS:
         return self.skipTest("skipping slow tests")
     with Context() as finalizers:
         config_dir = tempfile.mkdtemp()
         repo_dir = tempfile.mkdtemp()
         if not preserve:
             finalizers.register(shutil.rmtree, config_dir)
             finalizers.register(shutil.rmtree, repo_dir)
         from deb_pkg_tools import config
         config.user_config_directory = config_dir
         with open(os.path.join(config_dir, config.repo_config_file),
                   'w') as handle:
             handle.write('[test]\n')
             handle.write('directory = %s\n' % repo_dir)
             handle.write('release-origin = %s\n' % TEST_REPO_ORIGIN)
         self.test_package_building(repo_dir)
         update_repository(
             repo_dir,
             release_fields=dict(description=TEST_REPO_DESCRIPTION),
             cache=self.package_cache)
         assert os.path.isfile(os.path.join(repo_dir, 'Packages'))
         assert os.path.isfile(os.path.join(repo_dir, 'Packages.gz'))
         assert os.path.isfile(os.path.join(repo_dir, 'Release'))
         with open(os.path.join(repo_dir, 'Release')) as handle:
             fields = Deb822(handle)
             assert fields['Origin'] == TEST_REPO_ORIGIN
             assert fields['Description'] == TEST_REPO_DESCRIPTION
         if not apt_supports_trusted_option():
             assert os.path.isfile(os.path.join(repo_dir, 'Release.gpg'))
         return repo_dir
Example #22
0
 def read(self):
     if not self.manage_repos:
         log.debug("Skipping read due to manage_repos setting: %s" % self.path)
         return
     with open(self.path, "r") as f:
         for repo822 in Deb822.iter_paragraphs(f, shared_storage=False):
             self.repos822.append(repo822)
    def debcontrol(self):
        """ Return the debian/control as a Deb822 (a Debian-specific dict-like
        class) object.
        
        For a string representation of debian/control try
        .get_content('control') """

        return Deb822(self.get_content(CONTROL_FILE))
Example #24
0
def deb822_from_string(string):
    """
    Create a :class:`debian.deb822.Deb822` object from a string.

    :param string: The string containing the control fields to parse.
    :returns: A :class:`debian.deb822.Deb822` object.
    """
    return Deb822(StringIO(textwrap.dedent(string).strip()))
Example #25
0
 def test_upgrade(self, mock_package_install_hooks):
     with self.run_in_subprocess("click_get_frameworks_dir") as (enter,
                                                                 preloads):
         enter()
         os.environ["TEST_QUIET"] = "1"
         path = self.make_fake_package(
             control_fields={
                 "Package": "test-package",
                 "Version": "1.1",
                 "Architecture": "all",
                 "Maintainer": "Foo Bar <*****@*****.**>",
                 "Description": "test",
                 "Click-Version": "0.2",
             },
             manifest={
                 "name": "test-package",
                 "version": "1.1",
                 "framework": "ubuntu-sdk-13.10",
             },
             control_scripts={"preinst": static_preinst},
             data_files={"foo": None})
         root = os.path.join(self.temp_dir, "root")
         package_dir = os.path.join(root, "test-package")
         inst_dir = os.path.join(package_dir, "current")
         os.makedirs(os.path.join(package_dir, "1.0"))
         os.symlink("1.0", inst_dir)
         db = Click.DB()
         db.add(root)
         installer = ClickInstaller(db)
         self._setup_frameworks(preloads, frameworks=["ubuntu-sdk-13.10"])
         with mock_quiet_subprocess_call():
             installer.install(path)
         self.assertCountEqual([".click", "test-package"], os.listdir(root))
         self.assertCountEqual(["1.1", "current"], os.listdir(package_dir))
         self.assertTrue(os.path.islink(inst_dir))
         self.assertEqual("1.1", os.readlink(inst_dir))
         self.assertCountEqual([".click", "foo"], os.listdir(inst_dir))
         status_path = os.path.join(inst_dir, ".click", "status")
         with open(status_path) as status_file:
             # .readlines() avoids the need for a python-apt backport to
             # Ubuntu 12.04 LTS.
             status = list(Deb822.iter_paragraphs(status_file.readlines()))
         self.assertEqual(1, len(status))
         self.assertEqual(
             {
                 "Package": "test-package",
                 "Status": "install ok installed",
                 "Version": "1.1",
                 "Architecture": "all",
                 "Maintainer": "Foo Bar <*****@*****.**>",
                 "Description": "test",
                 "Click-Version": "0.2",
             }, status[0])
         mock_package_install_hooks.assert_called_once_with(db,
                                                            "test-package",
                                                            "1.0",
                                                            "1.1",
                                                            user_name=None)
Example #26
0
	def _read_module_attributes_from_source_package(module):
		# type: (BaseModule) -> umc.UMC_Module
		umc_module_definition_file = os.path.join(module['abs_path_to_src_pkg'], 'debian', '{}{}'.format(module['module_name'], UMC_MODULES))
		with open(umc_module_definition_file, 'r') as fd:
			def_file = fd.read()

		attributes = Deb822(def_file)
		attributes = dict((k, [v]) for k, v in attributes.items())  # simulate dh_ucs.parseRfc822 behaviour
		return attributes
Example #27
0
def load_control_file(control_file):
    """
    Load a control file and return the parsed control fields.

    :param control_file: The filename of the control file to load (a string).
    :returns: A dictionary created by :func:`parse_control_fields()`.
    """
    with open(control_file) as handle:
        return parse_control_fields(Deb822(handle))
Example #28
0
 def _remove(self, path, codename, component):
     for p in Deb822.iter_paragraphs(file(path)):
         if 'Source' in p:
             self._removesrc(p['Source'], codename)
         elif 'Package' in p:
             self._removedeb(p['Package'], codename)
         elif 'Binary' in p:
             for pp in p['Binary'].split():
                 self._removedeb(pp, codename)
def get_changes_file(changes_file_url):
    if changes_file_url is not None:
        changes_text = urllib.request.urlopen(changes_file_url).read()
        changes_dict = Deb822(changes_text)
    else:
        return

    if 'Launchpad-Bugs-Fixed' in changes_dict.keys():
        bugnum = changes_dict['Launchpad-Bugs-Fixed']
        return bugnum.split(' ') # This can be a string which has many entries
Example #30
0
 def _remove(self, path, codename, components=None):
     # pylint: disable=undefined-variable
     for p in Deb822.iter_paragraphs(file(path)):
         if 'Source' in p:
             self._removesrc(p['Source'], codename, components)
         elif 'Package' in p:
             self._removedeb(p['Package'], codename, components)
         elif 'Binary' in p:
             for pp in p['Binary'].split():
                 self._removedeb(pp, codename, components)
def update_control():
    """Update the debian control file.
    """
    from debian.deb822 import Deb822, PkgRelation
    f = open('debian/control', 'rb')
    iter = Deb822.iter_paragraphs(f.readlines())
    for i in iter:
        source = i
        break

    def update_deps(control, field, package, min_version, epoch=None):
        bdi = PkgRelation.parse_relations(control[field])
        if epoch is not None:
            epoch = "%d:" % epoch
        else:
            epoch = ""
        update_relation(bdi, package, ">=", epoch + "%d.%d.%d~" % min_version)
        control[field] = PkgRelation.str(bdi)

    tdb_version = find_version(os.path.join(tree, "lib/tdb/wscript"))
    talloc_version = find_version(os.path.join(tree, "lib/talloc/wscript"))
    ldb_version = find_version(os.path.join(tree, "lib/ldb/wscript"))
    tevent_version = find_version(os.path.join(tree, "lib/tevent/wscript"))

    eq_config = LibraryEquivalents('debian/library-equivalents')
    min_tdb_version = eq_config.find_oldest_compatible("tdb", tdb_version)
    min_talloc_version = eq_config.find_oldest_compatible("talloc", talloc_version)
    min_ldb_version = eq_config.find_oldest_compatible("ldb", ldb_version)
    min_tevent_version = eq_config.find_oldest_compatible("tevent", tevent_version)

    update_deps(source, "Build-Depends", "libtdb-dev", min_tdb_version)
    update_deps(source, "Build-Depends", "python-tdb", min_tdb_version)
    update_deps(source, "Build-Depends", "libtalloc-dev", min_talloc_version)
    update_deps(source, "Build-Depends", "python-talloc-dev", min_talloc_version)
    update_deps(source, "Build-Depends", "libldb-dev", min_ldb_version, 1)
    update_deps(source, "Build-Depends", "python-ldb-dev", min_ldb_version, 1)
    update_deps(source, "Build-Depends", "python-ldb", min_ldb_version, 1)
    update_deps(source, "Build-Depends", "libtevent-dev", min_tevent_version)

    with open("debian/control", "wb+") as o:
        for i in source.keys():
            if i == "Build-Depends":
                value=",\n               ".join(source[i].split(', '))
            else:
                value=source[i]
            o.write(("%s: %s\n" % (i, value)).encode('UTF-8'))

        for binary in iter:
            o.write(b"\n")
            binary.dump(o)
def update_control():
    """Update the debian control file.
    """
    from debian.deb822 import Deb822, PkgRelation
    f = open('debian/control', 'r')
    iter = Deb822.iter_paragraphs(f)
    source = iter.next()

    def update_deps(control, field, package, min_version, epoch=None):
        bdi = PkgRelation.parse_relations(control[field])
        if epoch is not None:
            epoch = "%d:" % epoch
        else:
            epoch = ""
        update_relation(bdi, package, ">=", epoch + "%d.%d.%d~" % min_version)
        control[field] = PkgRelation.str(bdi)

    tdb_version = find_version(os.path.join(tree, "lib/tdb/wscript"))
    talloc_version = find_version(os.path.join(tree, "lib/talloc/wscript"))
    ldb_version = find_version(os.path.join(tree, "lib/ldb/wscript"))
    tevent_version = find_version(os.path.join(tree, "lib/tevent/wscript"))

    eq_config = LibraryEquivalents('debian/library-equivalents')
    min_tdb_version = eq_config.find_oldest_compatible("tdb", tdb_version)
    min_talloc_version = eq_config.find_oldest_compatible("talloc", talloc_version)
    min_ldb_version = eq_config.find_oldest_compatible("ldb", ldb_version)
    min_tevent_version = eq_config.find_oldest_compatible("tevent", tevent_version)

    update_deps(source, "Build-Depends", "libtdb-dev", min_tdb_version)
    update_deps(source, "Build-Depends", "python-tdb", min_tdb_version)
    update_deps(source, "Build-Depends", "libtalloc-dev", min_talloc_version)
    update_deps(source, "Build-Depends", "python-talloc-dev", min_talloc_version)
    update_deps(source, "Build-Depends", "libldb-dev", min_ldb_version, 1)
    update_deps(source, "Build-Depends", "python-ldb-dev", min_ldb_version, 1)
    update_deps(source, "Build-Depends", "python-ldb", min_ldb_version, 1)
    update_deps(source, "Build-Depends", "libtevent-dev", min_tevent_version)

    o = open("debian/control", "w+")
    try:
        source.dump(o)

        for binary in iter:
            o.write("\n")
            binary.dump(o)
    finally:
        o.close()
Example #33
0
 def _remove(self, path, codename, component):
     for p in Deb822.iter_paragraphs(file(path)):
         if 'Source' in p:
             self._removesrc(p['Source'], codename)
         elif 'Package' in p:
             self._removedeb(p['Package'], codename)
Example #34
0
 def read(self):
     with open(self.path, 'r') as f:
         for repo822 in Deb822.iter_paragraphs(f, shared_storage=False):
             self.repos822.append(repo822)
Example #35
0
    if dists is None:
        dists = ('unstable (new queue)', )
    try:
        page = open_url(NEWQUEUE_URL, http_proxy, timeout)
    except NoNetwork:
        return {}
    except urllib2.HTTPError, x:
        print >> sys.stderr, "Warning:", x
        return {}
    if not page:
        return {}

    versions = {}

    # iter over the entries, one paragraph at a time
    for para in Deb822.iter_paragraphs(page):
        if para['Source'] == package:
            k = para['Distribution'] + ' (' + para['Queue']  + ')'
            versions[k] = para['Version']

    return versions

def get_incoming_version(package, timeout, http_proxy=None, arch='i386'):
    try:
        page = open_url(INCOMING_URL, http_proxy, timeout)
    except NoNetwork:
        return None
    except urllib2.HTTPError, x:
        print >> sys.stderr, "Warning:", x
        return None
    if not page:
Example #36
0
 def removesrc(self, path, component="main"):
     for p in Deb822.iter_paragraphs(file(path)):
         if 'Source' in p:
             self._removesrc(p['Source'], self.repo_attr.codename)