130 lines
3.2 KiB
Python
Executable File

#!/usr/bin/env python3
#pylint: disable=invalid-name
'''
aptly-resource out
https://github.com/gopythongo/aptly-api-client
HTTPS_PROXY="http://localhost:8080" \
CURL_CA_BUNDLE="$HOME/.mitmproxy/mitmproxy-ca-cert.pem" \
./out_test.py
'''
import json
import sys
import os
import hashlib
import functools
from pprint import pprint
from aptly_api import Client
from aptly_api.base import AptlyAPIException
import semver
BLOCK_SIZE = 65536
root = os.path.dirname(os.path.abspath(__file__))
config = json.loads(sys.stdin.read())
directory = sys.argv[1]
aptly = Client(
config['source']['api_uri'],
http_auth = (
config['source']['username'],
config['source']['password']
),
timeout = config['source']['timeout']
)
try:
repo = aptly.repos.show(config['source']['repo'])
except AptlyAPIException as e:
if e.status_code != 404:
raise e
aptly.repos.create(
reponame = config['source']['repo'],
default_distribution = config['source']['distribution'],
default_component = config['source']['component']
)
with open(
directory + '/' + config['params']['archive_file'],
'r',
encoding = 'utf8'
) as f:
archive_path = f.read().strip()
archive_filename = archive_path.split('/', -1)[-1]
archive_filename_parts = archive_filename.split('_')
file_hash = hashlib.sha256()
with open(directory + '/' + archive_path, 'rb') as f:
fb = f.read(BLOCK_SIZE)
while len(fb) > 0:
file_hash.update(fb)
fb = f.read(BLOCK_SIZE)
aptly.files.upload(
config['source']['repo'],
directory + '/' + archive_path
)
aptly.repos.add_uploaded_file(
reponame = config['source']['repo'],
dir = config['source']['repo'],
remove_processed_files = True,
force_replace = True
)
aptly.publish.update(
prefix = config['source']['repo'],
distribution = config['source']['distribution'],
force_overwrite = True
)
if 'keep_versions' in config['source'] \
and config['source']['keep_versions'] > 0:
packages_delete = aptly.repos.search_packages(
'datentonne',
config['source']['package'] + ' (<= ' + archive_filename_parts[1] + ')'
)
versions_delete = []
for package in packages_delete:
package_data = package.key.split(' ')
versions_delete.append({
'version': package_data[2],
'key': package.key,
})
def compare_func(a, b):
return semver.compare(a['version'], b['version'])
versions_delete.sort(key=functools.cmp_to_key(compare_func))
versions_delete.reverse()
for i, package in enumerate(versions_delete):
if i >= config['source']['keep_versions']:
aptly.repos.delete_packages_by_key(
config['source']['repo'],
package['key'],
)
aptly.publish.update(
prefix = config['source']['repo'],
distribution = config['source']['distribution'],
force_overwrite = True
)
print(json.dumps({
'version': {'version': archive_filename_parts[1]},
'metadata': [
{'name': 'sha256', 'value': file_hash.hexdigest()}
]
}))