MiddleArch/middlearch/package.py

88 lines
3.1 KiB
Python

import hashlib, logging, os, re
import jinja2 as j2
import os.path as path
import requests as r
import yaml
from git import get_tag_from_git
class Package(object):
def __init__(self, name, **params):
self.name = name
self.repo = params.get("repo")
self.tag = params.get("tag") or get_tag_from_git(self.repo)
self.force = params.get("force", False)
self.render = params.get("render", True)
self.maintainers = params.get("maintainers", {})
self.contributors = params.get("contributors", {})
self.build = False
logging.debug(self)
def __repr__(self):
return f"{self.name} [repo: {self.repo}, tag: {self.tag}, force: {self.force}]"
def load(config_dir, repository):
with open(path.join(config_dir, "packages.yaml")) as file:
p_list = yaml.load(file, Loader=yaml.SafeLoader)
packages = []
for p in p_list:
package = Package(**p)
packages.append(package)
current_tag = repository.get_package_version(package.name)
if package.tag > current_tag:
logging.info(f"{package.name} will be updated ({current_tag}{package.tag})")
package.build = True
elif package.force:
logging.info(f"{package.name} will be updated ({package.tag})")
package.build = True
else:
logging.info(f"{package.name} will be skipped")
logging.info(f"{len(packages)} packages loaded")
return packages
def render_pkgbuild(self, config):
def get_hash(name, tag):
regex = re.compile("^source=.+(https://.+\.tar\.[a-z]+)", re.MULTILINE)
with open(f"{config.get('templates', 'templates')}/{name}.j2") as file:
content = file.read()
try:
url = regex.search(content).group(1)
except:
logging.warning(f"cannot find valid source for {name} (is it a git version?)")
return "SKIP"
url = url.replace("${pkgver}", tag)
url = url.replace("${pkgname}", name)
archive = r.get(url)
hash = hashlib.sha256(archive.content).hexdigest()
return hash
env = j2.Environment(
loader=j2.FileSystemLoader(config.get('templates', 'templates')),
autoescape=j2.select_autoescape([])
)
template = env.get_template(f"{self.name}.j2")
hash = get_hash(self.name, self.tag)
sysenv = j2.Environment(
loader=j2.FileSystemLoader('templates'),
autoescape=j2.select_autoescape([])
)
maintainers_template = sysenv.get_template("maintainers.j2")
dest_dir = path.join(config.get('pkgbuilds', "pkgbuilds"), self.name)
os.makedirs(dest_dir, exist_ok=True)
with open(f"{config.get('pkgbuilds')}/{self.name}/PKGBUILD", "w") as file:
file.write(maintainers_template.render(
maintainers=self.maintainers,
contributors=self.contributors
))
file.write(template.render(name=self.name, tag=self.tag, hash=hash))