mirror of
https://github.com/arcan1s/ahriman.git
synced 2025-06-27 14:22:10 +00:00
Compare commits
71 Commits
Author | SHA1 | Date | |
---|---|---|---|
a5455b697d | |||
0bfb763b2a | |||
9f3566a150 | |||
16a6c4fdd7 | |||
91f66fdcee | |||
bb45b1d868 | |||
3d10fa472b | |||
a90c93bbc4 | |||
41a3c08d9f | |||
cb328ad797 | |||
810091cde9 | |||
fc0474fa8f | |||
b94179e071 | |||
9c5a9f5837 | |||
83047d8270 | |||
990d5dda81 | |||
48e79ce39c | |||
375d7c55e5 | |||
db52b8e844 | |||
50af309c80 | |||
581401d60f | |||
c2685f4746 | |||
952b55f707 | |||
b9b012be53 | |||
b8036649ab | |||
c90e20587e | |||
3e020ec141 | |||
783b7d043d | |||
5c297d1c67 | |||
b0d1f3c091 | |||
50e219fda5 | |||
75298d1b8a | |||
8196dcc8a0 | |||
f634f1df58 | |||
32df4fc54f | |||
11ae930c59 | |||
9c332c23d2 | |||
4ed0a49a44 | |||
50f532a48a | |||
c6ccf53768 | |||
ce0c07cbd9 | |||
912a76d5cb | |||
76d0b0bc6d | |||
27d018e721 | |||
a0e20ffb77 | |||
96e4abc3c0 | |||
6df60498aa | |||
eb0a4b6b4a | |||
8f469e7eac | |||
535e955814 | |||
0bd3ba626a | |||
ffe6aec190 | |||
56c600e5ac | |||
461883217d | |||
62d55eff19 | |||
534b5600b4 | |||
32cbafd12b | |||
880c70bd58 | |||
d449eb3c2e | |||
17b5cd0751 | |||
2aef906fc8 | |||
e034327501 | |||
5d79fcca22 | |||
6e9dcca254 | |||
fbf6748d4a | |||
2260e52d5c | |||
bd2b61494f | |||
7280d30748 | |||
710274065d | |||
e0b09cefad | |||
3b93510aad |
1
.bandit-test.yml
Normal file
1
.bandit-test.yml
Normal file
@ -0,0 +1 @@
|
||||
skips: ['B101', 'B404']
|
1
.bandit.yml
Normal file
1
.bandit.yml
Normal file
@ -0,0 +1 @@
|
||||
skips: ['B404', 'B603']
|
37
.github/workflows/release.yml
vendored
Normal file
37
.github/workflows/release.yml
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
name: release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*.*.*'
|
||||
|
||||
jobs:
|
||||
make-release:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- name: extract version
|
||||
id: version
|
||||
run: echo ::set-output name=VERSION::${GITHUB_REF#refs/tags/}
|
||||
- name: create changelog
|
||||
id: changelog
|
||||
uses: jaywcjlove/changelog-generator@main
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
filter: 'Release \d+\.\d+\.\d+'
|
||||
- name: create archive
|
||||
run: make archive
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.VERSION }}
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
body: |
|
||||
${{ steps.changelog.outputs.compareurl }}
|
||||
${{ steps.changelog.outputs.changelog }}
|
||||
files: ahriman-*-src.tar.xz
|
||||
fail_on_unmatched_files: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
@ -1,6 +1,4 @@
|
||||
# based on https://github.com/actions/starter-workflows/blob/main/ci/python-app.yml
|
||||
|
||||
name: ahriman
|
||||
name: tests
|
||||
|
||||
on:
|
||||
push:
|
||||
@ -9,7 +7,7 @@ on:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
run-tests:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@ -20,8 +18,9 @@ jobs:
|
||||
docker run \
|
||||
-v ${{ github.workspace }}:/build -w /build \
|
||||
archlinux:latest \
|
||||
/bin/bash -c "pacman --noconfirm -Syu base-devel python python-pip && \
|
||||
/bin/bash -c "pacman --noconfirm -Syu base-devel python-argparse-manpage python-pip && \
|
||||
pip install -e .[web] && \
|
||||
pip install -e .[check] && \
|
||||
pip install -e .[s3] && \
|
||||
pip install -e .[test] && \
|
||||
make check tests"
|
2
.gitignore
vendored
2
.gitignore
vendored
@ -94,3 +94,5 @@ ENV/
|
||||
.venv/
|
||||
|
||||
*.tar.xz
|
||||
|
||||
man/
|
||||
|
@ -22,7 +22,7 @@ ignore-patterns=
|
||||
|
||||
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
|
||||
# number of processors available to use.
|
||||
jobs=1
|
||||
jobs=0
|
||||
|
||||
# Control the amount of potential inferred values when inferring a single
|
||||
# object. This can help the performance when dealing with large functions or
|
||||
@ -149,7 +149,6 @@ disable=print-statement,
|
||||
too-few-public-methods,
|
||||
too-many-instance-attributes,
|
||||
broad-except,
|
||||
logging-fstring-interpolation,
|
||||
too-many-ancestors,
|
||||
fixme,
|
||||
too-many-arguments,
|
||||
|
@ -1,6 +1,6 @@
|
||||
# ahriman configuration
|
||||
|
||||
Some groups can be specified for each architecture separately. E.g. if there are `build` and `build_x86_64` groups it will use the `build_x86_64` for the `x86_64` architecture and `build` for any other (architecture specific group has higher priority).
|
||||
Some groups can be specified for each architecture separately. E.g. if there are `build` and `build:x86_64` groups it will use the option from `build:x86_64` for the `x86_64` architecture and `build` for any other (architecture specific group has higher priority). In case if both groups are presented, architecture specific options will be merged into global ones overriding them.
|
||||
|
||||
## `settings` group
|
||||
|
||||
@ -18,9 +18,9 @@ libalpm and AUR related configuration.
|
||||
* `repositories` - list of pacman repositories, space separated list of strings, required.
|
||||
* `root` - root for alpm library, string, required.
|
||||
|
||||
## `build_*` groups
|
||||
## `build:*` groups
|
||||
|
||||
Build related configuration. Group name must refer to architecture, e.g. it should be `build_x86_64` for x86_64 architecture.
|
||||
Build related configuration. Group name must refer to architecture, e.g. it should be `build:x86_64` for x86_64 architecture.
|
||||
|
||||
* `archbuild_flags` - additional flags passed to `archbuild` command, space separated list of strings, optional.
|
||||
* `build_command` - default build command, string, required.
|
||||
@ -35,9 +35,9 @@ Base repository settings.
|
||||
* `name` - repository name, string, required.
|
||||
* `root` - root path for application, string, required.
|
||||
|
||||
## `sign_*` groups
|
||||
## `sign:*` groups
|
||||
|
||||
Settings for signing packages or repository. Group name must refer to architecture, e.g. it should be `sign_x86_64` for x86_64 architecture.
|
||||
Settings for signing packages or repository. Group name must refer to architecture, e.g. it should be `sign:x86_64` for x86_64 architecture.
|
||||
|
||||
* `target` - configuration flag to enable signing, space separated list of strings, required. Allowed values are `package` (sign each package separately), `repository` (sign repository database file).
|
||||
* `key` - default PGP key, string, required. This key will also be used for database signing if enabled.
|
||||
@ -47,11 +47,27 @@ Settings for signing packages or repository. Group name must refer to architectu
|
||||
|
||||
Report generation settings.
|
||||
|
||||
* `target` - list of reports to be generated, space separated list of strings, optional. Allowed values are `html`.
|
||||
* `target` - list of reports to be generated, space separated list of strings, optional. Allowed values are `html`, `email`.
|
||||
|
||||
### `html_*` groups
|
||||
### `email:*` groups
|
||||
|
||||
Group name must refer to architecture, e.g. it should be `html_x86_64` for x86_64 architecture.
|
||||
Group name must refer to architecture, e.g. it should be `email:x86_64` for x86_64 architecture.
|
||||
|
||||
* `homepage` - link to homepage, string, optional.
|
||||
* `host` - SMTP host for sending emails, string, required.
|
||||
* `link_path` - prefix for HTML links, string, required.
|
||||
* `no_empty_report` - skip report generation for empty packages list, boolean, optional, default `yes`.
|
||||
* `password` - SMTP password to authenticate, string, optional.
|
||||
* `port` - SMTP port for sending emails, int, required.
|
||||
* `receivers` - SMTP receiver addresses, space separated list of strings, required.
|
||||
* `sender` - SMTP sender address, string, required.
|
||||
* `ssl` - SSL mode for SMTP connection, one of `ssl`, `starttls`, `disabled`, optional, default `disabled`.
|
||||
* `template_path` - path to Jinja2 template, string, required.
|
||||
* `user` - SMTP user to authenticate, string, optional.
|
||||
|
||||
### `html:*` groups
|
||||
|
||||
Group name must refer to architecture, e.g. it should be `html:x86_64` for x86_64 architecture.
|
||||
|
||||
* `path` - path to html report file, string, required.
|
||||
* `homepage` - link to homepage, string, optional.
|
||||
@ -64,21 +80,26 @@ Remote synchronization settings.
|
||||
|
||||
* `target` - list of synchronizations to be used, space separated list of strings, optional. Allowed values are `rsync`, `s3`.
|
||||
|
||||
### `rsync_*` groups
|
||||
### `rsync:*` groups
|
||||
|
||||
Group name must refer to architecture, e.g. it should be `rsync_x86_64` for x86_64 architecture. Requires `rsync` package to be installed. Do not forget to configure ssh for user `ahriman`.
|
||||
Group name must refer to architecture, e.g. it should be `rsync:x86_64` for x86_64 architecture. Requires `rsync` package to be installed. Do not forget to configure ssh for user `ahriman`.
|
||||
|
||||
* `command` - rsync command to run, space separated list of string, required.
|
||||
* `remote` - remote server to rsync (e.g. `1.2.3.4:5678:path/to/sync`), string, required.
|
||||
|
||||
### `s3_*` groups
|
||||
### `s3:*` groups
|
||||
|
||||
Group name must refer to architecture, e.g. it should be `s3_x86_64` for x86_64 architecture. Requires `aws-cli` package to be installed. Do not forget to configure it for user `ahriman`.
|
||||
Group name must refer to architecture, e.g. it should be `s3:x86_64` for x86_64 architecture.
|
||||
|
||||
* `bucket` - bucket name (e.g. `s3://bucket/path`), string, required.
|
||||
* `access_key` - AWS access key ID, string, required.
|
||||
* `bucket` - bucket name (e.g. `bucket`), string, required.
|
||||
* `chunk_size` - chunk size for calculating entity tags, int, optional, default 8 * 1024 * 1024.
|
||||
* `region` - bucket region (e.g. `eu-central-1`), string, required.
|
||||
* `secret_key` - AWS secret access key, string, required.
|
||||
|
||||
## `web_*` groups
|
||||
## `web:*` groups
|
||||
|
||||
Web server settings. If any of `host`/`port` is not set, web integration will be disabled. Group name must refer to architecture, e.g. it should be `web_x86_64` for x86_64 architecture.
|
||||
Web server settings. If any of `host`/`port` is not set, web integration will be disabled. Group name must refer to architecture, e.g. it should be `web:x86_64` for x86_64 architecture.
|
||||
|
||||
* `host` - host to bind, string, optional.
|
||||
* `port` - port to bind, int, optional.
|
||||
|
20
Makefile
20
Makefile
@ -3,7 +3,7 @@
|
||||
|
||||
PROJECT := ahriman
|
||||
|
||||
FILES := AUTHORS COPYING CONFIGURING.md README.md package src setup.py
|
||||
FILES := AUTHORS COPYING CONFIGURING.md README.md package src setup.cfg setup.py
|
||||
TARGET_FILES := $(addprefix $(PROJECT)/, $(FILES))
|
||||
IGNORE_FILES := package/archlinux src/.mypy_cache
|
||||
|
||||
@ -21,13 +21,13 @@ archive_directory: $(TARGET_FILES)
|
||||
find "$(PROJECT)" -depth -type d -name "*.egg-info" -execdir rm -rf {} +
|
||||
|
||||
archlinux: archive
|
||||
sed -i "/sha512sums=('[0-9A-Fa-f]*/s/[^'][^)]*/sha512sums=('$$(sha512sum $(PROJECT)-$(VERSION)-src.tar.xz | awk '{print $$1}')'/" package/archlinux/PKGBUILD
|
||||
sed -i "s/pkgver=[0-9.]*/pkgver=$(VERSION)/" package/archlinux/PKGBUILD
|
||||
|
||||
check:
|
||||
cd src && mypy --implicit-reexport --strict -p "$(PROJECT)"
|
||||
find "src/$(PROJECT)" tests -name "*.py" -execdir autopep8 --exit-code --max-line-length 120 -aa -i {} +
|
||||
cd src && pylint --rcfile=../.pylintrc "$(PROJECT)"
|
||||
check: clean mypy
|
||||
autopep8 --exit-code --max-line-length 120 -aa -i -j 0 -r "src/$(PROJECT)" "tests/$(PROJECT)"
|
||||
pylint --rcfile=.pylintrc "src/$(PROJECT)"
|
||||
bandit -c .bandit.yml -r "src/$(PROJECT)"
|
||||
bandit -c .bandit-test.yml -r "tests/$(PROJECT)"
|
||||
|
||||
clean:
|
||||
find . -type f -name "$(PROJECT)-*-src.tar.xz" -delete
|
||||
@ -36,14 +36,18 @@ clean:
|
||||
directory: clean
|
||||
mkdir "$(PROJECT)"
|
||||
|
||||
mypy:
|
||||
cd src && mypy --implicit-reexport --strict -p "$(PROJECT)" --install-types --non-interactive || true
|
||||
cd src && mypy --implicit-reexport --strict -p "$(PROJECT)"
|
||||
|
||||
push: archlinux
|
||||
git add package/archlinux/PKGBUILD src/ahriman/version.py
|
||||
git commit -m "Release $(VERSION)"
|
||||
git push
|
||||
git tag "$(VERSION)"
|
||||
git push
|
||||
git push --tags
|
||||
|
||||
tests:
|
||||
tests: clean
|
||||
python setup.py test
|
||||
|
||||
version:
|
||||
|
@ -1,5 +1,8 @@
|
||||
# ArcHlinux ReposItory MANager
|
||||
|
||||
[](https://github.com/arcan1s/ahriman/actions/workflows/run-tests.yml)
|
||||
[](https://www.codefactor.io/repository/github/arcan1s/ahriman)
|
||||
|
||||
Wrapper for managing custom repository inspired by [repo-scripts](https://github.com/arcan1s/repo-scripts).
|
||||
|
||||
## Features
|
||||
@ -64,7 +67,7 @@ Wrapper for managing custom repository inspired by [repo-scripts](https://github
|
||||
* Add packages by using `ahriman add {package}` command:
|
||||
|
||||
```shell
|
||||
sudo -u ahriman ahriman -a x86_64 add yay
|
||||
sudo -u ahriman ahriman -a x86_64 add yay --now
|
||||
```
|
||||
|
||||
Note that initial service configuration can be done by running `ahriman setup` with specific arguments.
|
||||
|
@ -1,31 +1,27 @@
|
||||
# Maintainer: Evgeniy Alekseev
|
||||
|
||||
pkgname='ahriman'
|
||||
pkgver=0.18.0
|
||||
pkgver=1.2.5
|
||||
pkgrel=1
|
||||
pkgdesc="ArcHlinux ReposItory MANager"
|
||||
arch=('any')
|
||||
url="https://github.com/arcan1s/ahriman"
|
||||
license=('GPL3')
|
||||
depends=('devtools' 'git' 'pyalpm' 'python-aur' 'python-srcinfo')
|
||||
makedepends=('python-pip')
|
||||
optdepends=('aws-cli: sync to s3'
|
||||
'breezy: -bzr packages support'
|
||||
makedepends=('python-argparse-manpage' 'python-pip')
|
||||
optdepends=('breezy: -bzr packages support'
|
||||
'darcs: -darcs packages support'
|
||||
'gnupg: package and repository sign'
|
||||
'mercurial: -hg packages support'
|
||||
'python-aiohttp: web server'
|
||||
'python-aiohttp-jinja2: web server'
|
||||
'python-boto3: sync to s3'
|
||||
'python-jinja: html report generation'
|
||||
'python-requests: web server'
|
||||
'rsync: sync by using rsync'
|
||||
'subversion: -svn packages support')
|
||||
source=("https://github.com/arcan1s/ahriman/releases/download/$pkgver/$pkgname-$pkgver-src.tar.xz"
|
||||
'ahriman.sysusers'
|
||||
'ahriman.tmpfiles')
|
||||
sha512sums=('8acc57f937d587ca665c29092cadddbaf3ba0b80e870b80d1551e283aba8f21306f9030a26fec8c71ab5863316f5f5f061b7ddc63cdff9e6d5a885f28ef1893d'
|
||||
'13718afec2c6786a18f0b223ef8e58dccf0688bca4cdbe203f14071f5031ed20120eb0ce38b52c76cfd6e8b6581a9c9eaa2743eb11abbaca637451a84c33f075'
|
||||
'55b20f6da3d66e7bbf2add5d95a3b60632df121717d25a993e56e737d14f51fe063eb6f1b38bd81cc32e05db01c0c1d80aaa720c45cde87f238d8b46cdb8cbc4')
|
||||
backup=('etc/ahriman.ini'
|
||||
'etc/ahriman.ini.d/logging.ini')
|
||||
|
||||
@ -43,3 +39,7 @@ package() {
|
||||
install -Dm644 "$srcdir/$pkgname.sysusers" "$pkgdir/usr/lib/sysusers.d/$pkgname.conf"
|
||||
install -Dm644 "$srcdir/$pkgname.tmpfiles" "$pkgdir/usr/lib/tmpfiles.d/$pkgname.conf"
|
||||
}
|
||||
|
||||
sha512sums=('6ab741bfb42f92ab00d1b6ecfc44426c00e5c433486e014efbdb585715d9a12dbbafc280e5a9f85b941c8681b13a9dad41327a3e3c44a9683ae30c1d6f017f50'
|
||||
'13718afec2c6786a18f0b223ef8e58dccf0688bca4cdbe203f14071f5031ed20120eb0ce38b52c76cfd6e8b6581a9c9eaa2743eb11abbaca637451a84c33f075'
|
||||
'55b20f6da3d66e7bbf2add5d95a3b60632df121717d25a993e56e737d14f51fe063eb6f1b38bd81cc32e05db01c0c1d80aaa720c45cde87f238d8b46cdb8cbc4')
|
||||
|
@ -1,2 +1 @@
|
||||
d /var/lib/ahriman 0775 ahriman log
|
||||
d /var/log/ahriman 0755 ahriman ahriman
|
@ -13,7 +13,7 @@ archbuild_flags =
|
||||
build_command = extra-x86_64-build
|
||||
ignore_packages =
|
||||
makechrootpkg_flags =
|
||||
makepkg_flags = --skippgpcheck
|
||||
makepkg_flags =
|
||||
|
||||
[repository]
|
||||
name = aur-clone
|
||||
@ -21,25 +21,27 @@ root = /var/lib/ahriman
|
||||
|
||||
[sign]
|
||||
target =
|
||||
key =
|
||||
|
||||
[report]
|
||||
target =
|
||||
|
||||
[email]
|
||||
no_empty_report = yes
|
||||
template_path = /usr/share/ahriman/repo-index.jinja2
|
||||
ssl = disabled
|
||||
|
||||
[html]
|
||||
path =
|
||||
homepage =
|
||||
link_path =
|
||||
template_path = /usr/share/ahriman/repo-index.jinja2
|
||||
|
||||
[upload]
|
||||
target =
|
||||
|
||||
[rsync]
|
||||
remote =
|
||||
command = rsync --archive --compress --partial --delete
|
||||
|
||||
[s3]
|
||||
bucket =
|
||||
chunk_size = 8388608
|
||||
|
||||
[web]
|
||||
host = 127.0.0.1
|
||||
templates = /usr/share/ahriman
|
@ -2,10 +2,10 @@
|
||||
keys = root,builder,build_details,http
|
||||
|
||||
[handlers]
|
||||
keys = console_handler,build_file_handler,file_handler,http_handler
|
||||
keys = console_handler,build_file_handler,file_handler,http_handler,syslog_handler
|
||||
|
||||
[formatters]
|
||||
keys = generic_format
|
||||
keys = generic_format,syslog_format
|
||||
|
||||
[handler_console_handler]
|
||||
class = StreamHandler
|
||||
@ -31,29 +31,39 @@ level = DEBUG
|
||||
formatter = generic_format
|
||||
args = ("/var/log/ahriman/http.log", "a", 20971520, 20)
|
||||
|
||||
[handler_syslog_handler]
|
||||
class = logging.handlers.SysLogHandler
|
||||
level = DEBUG
|
||||
formatter = syslog_format
|
||||
args = ("/dev/log",)
|
||||
|
||||
[formatter_generic_format]
|
||||
format = [%(levelname)s %(asctime)s] [%(filename)s:%(lineno)d] [%(funcName)s]: %(message)s
|
||||
datefmt =
|
||||
|
||||
[formatter_syslog_format]
|
||||
format = [%(levelname)s] [%(filename)s:%(lineno)d] [%(funcName)s]: %(message)s
|
||||
datefmt =
|
||||
|
||||
[logger_root]
|
||||
level = DEBUG
|
||||
handlers = file_handler
|
||||
handlers = syslog_handler
|
||||
qualname = root
|
||||
|
||||
[logger_builder]
|
||||
level = DEBUG
|
||||
handlers = file_handler
|
||||
handlers = syslog_handler
|
||||
qualname = builder
|
||||
propagate = 0
|
||||
|
||||
[logger_build_details]
|
||||
level = DEBUG
|
||||
handlers = build_file_handler
|
||||
handlers = syslog_handler
|
||||
qualname = build_details
|
||||
propagate = 0
|
||||
|
||||
[logger_http]
|
||||
level = DEBUG
|
||||
handlers = http_handler
|
||||
handlers = syslog_handler
|
||||
qualname = http
|
||||
propagate = 0
|
||||
|
@ -1,7 +1,7 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>{{ repository|e }}</title>
|
||||
<title>{{ repository }}</title>
|
||||
|
||||
{% include "style.jinja2" %}
|
||||
|
||||
@ -12,9 +12,9 @@
|
||||
<body>
|
||||
<div class="root">
|
||||
<h1>ahriman
|
||||
<img src="https://img.shields.io/badge/version-{{ version|e }}-informational" alt="{{ version|e }}">
|
||||
<img src="https://img.shields.io/badge/architecture-{{ architecture|e }}-informational" alt="{{ architecture|e }}">
|
||||
<img src="https://img.shields.io/badge/service%20status-{{ service.status|e }}-{{ service.status_color|e }}" alt="{{ service.status|e }}" title="{{ service.timestamp|e }}">
|
||||
<img src="https://img.shields.io/badge/version-{{ version }}-informational" alt="{{ version }}">
|
||||
<img src="https://img.shields.io/badge/architecture-{{ architecture }}-informational" alt="{{ architecture }}">
|
||||
<img src="https://img.shields.io/badge/service%20status-{{ service.status }}-{{ service.status_color }}" alt="{{ service.status }}" title="{{ service.timestamp }}">
|
||||
</h1>
|
||||
|
||||
{% include "search-line.jinja2" %}
|
||||
@ -31,11 +31,11 @@
|
||||
|
||||
{% for package in packages %}
|
||||
<tr class="package">
|
||||
<td class="include-search"><a href="{{ package.web_url|e }}" title="{{ package.base|e }}">{{ package.base|e }}</a></td>
|
||||
<td class="include-search"><a href="{{ package.web_url }}" title="{{ package.base }}">{{ package.base }}</a></td>
|
||||
<td class="include-search">{{ package.packages|join("<br>"|safe) }}</td>
|
||||
<td>{{ package.version|e }}</td>
|
||||
<td>{{ package.timestamp|e }}</td>
|
||||
<td class="status package-{{ package.status|e }}">{{ package.status|e }}</td>
|
||||
<td>{{ package.version }}</td>
|
||||
<td>{{ package.timestamp }}</td>
|
||||
<td class="status package-{{ package.status }}">{{ package.status }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
|
@ -1,32 +1,36 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>{{ repository|e }}</title>
|
||||
<title>{{ repository }}</title>
|
||||
|
||||
{% include "style.jinja2" %}
|
||||
|
||||
{% include "sorttable.jinja2" %}
|
||||
{% include "search.jinja2" %}
|
||||
{% if extended_report %}
|
||||
{% include "sorttable.jinja2" %}
|
||||
{% include "search.jinja2" %}
|
||||
{% endif %}
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="root">
|
||||
<h1>Archlinux user repository</h1>
|
||||
{% if extended_report %}
|
||||
<h1>Archlinux user repository</h1>
|
||||
|
||||
<section class="element">
|
||||
{% if pgp_key is not none %}
|
||||
<p>This repository is signed with <a href="http://keys.gnupg.net/pks/lookup?search=0x{{ pgp_key|e }}&fingerprint=on&op=index" title="key search">{{ pgp_key|e }}</a> by default.</p>
|
||||
{% endif %}
|
||||
<section class="element">
|
||||
{% if pgp_key is not none %}
|
||||
<p>This repository is signed with <a href="http://keys.gnupg.net/pks/lookup?search=0x{{ pgp_key }}&fingerprint=on&op=index" title="key search">{{ pgp_key }}</a> by default.</p>
|
||||
{% endif %}
|
||||
|
||||
<code>
|
||||
$ cat /etc/pacman.conf<br>
|
||||
[{{ repository|e }}]<br>
|
||||
Server = {{ link_path|e }}<br>
|
||||
SigLevel = Database{% if has_repo_signed %}Required{% else %}Never{% endif %} Package{% if has_package_signed %}Required{% else %}Never{% endif %} TrustedOnly
|
||||
</code>
|
||||
</section>
|
||||
|
||||
{% include "search-line.jinja2" %}
|
||||
<code>
|
||||
$ cat /etc/pacman.conf<br>
|
||||
[{{ repository }}]<br>
|
||||
Server = {{ link_path }}<br>
|
||||
SigLevel = Database{% if has_repo_signed %}Required{% else %}Never{% endif %} Package{% if has_package_signed %}Required{% else %}Never{% endif %} TrustedOnly
|
||||
</code>
|
||||
</section>
|
||||
|
||||
{% include "search-line.jinja2" %}
|
||||
{% endif %}
|
||||
|
||||
<section class="element">
|
||||
<table class="sortable search-table">
|
||||
@ -40,23 +44,25 @@
|
||||
|
||||
{% for package in packages %}
|
||||
<tr class="package">
|
||||
<td class="include-search"><a href="{{ link_path|e }}/{{ package.filename|e }}" title="{{ package.name|e }}">{{ package.name|e }}</a></td>
|
||||
<td>{{ package.version|e }}</td>
|
||||
<td>{{ package.archive_size|e }}</td>
|
||||
<td>{{ package.installed_size|e }}</td>
|
||||
<td>{{ package.build_date|e }}</td>
|
||||
<td class="include-search"><a href="{{ link_path }}/{{ package.filename }}" title="{{ package.name }}">{{ package.name }}</a></td>
|
||||
<td>{{ package.version }}</td>
|
||||
<td>{{ package.archive_size }}</td>
|
||||
<td>{{ package.installed_size }}</td>
|
||||
<td>{{ package.build_date }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<footer>
|
||||
<ul class="navigation">
|
||||
{% if homepage is not none %}
|
||||
<li><a href="{{ homepage|e }}" title="homepage">Homepage</a></li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</footer>
|
||||
{% if extended_report %}
|
||||
<footer>
|
||||
<ul class="navigation">
|
||||
{% if homepage is not none %}
|
||||
<li><a href="{{ homepage }}" title="homepage">Homepage</a></li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</footer>
|
||||
{% endif %}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
@ -1,3 +1,3 @@
|
||||
<section class="element">
|
||||
<input type="search" id="search" onkeyup="searchInTable()" placeholder="search for package" title="search for package"/>
|
||||
</section>
|
||||
</section>
|
||||
|
@ -5,21 +5,22 @@
|
||||
const tables = document.getElementsByClassName("search-table");
|
||||
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
const tr = tables[i].getElementsByTagName("tr");
|
||||
const trs = tables[i].getElementsByTagName("tr");
|
||||
// from 1 coz of header
|
||||
for (let i = 1; i < tr.length; i++) {
|
||||
let td = tr[i].getElementsByClassName("include-search");
|
||||
for (let i = 1; i < trs.length; i++) {
|
||||
let tr = trs[i].getElementsByClassName("include-search");
|
||||
let display = "none";
|
||||
for (let j = 0; j < td.length; j++) {
|
||||
if (td[j].tagName.toLowerCase() === "td") {
|
||||
if (td[j].innerHTML.toLowerCase().indexOf(filter) > -1) {
|
||||
for (let j = 0; j < tr.length; j++) {
|
||||
if (tr[j].tagName.toLowerCase() === "td") {
|
||||
let contains = (element) => tr[j].innerHTML.toLowerCase().indexOf(element) > -1
|
||||
if (filter.some(contains)) {
|
||||
display = "";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
tr[i].style.display = display;
|
||||
trs[i].style.display = display;
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</script>
|
||||
|
@ -1 +1 @@
|
||||
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
|
||||
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
|
||||
|
@ -133,4 +133,4 @@
|
||||
ul.navigation li a:hover {
|
||||
background-color: rgba(var(--color-hover), 1.0);
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
|
@ -2,4 +2,7 @@
|
||||
test = pytest
|
||||
|
||||
[tool:pytest]
|
||||
addopts = --cov=ahriman --pspec
|
||||
addopts = --cov=ahriman --cov-report term-missing:skip-covered --pspec
|
||||
|
||||
[build_manpages]
|
||||
manpages = man/ahriman.1:module=ahriman.application.ahriman:function=_parser
|
||||
|
25
setup.py
25
setup.py
@ -1,11 +1,14 @@
|
||||
from distutils.util import convert_path
|
||||
from build_manpages import build_manpages
|
||||
from pathlib import Path
|
||||
from setuptools import setup, find_packages
|
||||
from os import path
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
metadata_path = Path(__file__).resolve().parent / "src/ahriman/version.py"
|
||||
metadata: Dict[str, Any] = dict()
|
||||
with metadata_path.open() as metadata_file:
|
||||
exec(metadata_file.read(), metadata) # pylint: disable=exec-used
|
||||
|
||||
here = path.abspath(path.dirname(__file__))
|
||||
metadata = dict()
|
||||
with open(convert_path("src/ahriman/version.py")) as metadata_file:
|
||||
exec(metadata_file.read(), metadata)
|
||||
|
||||
setup(
|
||||
name="ahriman",
|
||||
@ -29,6 +32,7 @@ setup(
|
||||
install_requires=[
|
||||
"aur",
|
||||
"pyalpm",
|
||||
"requests",
|
||||
"srcinfo",
|
||||
],
|
||||
setup_requires=[
|
||||
@ -73,9 +77,13 @@ setup(
|
||||
extras_require={
|
||||
"check": [
|
||||
"autopep8",
|
||||
"bandit",
|
||||
"mypy",
|
||||
"pylint",
|
||||
],
|
||||
"s3": [
|
||||
"boto3",
|
||||
],
|
||||
"test": [
|
||||
"pytest",
|
||||
"pytest-aiohttp",
|
||||
@ -89,7 +97,10 @@ setup(
|
||||
"Jinja2",
|
||||
"aiohttp",
|
||||
"aiohttp_jinja2",
|
||||
"requests",
|
||||
],
|
||||
},
|
||||
|
||||
cmdclass={
|
||||
"build_manpages": build_manpages.build_manpages,
|
||||
}
|
||||
)
|
||||
|
@ -19,16 +19,18 @@
|
||||
#
|
||||
import argparse
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import ahriman.application.handlers as handlers
|
||||
import ahriman.version as version
|
||||
from pathlib import Path
|
||||
|
||||
from ahriman import version
|
||||
from ahriman.application import handlers
|
||||
from ahriman.models.build_status import BuildStatusEnum
|
||||
from ahriman.models.sign_settings import SignSettings
|
||||
|
||||
|
||||
# pylint thinks it is bad idea, but get the fuck off
|
||||
# pylint: disable=protected-access
|
||||
SubParserAction = argparse._SubParsersAction
|
||||
SubParserAction = argparse._SubParsersAction # pylint: disable=protected-access
|
||||
|
||||
|
||||
def _parser() -> argparse.ArgumentParser:
|
||||
@ -36,12 +38,18 @@ def _parser() -> argparse.ArgumentParser:
|
||||
command line parser generator
|
||||
:return: command line parser for the application
|
||||
"""
|
||||
parser = argparse.ArgumentParser(prog="ahriman", description="ArcHlinux ReposItory MANager")
|
||||
parser = argparse.ArgumentParser(prog="ahriman", description="ArcHlinux ReposItory MANager",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("-a", "--architecture", help="target architectures (can be used multiple times)",
|
||||
action="append", required=True)
|
||||
parser.add_argument("-c", "--config", help="configuration path", default="/etc/ahriman.ini")
|
||||
action="append")
|
||||
parser.add_argument("-c", "--configuration", help="configuration path", type=Path, default=Path("/etc/ahriman.ini"))
|
||||
parser.add_argument("--force", help="force run, remove file lock", action="store_true")
|
||||
parser.add_argument("--lock", help="lock file", default="/tmp/ahriman.lock")
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--lock",
|
||||
help="lock file",
|
||||
type=Path,
|
||||
default=Path(tempfile.gettempdir()) / "ahriman.lock")
|
||||
parser.add_argument("--no-log", help="redirect all log messages to stderr", action="store_true")
|
||||
parser.add_argument("--no-report", help="force disable reporting to web service", action="store_true")
|
||||
parser.add_argument("--unsafe", help="allow to run ahriman as non-ahriman user", action="store_true")
|
||||
@ -53,9 +61,12 @@ def _parser() -> argparse.ArgumentParser:
|
||||
_set_check_parser(subparsers)
|
||||
_set_clean_parser(subparsers)
|
||||
_set_config_parser(subparsers)
|
||||
_set_init_parser(subparsers)
|
||||
_set_key_import_parser(subparsers)
|
||||
_set_rebuild_parser(subparsers)
|
||||
_set_remove_parser(subparsers)
|
||||
_set_report_parser(subparsers)
|
||||
_set_search_parser(subparsers)
|
||||
_set_setup_parser(subparsers)
|
||||
_set_sign_parser(subparsers)
|
||||
_set_status_parser(subparsers)
|
||||
@ -73,10 +84,12 @@ def _set_add_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("add", description="add package")
|
||||
parser = root.add_parser("add", help="add package", description="add package",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("package", help="package base/name or archive path", nargs="+")
|
||||
parser.add_argument("--now", help="run update function after", action="store_true")
|
||||
parser.add_argument("--without-dependencies", help="do not add dependencies", action="store_true")
|
||||
parser.set_defaults(handler=handlers.Add)
|
||||
parser.set_defaults(handler=handlers.Add, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
@ -86,10 +99,12 @@ def _set_check_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("check", description="check for updates. Same as update --dry-run --no-manual")
|
||||
parser = root.add_parser("check", help="check for updates",
|
||||
description="check for updates. Same as update --dry-run --no-manual",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("package", help="filter check by package base", nargs="*")
|
||||
parser.add_argument("--no-vcs", help="do not check VCS packages", action="store_true")
|
||||
parser.set_defaults(handler=handlers.Update, no_aur=False, no_manual=True, dry_run=True)
|
||||
parser.set_defaults(handler=handlers.Update, architecture=[], no_aur=False, no_manual=True, dry_run=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -99,13 +114,14 @@ def _set_clean_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("clean", description="clear all local caches")
|
||||
parser = root.add_parser("clean", help="clean local caches", description="clear local caches",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--no-build", help="do not clear directory with package sources", action="store_true")
|
||||
parser.add_argument("--no-cache", help="do not clear directory with package caches", action="store_true")
|
||||
parser.add_argument("--no-chroot", help="do not clear build chroot", action="store_true")
|
||||
parser.add_argument("--no-manual", help="do not clear directory with manually added packages", action="store_true")
|
||||
parser.add_argument("--no-packages", help="do not clear directory with built packages", action="store_true")
|
||||
parser.set_defaults(handler=handlers.Clean, unsafe=True)
|
||||
parser.set_defaults(handler=handlers.Clean, architecture=[], no_log=True, unsafe=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -115,8 +131,38 @@ def _set_config_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("config", description="dump configuration for specified architecture")
|
||||
parser.set_defaults(handler=handlers.Dump, lock=None, no_report=True, unsafe=True)
|
||||
parser = root.add_parser("config", help="dump configuration",
|
||||
description="dump configuration for specified architecture",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.set_defaults(handler=handlers.Dump, lock=None, no_log=True, no_report=True, unsafe=True)
|
||||
return parser
|
||||
|
||||
|
||||
def _set_init_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
"""
|
||||
add parser for init subcommand
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("init", help="create repository tree",
|
||||
description="create empty repository tree. Optional command for auto architecture support",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.set_defaults(handler=handlers.Init, no_report=True)
|
||||
return parser
|
||||
|
||||
|
||||
def _set_key_import_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
"""
|
||||
add parser for key import subcommand
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("key-import", help="import PGP key",
|
||||
description="import PGP key from public sources to repository user",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--key-server", help="key server for key import", default="keys.gnupg.net")
|
||||
parser.add_argument("key", help="PGP key to import from public server")
|
||||
parser.set_defaults(handler=handlers.KeyImport, architecture=[""], lock=None, no_report=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -126,8 +172,10 @@ def _set_rebuild_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("rebuild", description="rebuild whole repository")
|
||||
parser.set_defaults(handler=handlers.Rebuild)
|
||||
parser = root.add_parser("rebuild", help="rebuild repository", description="rebuild whole repository",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--depends-on", help="only rebuild packages that depend on specified package", action="append")
|
||||
parser.set_defaults(handler=handlers.Rebuild, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
@ -137,9 +185,10 @@ def _set_remove_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("remove", description="remove package")
|
||||
parser = root.add_parser("remove", help="remove package", description="remove package",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("package", help="package name or base", nargs="+")
|
||||
parser.set_defaults(handler=handlers.Remove)
|
||||
parser.set_defaults(handler=handlers.Remove, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
@ -149,9 +198,22 @@ def _set_report_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("report", description="generate report")
|
||||
parser = root.add_parser("report", help="generate report", description="generate report",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("target", help="target to generate report", nargs="*")
|
||||
parser.set_defaults(handler=handlers.Report)
|
||||
parser.set_defaults(handler=handlers.Report, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
def _set_search_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
"""
|
||||
add parser for search subcommand
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("search", help="search for package", description="search for package in AUR using API")
|
||||
parser.add_argument("search", help="search terms, can be specified multiple times", nargs="+")
|
||||
parser.set_defaults(handler=handlers.Search, architecture=[""], lock=None, no_log=True, no_report=True, unsafe=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -161,14 +223,20 @@ def _set_setup_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("setup", description="create initial service configuration, requires root")
|
||||
parser = root.add_parser("setup", help="initial service configuration",
|
||||
description="create initial service configuration, requires root",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--build-command", help="build command prefix", default="ahriman")
|
||||
parser.add_argument("--from-config", help="path to default devtools pacman configuration",
|
||||
default="/usr/share/devtools/pacman-extra.conf")
|
||||
parser.add_argument("--from-configuration", help="path to default devtools pacman configuration",
|
||||
type=Path, default=Path("/usr/share/devtools/pacman-extra.conf"))
|
||||
parser.add_argument("--no-multilib", help="do not add multilib repository", action="store_true")
|
||||
parser.add_argument("--packager", help="packager name and email", required=True)
|
||||
parser.add_argument("--repository", help="repository name", default="aur-clone")
|
||||
parser.set_defaults(handler=handlers.Setup, lock=None, no_report=True, unsafe=True)
|
||||
parser.add_argument("--repository", help="repository name", required=True)
|
||||
parser.add_argument("--sign-key", help="sign key id")
|
||||
parser.add_argument("--sign-target", help="sign options", type=SignSettings.from_option,
|
||||
choices=SignSettings, action="append")
|
||||
parser.add_argument("--web-port", help="port of the web service", type=int)
|
||||
parser.set_defaults(handler=handlers.Setup, lock=None, no_log=True, no_report=True, unsafe=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -178,9 +246,10 @@ def _set_sign_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("sign", description="(re-)sign packages and repository database")
|
||||
parser = root.add_parser("sign", help="sign packages", description="(re-)sign packages and repository database",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("package", help="sign only specified packages", nargs="*")
|
||||
parser.set_defaults(handler=handlers.Sign)
|
||||
parser.set_defaults(handler=handlers.Sign, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
@ -190,10 +259,11 @@ def _set_status_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("status", description="request status of the package")
|
||||
parser = root.add_parser("status", help="get package status", description="request status of the package",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("--ahriman", help="get service status itself", action="store_true")
|
||||
parser.add_argument("package", help="filter status by package base", nargs="*")
|
||||
parser.set_defaults(handler=handlers.Status, lock=None, no_report=True, unsafe=True)
|
||||
parser.set_defaults(handler=handlers.Status, lock=None, no_log=True, no_report=True, unsafe=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -203,14 +273,16 @@ def _set_status_update_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("status-update", description="request status of the package")
|
||||
parser = root.add_parser("status-update", help="update package status", description="request status of the package",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument(
|
||||
"package",
|
||||
help="set status for specified packages. If no packages supplied, service status will be updated",
|
||||
nargs="*")
|
||||
parser.add_argument("--status", help="new status", choices=[value.value for value in BuildStatusEnum],
|
||||
default="success")
|
||||
parser.set_defaults(handler=handlers.StatusUpdate, lock=None, no_report=True, unsafe=True)
|
||||
parser.add_argument("--status", help="new status", choices=BuildStatusEnum,
|
||||
type=BuildStatusEnum, default=BuildStatusEnum.Success)
|
||||
parser.add_argument("--remove", help="remove package status page", action="store_true")
|
||||
parser.set_defaults(handler=handlers.StatusUpdate, lock=None, no_log=True, no_report=True, unsafe=True)
|
||||
return parser
|
||||
|
||||
|
||||
@ -220,9 +292,10 @@ def _set_sync_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("sync", description="sync packages to remote server")
|
||||
parser = root.add_parser("sync", help="sync repository", description="sync packages to remote server",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("target", help="target to sync", nargs="*")
|
||||
parser.set_defaults(handler=handlers.Sync)
|
||||
parser.set_defaults(handler=handlers.Sync, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
@ -232,13 +305,14 @@ def _set_update_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("update", description="run updates")
|
||||
parser = root.add_parser("update", help="update packages", description="run updates",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.add_argument("package", help="filter check by package base", nargs="*")
|
||||
parser.add_argument("--dry-run", help="just perform check for updates, same as check command", action="store_true")
|
||||
parser.add_argument("--no-aur", help="do not check for AUR updates. Implies --no-vcs", action="store_true")
|
||||
parser.add_argument("--no-manual", help="do not include manual updates", action="store_true")
|
||||
parser.add_argument("--no-vcs", help="do not check VCS packages", action="store_true")
|
||||
parser.set_defaults(handler=handlers.Update)
|
||||
parser.set_defaults(handler=handlers.Update, architecture=[])
|
||||
return parser
|
||||
|
||||
|
||||
@ -248,16 +322,24 @@ def _set_web_parser(root: SubParserAction) -> argparse.ArgumentParser:
|
||||
:param root: subparsers for the commands
|
||||
:return: created argument parser
|
||||
"""
|
||||
parser = root.add_parser("web", description="start web server")
|
||||
parser = root.add_parser("web", help="start web server", description="start web server",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
||||
parser.set_defaults(handler=handlers.Web, lock=None, no_report=True)
|
||||
return parser
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args_parser = _parser()
|
||||
args = args_parser.parse_args()
|
||||
def run() -> None:
|
||||
"""
|
||||
run application instance
|
||||
"""
|
||||
if __name__ == "__main__":
|
||||
args_parser = _parser()
|
||||
args = args_parser.parse_args()
|
||||
|
||||
handler: handlers.Handler = args.handler
|
||||
status = handler.execute(args)
|
||||
handler: handlers.Handler = args.handler
|
||||
status = handler.execute(args)
|
||||
|
||||
sys.exit(status)
|
||||
sys.exit(status)
|
||||
|
||||
|
||||
run()
|
||||
|
@ -35,21 +35,28 @@ class Application:
|
||||
"""
|
||||
base application class
|
||||
:ivar architecture: repository architecture
|
||||
:ivar config: configuration instance
|
||||
:ivar configuration: configuration instance
|
||||
:ivar logger: application logger
|
||||
:ivar repository: repository instance
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.logger = logging.getLogger("root")
|
||||
self.config = config
|
||||
self.configuration = configuration
|
||||
self.architecture = architecture
|
||||
self.repository = Repository(architecture, config)
|
||||
self.repository = Repository(architecture, configuration)
|
||||
|
||||
def _finalize(self, built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
generate report and sync to remote server
|
||||
"""
|
||||
self.report([], built_packages)
|
||||
self.sync([], built_packages)
|
||||
|
||||
def _known_packages(self) -> Set[str]:
|
||||
"""
|
||||
@ -58,18 +65,13 @@ class Application:
|
||||
"""
|
||||
known_packages: Set[str] = set()
|
||||
# local set
|
||||
for package in self.repository.packages():
|
||||
known_packages.update(package.packages.keys())
|
||||
for base in self.repository.packages():
|
||||
for package, properties in base.packages.items():
|
||||
known_packages.add(package)
|
||||
known_packages.update(properties.provides)
|
||||
known_packages.update(self.repository.pacman.all_packages())
|
||||
return known_packages
|
||||
|
||||
def _finalize(self) -> None:
|
||||
"""
|
||||
generate report and sync to remote server
|
||||
"""
|
||||
self.report([])
|
||||
self.sync([])
|
||||
|
||||
def get_updates(self, filter_packages: List[str], no_aur: bool, no_manual: bool, no_vcs: bool,
|
||||
log_fn: Callable[[str], None]) -> List[Package]:
|
||||
"""
|
||||
@ -106,7 +108,7 @@ class Application:
|
||||
add_archive(full_path)
|
||||
|
||||
def add_manual(src: str) -> Path:
|
||||
package = Package.load(src, self.repository.pacman, self.config.get("alpm", "aur_url"))
|
||||
package = Package.load(src, self.repository.pacman, self.configuration.get("alpm", "aur_url"))
|
||||
path = self.repository.paths.manual / package.base
|
||||
Task.fetch(path, package.git_url)
|
||||
return path
|
||||
@ -160,15 +162,16 @@ class Application:
|
||||
:param names: list of packages (either base or name) to remove
|
||||
"""
|
||||
self.repository.process_remove(names)
|
||||
self._finalize()
|
||||
self._finalize([])
|
||||
|
||||
def report(self, target: Iterable[str]) -> None:
|
||||
def report(self, target: Iterable[str], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
generate report
|
||||
:param target: list of targets to run (e.g. html)
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
targets = target or None
|
||||
self.repository.process_report(targets)
|
||||
self.repository.process_report(targets, built_packages)
|
||||
|
||||
def sign(self, packages: Iterable[str]) -> None:
|
||||
"""
|
||||
@ -182,6 +185,7 @@ class Application:
|
||||
continue
|
||||
for archive in package.packages.values():
|
||||
if archive.filepath is None:
|
||||
self.logger.warning("filepath is empty for %s", package.base)
|
||||
continue # avoid mypy warning
|
||||
src = self.repository.paths.repository / archive.filepath
|
||||
dst = self.repository.paths.packages / archive.filepath
|
||||
@ -190,15 +194,16 @@ class Application:
|
||||
self.update([])
|
||||
# sign repository database if set
|
||||
self.repository.sign.sign_repository(self.repository.repo.repo_path)
|
||||
self._finalize()
|
||||
self._finalize([])
|
||||
|
||||
def sync(self, target: Iterable[str]) -> None:
|
||||
def sync(self, target: Iterable[str], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
sync to remote server
|
||||
:param target: list of targets to run (e.g. s3)
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
targets = target or None
|
||||
self.repository.process_sync(targets)
|
||||
self.repository.process_sync(targets, built_packages)
|
||||
|
||||
def update(self, updates: Iterable[Package]) -> None:
|
||||
"""
|
||||
@ -206,8 +211,11 @@ class Application:
|
||||
:param updates: list of packages to update
|
||||
"""
|
||||
def process_update(paths: Iterable[Path]) -> None:
|
||||
if not paths:
|
||||
return # don't need to process if no update supplied
|
||||
updated = [Package.load(path, self.repository.pacman, self.repository.aur_url) for path in paths]
|
||||
self.repository.process_update(paths)
|
||||
self._finalize()
|
||||
self._finalize(updated)
|
||||
|
||||
# process built packages
|
||||
packages = self.repository.packages_built()
|
||||
@ -216,6 +224,6 @@ class Application:
|
||||
# process manual packages
|
||||
tree = Tree.load(updates)
|
||||
for num, level in enumerate(tree.levels()):
|
||||
self.logger.info(f"processing level #{num} {[package.base for package in level]}")
|
||||
self.logger.info("processing level #%i %s", num, [package.base for package in level])
|
||||
packages = self.repository.process_build(level)
|
||||
process_update(packages)
|
||||
|
@ -22,9 +22,12 @@ from ahriman.application.handlers.handler import Handler
|
||||
from ahriman.application.handlers.add import Add
|
||||
from ahriman.application.handlers.clean import Clean
|
||||
from ahriman.application.handlers.dump import Dump
|
||||
from ahriman.application.handlers.init import Init
|
||||
from ahriman.application.handlers.key_import import KeyImport
|
||||
from ahriman.application.handlers.rebuild import Rebuild
|
||||
from ahriman.application.handlers.remove import Remove
|
||||
from ahriman.application.handlers.report import Report
|
||||
from ahriman.application.handlers.search import Search
|
||||
from ahriman.application.handlers.setup import Setup
|
||||
from ahriman.application.handlers.sign import Sign
|
||||
from ahriman.application.handlers.status import Status
|
||||
|
@ -32,11 +32,17 @@ class Add(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, config).add(args.package, args.without_dependencies)
|
||||
application = Application(architecture, configuration)
|
||||
application.add(args.package, args.without_dependencies)
|
||||
if not args.now:
|
||||
return
|
||||
|
||||
packages = application.get_updates(args.package, True, False, True, application.logger.info)
|
||||
application.update(packages)
|
||||
|
@ -32,12 +32,12 @@ class Clean(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, config).clean(args.no_build, args.no_cache, args.no_chroot,
|
||||
args.no_manual, args.no_packages)
|
||||
Application(architecture, configuration).clean(args.no_build, args.no_cache, args.no_chroot,
|
||||
args.no_manual, args.no_packages)
|
||||
|
@ -27,20 +27,22 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
class Dump(Handler):
|
||||
"""
|
||||
dump config handler
|
||||
dump configuration handler
|
||||
"""
|
||||
|
||||
_print = print
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
config_dump = config.dump(architecture)
|
||||
for section, values in sorted(config_dump.items()):
|
||||
print(f"[{section}]")
|
||||
dump = configuration.dump()
|
||||
for section, values in sorted(dump.items()):
|
||||
Dump._print(f"[{section}]")
|
||||
for key, value in sorted(values.items()):
|
||||
print(f"{key} = {value}")
|
||||
print()
|
||||
Dump._print(f"{key} = {value}")
|
||||
Dump._print()
|
||||
|
@ -23,10 +23,12 @@ import argparse
|
||||
import logging
|
||||
|
||||
from multiprocessing import Pool
|
||||
from typing import Type
|
||||
from typing import Set, Type
|
||||
|
||||
from ahriman.application.lock import Lock
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.exceptions import MissingArchitecture
|
||||
from ahriman.models.repository_paths import RepositoryPaths
|
||||
|
||||
|
||||
class Handler:
|
||||
@ -35,17 +37,17 @@ class Handler:
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _call(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> bool:
|
||||
def _call(cls: Type[Handler], args: argparse.Namespace, architecture: str) -> bool:
|
||||
"""
|
||||
additional function to wrap all calls for multiprocessing library
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:return: True on success, False otherwise
|
||||
"""
|
||||
try:
|
||||
with Lock(args, architecture, config):
|
||||
cls.run(args, architecture, config)
|
||||
configuration = Configuration.from_path(args.configuration, architecture, not args.no_log)
|
||||
with Lock(args, architecture, configuration):
|
||||
cls.run(args, architecture, configuration)
|
||||
return True
|
||||
except Exception:
|
||||
logging.getLogger("root").exception("process exception")
|
||||
@ -58,18 +60,39 @@ class Handler:
|
||||
:param args: command line args
|
||||
:return: 0 on success, 1 otherwise
|
||||
"""
|
||||
configuration = Configuration.from_path(args.config, not args.no_log)
|
||||
with Pool(len(args.architecture)) as pool:
|
||||
architectures = cls.extract_architectures(args)
|
||||
with Pool(len(architectures)) as pool:
|
||||
result = pool.starmap(
|
||||
cls._call, [(args, architecture, configuration) for architecture in args.architecture])
|
||||
cls._call, [(args, architecture) for architecture in architectures])
|
||||
return 0 if all(result) else 1
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def extract_architectures(cls: Type[Handler], args: argparse.Namespace) -> Set[str]:
|
||||
"""
|
||||
get known architectures
|
||||
:param args: command line args
|
||||
:return: list of architectures for which tree is created
|
||||
"""
|
||||
if args.architecture is None:
|
||||
raise MissingArchitecture(args.command)
|
||||
if args.architecture:
|
||||
return set(args.architecture)
|
||||
|
||||
config = Configuration()
|
||||
config.load(args.configuration)
|
||||
root = config.getpath("repository", "root")
|
||||
architectures = RepositoryPaths.known_architectures(root)
|
||||
|
||||
if not architectures:
|
||||
raise MissingArchitecture(args.command)
|
||||
return architectures
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
42
src/ahriman/application/handlers/init.py
Normal file
42
src/ahriman/application/handlers/init.py
Normal file
@ -0,0 +1,42 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import argparse
|
||||
|
||||
from typing import Type
|
||||
|
||||
from ahriman.application.application import Application
|
||||
from ahriman.application.handlers.handler import Handler
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
class Init(Handler):
|
||||
"""
|
||||
repository init handler
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, configuration).repository.repo.init()
|
42
src/ahriman/application/handlers/key_import.py
Normal file
42
src/ahriman/application/handlers/key_import.py
Normal file
@ -0,0 +1,42 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import argparse
|
||||
|
||||
from typing import Type
|
||||
|
||||
from ahriman.application.application import Application
|
||||
from ahriman.application.handlers.handler import Handler
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
class KeyImport(Handler):
|
||||
"""
|
||||
key import packages handler
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, configuration).repository.sign.import_key(args.key_server, args.key)
|
@ -32,13 +32,19 @@ class Rebuild(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
application = Application(architecture, config)
|
||||
packages = application.repository.packages()
|
||||
depends_on = set(args.depends_on) if args.depends_on else None
|
||||
|
||||
application = Application(architecture, configuration)
|
||||
packages = [
|
||||
package
|
||||
for package in application.repository.packages()
|
||||
if depends_on is None or depends_on.intersection(package.depends)
|
||||
] # we have to use explicit list here for testing purpose
|
||||
application.update(packages)
|
||||
|
@ -32,11 +32,11 @@ class Remove(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, config).remove(args.package)
|
||||
Application(architecture, configuration).remove(args.package)
|
||||
|
@ -32,11 +32,11 @@ class Report(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, config).report(args.target)
|
||||
Application(architecture, configuration).report(args.target, [])
|
||||
|
58
src/ahriman/application/handlers/search.py
Normal file
58
src/ahriman/application/handlers/search.py
Normal file
@ -0,0 +1,58 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import argparse
|
||||
import aur # type: ignore
|
||||
|
||||
from typing import Callable, Type
|
||||
|
||||
from ahriman.application.handlers.handler import Handler
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
class Search(Handler):
|
||||
"""
|
||||
packages search handler
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
search = " ".join(args.search)
|
||||
packages = aur.search(search)
|
||||
|
||||
# it actually always should return string
|
||||
# explicit cast to string just to avoid mypy warning for untyped library
|
||||
comparator: Callable[[aur.Package], str] = lambda item: str(item.package_base)
|
||||
for package in sorted(packages, key=comparator):
|
||||
Search.log_fn(package)
|
||||
|
||||
@staticmethod
|
||||
def log_fn(package: aur.Package) -> None:
|
||||
"""
|
||||
log package information
|
||||
:param package: package object as from AUR
|
||||
"""
|
||||
print(f"=> {package.package_base} {package.version}")
|
||||
print(f" {package.description}")
|
@ -44,19 +44,19 @@ class Setup(Handler):
|
||||
SUDOERS_PATH = Path("/etc/sudoers.d/ahriman")
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
application = Application(architecture, config)
|
||||
application = Application(architecture, configuration)
|
||||
Setup.create_makepkg_configuration(args.packager, application.repository.paths)
|
||||
Setup.create_executable(args.build_command, architecture)
|
||||
Setup.create_devtools_configuration(args.build_command, architecture, Path(args.from_config), args.no_multilib,
|
||||
args.repository, application.repository.paths)
|
||||
Setup.create_ahriman_configuration(args.build_command, architecture, args.repository, config.include)
|
||||
Setup.create_devtools_configuration(args.build_command, architecture, args.from_configuration,
|
||||
args.no_multilib, args.repository, application.repository.paths)
|
||||
Setup.create_ahriman_configuration(args, architecture, args.repository, configuration.include)
|
||||
Setup.create_sudo_configuration(args.build_command, architecture)
|
||||
|
||||
@staticmethod
|
||||
@ -70,25 +70,38 @@ class Setup(Handler):
|
||||
return Setup.BIN_DIR_PATH / f"{prefix}-{architecture}-build"
|
||||
|
||||
@staticmethod
|
||||
def create_ahriman_configuration(prefix: str, architecture: str, repository: str, include_path: Path) -> None:
|
||||
def create_ahriman_configuration(args: argparse.Namespace, architecture: str, repository: str,
|
||||
include_path: Path) -> None:
|
||||
"""
|
||||
create service specific configuration
|
||||
:param prefix: command prefix in {prefix}-{architecture}-build
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param repository: repository name
|
||||
:param include_path: path to directory with configuration includes
|
||||
"""
|
||||
config = configparser.ConfigParser()
|
||||
configuration = configparser.ConfigParser()
|
||||
|
||||
config.add_section("build")
|
||||
config.set("build", "build_command", str(Setup.build_command(prefix, architecture)))
|
||||
section = Configuration.section_name("build", architecture)
|
||||
configuration.add_section(section)
|
||||
configuration.set(section, "build_command", str(Setup.build_command(args.build_command, architecture)))
|
||||
|
||||
config.add_section("repository")
|
||||
config.set("repository", "name", repository)
|
||||
configuration.add_section("repository")
|
||||
configuration.set("repository", "name", repository)
|
||||
|
||||
target = include_path / "build-overrides.ini"
|
||||
with target.open("w") as ahriman_config:
|
||||
config.write(ahriman_config)
|
||||
if args.sign_key is not None:
|
||||
section = Configuration.section_name("sign", architecture)
|
||||
configuration.add_section(section)
|
||||
configuration.set(section, "target", " ".join([target.name.lower() for target in args.sign_target]))
|
||||
configuration.set(section, "key", args.sign_key)
|
||||
|
||||
if args.web_port is not None:
|
||||
section = Configuration.section_name("web", architecture)
|
||||
configuration.add_section(section)
|
||||
configuration.set(section, "port", str(args.web_port))
|
||||
|
||||
target = include_path / "setup-overrides.ini"
|
||||
with target.open("w") as ahriman_configuration:
|
||||
configuration.write(ahriman_configuration)
|
||||
|
||||
@staticmethod
|
||||
def create_devtools_configuration(prefix: str, architecture: str, source: Path,
|
||||
@ -102,31 +115,31 @@ class Setup(Handler):
|
||||
:param repository: repository name
|
||||
:param paths: repository paths instance
|
||||
"""
|
||||
config = configparser.ConfigParser()
|
||||
configuration = configparser.ConfigParser()
|
||||
# preserve case
|
||||
# stupid mypy thinks that it is impossible
|
||||
config.optionxform = lambda key: key # type: ignore
|
||||
configuration.optionxform = lambda key: key # type: ignore
|
||||
|
||||
# load default configuration first
|
||||
# we cannot use Include here because it will be copied to new chroot, thus no includes there
|
||||
config.read(source)
|
||||
configuration.read(source)
|
||||
|
||||
# set our architecture now
|
||||
config.set("options", "Architecture", architecture)
|
||||
configuration.set("options", "Architecture", architecture)
|
||||
|
||||
# add multilib
|
||||
if not no_multilib:
|
||||
config.add_section("multilib")
|
||||
config.set("multilib", "Include", str(Setup.MIRRORLIST_PATH))
|
||||
configuration.add_section("multilib")
|
||||
configuration.set("multilib", "Include", str(Setup.MIRRORLIST_PATH))
|
||||
|
||||
# add repository itself
|
||||
config.add_section(repository)
|
||||
config.set(repository, "SigLevel", "Optional TrustAll") # we don't care
|
||||
config.set(repository, "Server", f"file://{paths.repository}")
|
||||
configuration.add_section(repository)
|
||||
configuration.set(repository, "SigLevel", "Optional TrustAll") # we don't care
|
||||
configuration.set(repository, "Server", f"file://{paths.repository}")
|
||||
|
||||
target = source.parent / f"pacman-{prefix}-{architecture}.conf"
|
||||
with target.open("w") as devtools_config:
|
||||
config.write(devtools_config)
|
||||
with target.open("w") as devtools_configuration:
|
||||
configuration.write(devtools_configuration)
|
||||
|
||||
@staticmethod
|
||||
def create_makepkg_configuration(packager: str, paths: RepositoryPaths) -> None:
|
||||
|
@ -32,11 +32,11 @@ class Sign(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, config).sign(args.package)
|
||||
Application(architecture, configuration).sign(args.package)
|
||||
|
@ -34,14 +34,14 @@ class Status(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
application = Application(architecture, config)
|
||||
application = Application(architecture, configuration)
|
||||
if args.ahriman:
|
||||
ahriman = application.repository.reporter.get_self()
|
||||
print(ahriman.pretty_print())
|
||||
|
@ -19,12 +19,11 @@
|
||||
#
|
||||
import argparse
|
||||
|
||||
from typing import Type
|
||||
from typing import Callable, Type
|
||||
|
||||
from ahriman.application.application import Application
|
||||
from ahriman.application.handlers.handler import Handler
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.models.build_status import BuildStatusEnum
|
||||
|
||||
|
||||
class StatusUpdate(Handler):
|
||||
@ -33,19 +32,19 @@ class StatusUpdate(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
client = Application(architecture, config).repository.reporter
|
||||
status = BuildStatusEnum(args.status)
|
||||
client = Application(architecture, configuration).repository.reporter
|
||||
callback: Callable[[str], None] = lambda p: client.remove(p) if args.remove else client.update(p, args.status)
|
||||
if args.package:
|
||||
# update packages statuses
|
||||
for package in args.package:
|
||||
client.update(package, status)
|
||||
callback(package)
|
||||
else:
|
||||
# update service status
|
||||
client.update_self(status)
|
||||
client.update_self(args.status)
|
||||
|
@ -32,11 +32,11 @@ class Sync(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Application(architecture, config).sync(args.target)
|
||||
Application(architecture, configuration).sync(args.target, [])
|
||||
|
@ -19,7 +19,7 @@
|
||||
#
|
||||
import argparse
|
||||
|
||||
from typing import Type
|
||||
from typing import Callable, Type
|
||||
|
||||
from ahriman.application.application import Application
|
||||
from ahriman.application.handlers.handler import Handler
|
||||
@ -32,20 +32,29 @@ class Update(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
# typing workaround
|
||||
def log_fn(line: str) -> None:
|
||||
return print(line) if args.dry_run else application.logger.info(line)
|
||||
|
||||
application = Application(architecture, config)
|
||||
packages = application.get_updates(args.package, args.no_aur, args.no_manual, args.no_vcs, log_fn)
|
||||
application = Application(architecture, configuration)
|
||||
packages = application.get_updates(args.package, args.no_aur, args.no_manual, args.no_vcs,
|
||||
Update.log_fn(application, args.dry_run))
|
||||
if args.dry_run:
|
||||
return
|
||||
|
||||
application.update(packages)
|
||||
|
||||
@staticmethod
|
||||
def log_fn(application: Application, dry_run: bool) -> Callable[[str], None]:
|
||||
"""
|
||||
package updates log function
|
||||
:param application: application instance
|
||||
:param dry_run: do not perform update itself
|
||||
:return: in case if dry_run is set it will return print, logger otherwise
|
||||
"""
|
||||
def inner(line: str) -> None:
|
||||
return print(line) if dry_run else application.logger.info(line)
|
||||
return inner
|
||||
|
@ -31,13 +31,13 @@ class Web(Handler):
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def run(cls: Type[Handler], args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
callback for command line
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
from ahriman.web.web import run_server, setup_service
|
||||
application = setup_service(architecture, config)
|
||||
application = setup_service(architecture, configuration)
|
||||
run_server(application)
|
||||
|
@ -20,12 +20,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
|
||||
from pathlib import Path
|
||||
from types import TracebackType
|
||||
from typing import Literal, Optional, Type
|
||||
|
||||
from ahriman import version
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.exceptions import DuplicateRun, UnsafeRun
|
||||
from ahriman.core.status.client import Client
|
||||
@ -42,31 +44,32 @@ class Lock:
|
||||
:ivar unsafe: skip user check
|
||||
"""
|
||||
|
||||
def __init__(self, args: argparse.Namespace, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, args: argparse.Namespace, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param args: command line args
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.path = Path(f"{args.lock}_{architecture}") if args.lock is not None else None
|
||||
self.force = args.force
|
||||
self.unsafe = args.unsafe
|
||||
|
||||
self.root = Path(config.get("repository", "root"))
|
||||
self.reporter = Client() if args.no_report else Client.load(architecture, config)
|
||||
self.root = Path(configuration.get("repository", "root"))
|
||||
self.reporter = Client() if args.no_report else Client.load(configuration)
|
||||
|
||||
def __enter__(self) -> Lock:
|
||||
"""
|
||||
default workflow is the following:
|
||||
|
||||
check user UID
|
||||
remove lock file if force flag is set
|
||||
check if there is lock file
|
||||
check web status watcher status
|
||||
create lock file
|
||||
report to web if enabled
|
||||
"""
|
||||
self.check_user()
|
||||
self.check_version()
|
||||
self.create()
|
||||
self.reporter.update_self(BuildStatusEnum.Building)
|
||||
return self
|
||||
@ -80,11 +83,22 @@ class Lock:
|
||||
:param exc_tb: exception traceback if any
|
||||
:return: always False (do not suppress any exception)
|
||||
"""
|
||||
self.remove()
|
||||
self.clear()
|
||||
status = BuildStatusEnum.Success if exc_val is None else BuildStatusEnum.Failed
|
||||
self.reporter.update_self(status)
|
||||
return False
|
||||
|
||||
def check_version(self) -> None:
|
||||
"""
|
||||
check web server version
|
||||
"""
|
||||
status = self.reporter.get_internal()
|
||||
if status.version is not None and status.version != version.__version__:
|
||||
logging.getLogger("root").warning(
|
||||
"status watcher version mismatch, our %s, their %s",
|
||||
version.__version__,
|
||||
status.version)
|
||||
|
||||
def check_user(self) -> None:
|
||||
"""
|
||||
check if current user is actually owner of ahriman root
|
||||
@ -96,6 +110,14 @@ class Lock:
|
||||
if current_uid != root_uid:
|
||||
raise UnsafeRun(current_uid, root_uid)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""
|
||||
remove lock file
|
||||
"""
|
||||
if self.path is None:
|
||||
return
|
||||
self.path.unlink(missing_ok=True)
|
||||
|
||||
def create(self) -> None:
|
||||
"""
|
||||
create lock file
|
||||
@ -106,11 +128,3 @@ class Lock:
|
||||
self.path.touch(exist_ok=self.force)
|
||||
except FileExistsError:
|
||||
raise DuplicateRun()
|
||||
|
||||
def remove(self) -> None:
|
||||
"""
|
||||
remove lock file
|
||||
"""
|
||||
if self.path is None:
|
||||
return
|
||||
self.path.unlink(missing_ok=True)
|
||||
|
@ -18,7 +18,7 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from pyalpm import Handle # type: ignore
|
||||
from typing import List, Set
|
||||
from typing import Set
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
@ -29,24 +29,26 @@ class Pacman:
|
||||
:ivar handle: pyalpm root `Handle`
|
||||
"""
|
||||
|
||||
def __init__(self, config: Configuration) -> None:
|
||||
def __init__(self, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
root = config.get("alpm", "root")
|
||||
pacman_root = config.getpath("alpm", "database")
|
||||
root = configuration.get("alpm", "root")
|
||||
pacman_root = configuration.getpath("alpm", "database")
|
||||
self.handle = Handle(root, str(pacman_root))
|
||||
for repository in config.getlist("alpm", "repositories"):
|
||||
for repository in configuration.getlist("alpm", "repositories"):
|
||||
self.handle.register_syncdb(repository, 0) # 0 is pgp_level
|
||||
|
||||
def all_packages(self) -> List[str]:
|
||||
def all_packages(self) -> Set[str]:
|
||||
"""
|
||||
get list of packages known for alpm
|
||||
:return: list of package names
|
||||
"""
|
||||
result: Set[str] = set()
|
||||
for database in self.handle.get_syncdbs():
|
||||
result.update({package.name for package in database.pkgcache})
|
||||
for package in database.pkgcache:
|
||||
result.add(package.name) # package itself
|
||||
result.update(package.provides) # provides list for meta-packages
|
||||
|
||||
return list(result)
|
||||
return result
|
||||
|
@ -68,6 +68,16 @@ class Repo:
|
||||
cwd=self.paths.repository,
|
||||
logger=self.logger)
|
||||
|
||||
def init(self) -> None:
|
||||
"""
|
||||
create empty repository database
|
||||
"""
|
||||
Repo._check_output(
|
||||
"repo-add", *self.sign_args, str(self.repo_path),
|
||||
exception=None,
|
||||
cwd=self.paths.repository,
|
||||
logger=self.logger)
|
||||
|
||||
def remove(self, package: str, filename: Path) -> None:
|
||||
"""
|
||||
remove package from repository
|
||||
|
@ -41,12 +41,11 @@ class Task:
|
||||
|
||||
_check_output = check_output
|
||||
|
||||
def __init__(self, package: Package, architecture: str, config: Configuration, paths: RepositoryPaths) -> None:
|
||||
def __init__(self, package: Package, configuration: Configuration, paths: RepositoryPaths) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param package: package definitions
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
:param paths: repository paths instance
|
||||
"""
|
||||
self.logger = logging.getLogger("builder")
|
||||
@ -54,11 +53,10 @@ class Task:
|
||||
self.package = package
|
||||
self.paths = paths
|
||||
|
||||
section = config.get_section_name("build", architecture)
|
||||
self.archbuild_flags = config.getlist(section, "archbuild_flags")
|
||||
self.build_command = config.get(section, "build_command")
|
||||
self.makepkg_flags = config.getlist(section, "makepkg_flags")
|
||||
self.makechrootpkg_flags = config.getlist(section, "makechrootpkg_flags")
|
||||
self.archbuild_flags = configuration.getlist("build", "archbuild_flags")
|
||||
self.build_command = configuration.get("build", "build_command")
|
||||
self.makepkg_flags = configuration.getlist("build", "makepkg_flags")
|
||||
self.makechrootpkg_flags = configuration.getlist("build", "makechrootpkg_flags")
|
||||
|
||||
@property
|
||||
def cache_path(self) -> Path:
|
||||
@ -97,14 +95,14 @@ class Task:
|
||||
run package build
|
||||
:return: paths of produced packages
|
||||
"""
|
||||
cmd = [self.build_command, "-r", str(self.paths.chroot)]
|
||||
cmd.extend(self.archbuild_flags)
|
||||
cmd.extend(["--"] + self.makechrootpkg_flags)
|
||||
cmd.extend(["--"] + self.makepkg_flags)
|
||||
self.logger.info(f"using {cmd} for {self.package.base}")
|
||||
command = [self.build_command, "-r", str(self.paths.chroot)]
|
||||
command.extend(self.archbuild_flags)
|
||||
command.extend(["--"] + self.makechrootpkg_flags)
|
||||
command.extend(["--"] + self.makepkg_flags)
|
||||
self.logger.info("using %s for %s", command, self.package.base)
|
||||
|
||||
Task._check_output(
|
||||
*cmd,
|
||||
*command,
|
||||
exception=BuildFailed(self.package.base),
|
||||
cwd=self.git_path,
|
||||
logger=self.build_logger)
|
||||
@ -125,4 +123,4 @@ class Task:
|
||||
if self.cache_path.is_dir():
|
||||
# no need to clone whole repository, just copy from cache first
|
||||
shutil.copytree(self.cache_path, git_path)
|
||||
return Task.fetch(git_path, self.package.git_url)
|
||||
return self.fetch(git_path, self.package.git_url)
|
||||
|
@ -34,13 +34,11 @@ class Configuration(configparser.RawConfigParser):
|
||||
:cvar ARCHITECTURE_SPECIFIC_SECTIONS: known sections which can be architecture specific (required by dump)
|
||||
:cvar DEFAULT_LOG_FORMAT: default log format (in case of fallback)
|
||||
:cvar DEFAULT_LOG_LEVEL: default log level (in case of fallback)
|
||||
:cvar STATIC_SECTIONS: known sections which are not architecture specific (required by dump)
|
||||
"""
|
||||
|
||||
DEFAULT_LOG_FORMAT = "[%(levelname)s %(asctime)s] [%(filename)s:%(lineno)d] [%(funcName)s]: %(message)s"
|
||||
DEFAULT_LOG_LEVEL = logging.DEBUG
|
||||
|
||||
STATIC_SECTIONS = ["alpm", "report", "repository", "settings", "upload"]
|
||||
ARCHITECTURE_SPECIFIC_SECTIONS = ["build", "html", "rsync", "s3", "sign", "web"]
|
||||
|
||||
def __init__(self) -> None:
|
||||
@ -57,37 +55,47 @@ class Configuration(configparser.RawConfigParser):
|
||||
"""
|
||||
return self.getpath("settings", "include")
|
||||
|
||||
@property
|
||||
def logging_path(self) -> Path:
|
||||
"""
|
||||
:return: path to logging configuration
|
||||
"""
|
||||
return self.getpath("settings", "logging")
|
||||
|
||||
@classmethod
|
||||
def from_path(cls: Type[Configuration], path: Path, logfile: bool) -> Configuration:
|
||||
def from_path(cls: Type[Configuration], path: Path, architecture: str, logfile: bool) -> Configuration:
|
||||
"""
|
||||
constructor with full object initialization
|
||||
:param path: path to root configuration file
|
||||
:param architecture: repository architecture
|
||||
:param logfile: use log file to output messages
|
||||
:return: configuration instance
|
||||
"""
|
||||
config = cls()
|
||||
config.load(path)
|
||||
config.merge_sections(architecture)
|
||||
config.load_logging(logfile)
|
||||
return config
|
||||
|
||||
def dump(self, architecture: str) -> Dict[str, Dict[str, str]]:
|
||||
@staticmethod
|
||||
def section_name(section: str, architecture: str) -> str:
|
||||
"""
|
||||
generate section name for architecture specific sections
|
||||
:param section: section name
|
||||
:param architecture: repository architecture
|
||||
:return: correct section name for repository specific section
|
||||
"""
|
||||
return f"{section}:{architecture}"
|
||||
|
||||
def dump(self) -> Dict[str, Dict[str, str]]:
|
||||
"""
|
||||
dump configuration to dictionary
|
||||
:param architecture: repository architecture
|
||||
:return: configuration dump for specific architecture
|
||||
"""
|
||||
result: Dict[str, Dict[str, str]] = {}
|
||||
for section in Configuration.STATIC_SECTIONS:
|
||||
if not self.has_section(section):
|
||||
continue
|
||||
result[section] = dict(self[section])
|
||||
for group in Configuration.ARCHITECTURE_SPECIFIC_SECTIONS:
|
||||
section = self.get_section_name(group, architecture)
|
||||
if not self.has_section(section):
|
||||
continue
|
||||
result[section] = dict(self[section])
|
||||
|
||||
return result
|
||||
return {
|
||||
section: dict(self[section])
|
||||
for section in self.sections()
|
||||
}
|
||||
|
||||
def getlist(self, section: str, key: str) -> List[str]:
|
||||
"""
|
||||
@ -113,16 +121,6 @@ class Configuration(configparser.RawConfigParser):
|
||||
return value
|
||||
return self.path.parent / value
|
||||
|
||||
def get_section_name(self, prefix: str, suffix: str) -> str:
|
||||
"""
|
||||
check if there is `prefix`_`suffix` section and return it on success. Return `prefix` otherwise
|
||||
:param prefix: section name prefix
|
||||
:param suffix: section name suffix (e.g. architecture name)
|
||||
:return: found section name
|
||||
"""
|
||||
probe = f"{prefix}_{suffix}"
|
||||
return probe if self.has_section(probe) else prefix
|
||||
|
||||
def load(self, path: Path) -> None:
|
||||
"""
|
||||
fully load configuration
|
||||
@ -138,8 +136,10 @@ class Configuration(configparser.RawConfigParser):
|
||||
"""
|
||||
try:
|
||||
for path in sorted(self.include.glob("*.ini")):
|
||||
if path == self.logging_path:
|
||||
continue # we don't want to load logging explicitly
|
||||
self.read(path)
|
||||
except (FileNotFoundError, configparser.NoOptionError):
|
||||
except (FileNotFoundError, configparser.NoOptionError, configparser.NoSectionError):
|
||||
pass
|
||||
|
||||
def load_logging(self, logfile: bool) -> None:
|
||||
@ -149,17 +149,39 @@ class Configuration(configparser.RawConfigParser):
|
||||
"""
|
||||
def file_logger() -> None:
|
||||
try:
|
||||
config_path = self.getpath("settings", "logging")
|
||||
fileConfig(config_path)
|
||||
path = self.logging_path
|
||||
fileConfig(path)
|
||||
except (FileNotFoundError, PermissionError):
|
||||
console_logger()
|
||||
logging.exception("could not create logfile, fallback to stderr")
|
||||
|
||||
def console_logger() -> None:
|
||||
logging.basicConfig(filename=None, format=Configuration.DEFAULT_LOG_FORMAT,
|
||||
level=Configuration.DEFAULT_LOG_LEVEL)
|
||||
logging.basicConfig(filename=None, format=self.DEFAULT_LOG_FORMAT,
|
||||
level=self.DEFAULT_LOG_LEVEL)
|
||||
|
||||
if logfile:
|
||||
file_logger()
|
||||
else:
|
||||
console_logger()
|
||||
|
||||
def merge_sections(self, architecture: str) -> None:
|
||||
"""
|
||||
merge architecture specific sections into main configuration
|
||||
:param architecture: repository architecture
|
||||
"""
|
||||
for section in self.ARCHITECTURE_SPECIFIC_SECTIONS:
|
||||
if not self.has_section(section):
|
||||
self.add_section(section) # add section if not exists
|
||||
# get overrides
|
||||
specific = self.section_name(section, architecture)
|
||||
if self.has_section(specific):
|
||||
# if there is no such section it means that there is no overrides for this arch
|
||||
# but we anyway will have to delete sections for others archs
|
||||
for key, value in self[specific].items():
|
||||
self.set(section, key, value)
|
||||
# remove any arch specific section
|
||||
for foreign in self.sections():
|
||||
# we would like to use lambda filter here, but pylint is too dumb
|
||||
if not foreign.startswith(f"{section}:"):
|
||||
continue
|
||||
self.remove_section(foreign)
|
||||
|
@ -83,6 +83,19 @@ class InvalidPackageInfo(Exception):
|
||||
Exception.__init__(self, f"There are errors during reading package information: `{details}`")
|
||||
|
||||
|
||||
class MissingArchitecture(Exception):
|
||||
"""
|
||||
exception which will be raised if architecture is required, but missing
|
||||
"""
|
||||
|
||||
def __init__(self, command: str) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param command: command name which throws exception
|
||||
"""
|
||||
Exception.__init__(self, f"Architecture required for subcommand {command}, but missing")
|
||||
|
||||
|
||||
class ReportFailed(Exception):
|
||||
"""
|
||||
report generation exception
|
||||
|
105
src/ahriman/core/report/email.py
Normal file
105
src/ahriman/core/report/email.py
Normal file
@ -0,0 +1,105 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import datetime
|
||||
import smtplib
|
||||
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
from email.mime.text import MIMEText
|
||||
from typing import Dict, Iterable
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.report.jinja_template import JinjaTemplate
|
||||
from ahriman.core.report.report import Report
|
||||
from ahriman.core.util import pretty_datetime
|
||||
from ahriman.models.package import Package
|
||||
from ahriman.models.smtp_ssl_settings import SmtpSSLSettings
|
||||
|
||||
|
||||
class Email(Report, JinjaTemplate):
|
||||
"""
|
||||
email report generator
|
||||
:ivar host: SMTP host to connect
|
||||
:ivar no_empty_report: skip empty report generation
|
||||
:ivar password: password to authenticate via SMTP
|
||||
:ivar port: SMTP port to connect
|
||||
:ivar receivers: list of receivers emails
|
||||
:ivar sender: sender email address
|
||||
:ivar ssl: SSL mode for SMTP connection
|
||||
:ivar user: username to authenticate via SMTP
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Report.__init__(self, architecture, configuration)
|
||||
JinjaTemplate.__init__(self, "email", configuration)
|
||||
|
||||
# base smtp settings
|
||||
self.host = configuration.get("email", "host")
|
||||
self.no_empty_report = configuration.getboolean("email", "no_empty_report", fallback=True)
|
||||
self.password = configuration.get("email", "password", fallback=None)
|
||||
self.port = configuration.getint("email", "port")
|
||||
self.receivers = configuration.getlist("email", "receivers")
|
||||
self.sender = configuration.get("email", "sender")
|
||||
self.ssl = SmtpSSLSettings.from_option(configuration.get("email", "ssl", fallback="disabled"))
|
||||
self.user = configuration.get("email", "user", fallback=None)
|
||||
|
||||
def _send(self, text: str, attachment: Dict[str, str]) -> None:
|
||||
"""
|
||||
send email callback
|
||||
:param text: email body text
|
||||
:param attachment: map of attachment filename to attachment content
|
||||
"""
|
||||
message = MIMEMultipart()
|
||||
message["From"] = self.sender
|
||||
message["To"] = ", ".join(self.receivers)
|
||||
message["Subject"] = f"{self.name} build report at {pretty_datetime(datetime.datetime.utcnow().timestamp())}"
|
||||
|
||||
message.attach(MIMEText(text, "html"))
|
||||
for filename, content in attachment.items():
|
||||
attach = MIMEText(content, "html")
|
||||
attach.add_header("Content-Disposition", "attachment", filename=filename)
|
||||
message.attach(attach)
|
||||
|
||||
if self.ssl != SmtpSSLSettings.SSL:
|
||||
session = smtplib.SMTP(self.host, self.port)
|
||||
if self.ssl == SmtpSSLSettings.STARTTLS:
|
||||
session.starttls()
|
||||
else:
|
||||
session = smtplib.SMTP_SSL(self.host, self.port)
|
||||
if self.user is not None and self.password is not None:
|
||||
session.login(self.user, self.password)
|
||||
session.sendmail(self.sender, self.receivers, message.as_string())
|
||||
session.quit()
|
||||
|
||||
def generate(self, packages: Iterable[Package], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
generate report for the specified packages
|
||||
:param packages: list of packages to generate report
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
if self.no_empty_report and not built_packages:
|
||||
return
|
||||
text = self.make_html(built_packages, False)
|
||||
attachments = {"index.html": self.make_html(packages, True)}
|
||||
self._send(text, attachments)
|
@ -17,105 +17,36 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import jinja2
|
||||
|
||||
from typing import Callable, Dict, Iterable
|
||||
from typing import Iterable
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.report.jinja_template import JinjaTemplate
|
||||
from ahriman.core.report.report import Report
|
||||
from ahriman.core.util import pretty_datetime, pretty_size
|
||||
from ahriman.models.package import Package
|
||||
from ahriman.models.sign_settings import SignSettings
|
||||
|
||||
|
||||
class HTML(Report):
|
||||
class HTML(Report, JinjaTemplate):
|
||||
"""
|
||||
html report generator
|
||||
|
||||
It uses jinja2 templates for report generation, the following variables are allowed:
|
||||
|
||||
homepage - link to homepage, string, optional
|
||||
link_path - prefix fo packages to download, string, required
|
||||
has_package_signed - True in case if package sign enabled, False otherwise, required
|
||||
has_repo_signed - True in case if repository database sign enabled, False otherwise, required
|
||||
packages - sorted list of packages properties, required
|
||||
* architecture, string
|
||||
* archive_size, pretty printed size, string
|
||||
* build_date, pretty printed datetime, string
|
||||
* description, string
|
||||
* filename, string,
|
||||
* groups, sorted list of strings
|
||||
* installed_size, pretty printed datetime, string
|
||||
* licenses, sorted list of strings
|
||||
* name, string
|
||||
* url, string
|
||||
* version, string
|
||||
pgp_key - default PGP key ID, string, optional
|
||||
repository - repository name, string, required
|
||||
|
||||
:ivar homepage: homepage link if any (for footer)
|
||||
:ivar link_path: prefix fo packages to download
|
||||
:ivar name: repository name
|
||||
:ivar pgp_key: default PGP key
|
||||
:ivar report_path: output path to html report
|
||||
:ivar sign_targets: targets to sign enabled in configuration
|
||||
:ivar template_path: path to directory with jinja templates
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Report.__init__(self, architecture, config)
|
||||
section = config.get_section_name("html", architecture)
|
||||
self.report_path = config.getpath(section, "path")
|
||||
self.link_path = config.get(section, "link_path")
|
||||
self.template_path = config.getpath(section, "template_path")
|
||||
Report.__init__(self, architecture, configuration)
|
||||
JinjaTemplate.__init__(self, "html", configuration)
|
||||
|
||||
# base template vars
|
||||
self.homepage = config.get(section, "homepage", fallback=None)
|
||||
self.name = config.get("repository", "name")
|
||||
self.report_path = configuration.getpath("html", "path")
|
||||
|
||||
sign_section = config.get_section_name("sign", architecture)
|
||||
self.sign_targets = [SignSettings.from_option(opt) for opt in config.getlist(sign_section, "target")]
|
||||
self.pgp_key = config.get(sign_section, "key") if self.sign_targets else None
|
||||
|
||||
def generate(self, packages: Iterable[Package]) -> None:
|
||||
def generate(self, packages: Iterable[Package], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
generate report for the specified packages
|
||||
:param packages: list of packages to generate report
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
# idea comes from https://stackoverflow.com/a/38642558
|
||||
loader = jinja2.FileSystemLoader(searchpath=self.template_path.parent)
|
||||
environment = jinja2.Environment(loader=loader)
|
||||
template = environment.get_template(self.template_path.name)
|
||||
|
||||
content = [
|
||||
{
|
||||
"architecture": properties.architecture or "",
|
||||
"archive_size": pretty_size(properties.archive_size),
|
||||
"build_date": pretty_datetime(properties.build_date),
|
||||
"description": properties.description or "",
|
||||
"filename": properties.filename,
|
||||
"groups": properties.groups,
|
||||
"installed_size": pretty_size(properties.installed_size),
|
||||
"licenses": properties.licenses,
|
||||
"name": package,
|
||||
"url": properties.url or "",
|
||||
"version": base.version
|
||||
} for base in packages for package, properties in base.packages.items()
|
||||
]
|
||||
comparator: Callable[[Dict[str, str]], str] = lambda item: item["filename"]
|
||||
|
||||
html = template.render(
|
||||
homepage=self.homepage,
|
||||
link_path=self.link_path,
|
||||
has_package_signed=SignSettings.SignPackages in self.sign_targets,
|
||||
has_repo_signed=SignSettings.SignRepository in self.sign_targets,
|
||||
packages=sorted(content, key=comparator),
|
||||
pgp_key=self.pgp_key,
|
||||
repository=self.name)
|
||||
|
||||
html = self.make_html(packages, True)
|
||||
self.report_path.write_text(html)
|
||||
|
117
src/ahriman/core/report/jinja_template.py
Normal file
117
src/ahriman/core/report/jinja_template.py
Normal file
@ -0,0 +1,117 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import jinja2
|
||||
|
||||
from typing import Callable, Dict, Iterable
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.sign.gpg import GPG
|
||||
from ahriman.core.util import pretty_datetime, pretty_size
|
||||
from ahriman.models.package import Package
|
||||
from ahriman.models.sign_settings import SignSettings
|
||||
|
||||
|
||||
class JinjaTemplate:
|
||||
"""
|
||||
jinja based report generator
|
||||
|
||||
It uses jinja2 templates for report generation, the following variables are allowed:
|
||||
|
||||
homepage - link to homepage, string, optional
|
||||
link_path - prefix fo packages to download, string, required
|
||||
has_package_signed - True in case if package sign enabled, False otherwise, required
|
||||
has_repo_signed - True in case if repository database sign enabled, False otherwise, required
|
||||
packages - sorted list of packages properties, required
|
||||
* architecture, string
|
||||
* archive_size, pretty printed size, string
|
||||
* build_date, pretty printed datetime, string
|
||||
* depends, sorted list of strings
|
||||
* description, string
|
||||
* filename, string,
|
||||
* groups, sorted list of strings
|
||||
* installed_size, pretty printed datetime, string
|
||||
* licenses, sorted list of strings
|
||||
* name, string
|
||||
* url, string
|
||||
* version, string
|
||||
pgp_key - default PGP key ID, string, optional
|
||||
repository - repository name, string, required
|
||||
|
||||
:ivar homepage: homepage link if any (for footer)
|
||||
:ivar link_path: prefix fo packages to download
|
||||
:ivar name: repository name
|
||||
:ivar default_pgp_key: default PGP key
|
||||
:ivar sign_targets: targets to sign enabled in configuration
|
||||
:ivar template_path: path to directory with jinja templates
|
||||
"""
|
||||
|
||||
def __init__(self, section: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param section: settings section name
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.link_path = configuration.get(section, "link_path")
|
||||
self.template_path = configuration.getpath(section, "template_path")
|
||||
|
||||
# base template vars
|
||||
self.homepage = configuration.get(section, "homepage", fallback=None)
|
||||
self.name = configuration.get("repository", "name")
|
||||
|
||||
self.sign_targets, self.default_pgp_key = GPG.sign_options(configuration)
|
||||
|
||||
def make_html(self, packages: Iterable[Package], extended_report: bool) -> str:
|
||||
"""
|
||||
generate report for the specified packages
|
||||
:param packages: list of packages to generate report
|
||||
:param extended_report: include additional blocks to the report
|
||||
"""
|
||||
# idea comes from https://stackoverflow.com/a/38642558
|
||||
loader = jinja2.FileSystemLoader(searchpath=self.template_path.parent)
|
||||
environment = jinja2.Environment(loader=loader, autoescape=True)
|
||||
template = environment.get_template(self.template_path.name)
|
||||
|
||||
content = [
|
||||
{
|
||||
"architecture": properties.architecture or "",
|
||||
"archive_size": pretty_size(properties.archive_size),
|
||||
"build_date": pretty_datetime(properties.build_date),
|
||||
"depends": properties.depends,
|
||||
"description": properties.description or "",
|
||||
"filename": properties.filename,
|
||||
"groups": properties.groups,
|
||||
"installed_size": pretty_size(properties.installed_size),
|
||||
"licenses": properties.licenses,
|
||||
"name": package,
|
||||
"url": properties.url or "",
|
||||
"version": base.version
|
||||
} for base in packages for package, properties in base.packages.items()
|
||||
]
|
||||
comparator: Callable[[Dict[str, str]], str] = lambda item: item["filename"]
|
||||
|
||||
return template.render(
|
||||
extended_report=extended_report,
|
||||
homepage=self.homepage,
|
||||
link_path=self.link_path,
|
||||
has_package_signed=SignSettings.Packages in self.sign_targets,
|
||||
has_repo_signed=SignSettings.Repository in self.sign_targets,
|
||||
packages=sorted(content, key=comparator),
|
||||
pgp_key=self.default_pgp_key,
|
||||
repository=self.name)
|
@ -17,9 +17,11 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from typing import Iterable
|
||||
from typing import Iterable, Type
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.exceptions import ReportFailed
|
||||
@ -31,44 +33,53 @@ class Report:
|
||||
"""
|
||||
base report generator
|
||||
:ivar architecture: repository architecture
|
||||
:ivar config: configuration instance
|
||||
:ivar configuration: configuration instance
|
||||
:ivar logger: class logger
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.logger = logging.getLogger("builder")
|
||||
self.architecture = architecture
|
||||
self.config = config
|
||||
self.configuration = configuration
|
||||
|
||||
@staticmethod
|
||||
def run(architecture: str, config: Configuration, target: str, packages: Iterable[Package]) -> None:
|
||||
@classmethod
|
||||
def load(cls: Type[Report], architecture: str, configuration: Configuration, target: str) -> Report:
|
||||
"""
|
||||
run report generation
|
||||
load client from settings
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
:param target: target to generate report (e.g. html)
|
||||
:param packages: list of packages to generate report
|
||||
:return: client according to current settings
|
||||
"""
|
||||
provider = ReportSettings.from_option(target)
|
||||
if provider == ReportSettings.HTML:
|
||||
from ahriman.core.report.html import HTML
|
||||
report: Report = HTML(architecture, config)
|
||||
else:
|
||||
report = Report(architecture, config)
|
||||
return HTML(architecture, configuration)
|
||||
if provider == ReportSettings.Email:
|
||||
from ahriman.core.report.email import Email
|
||||
return Email(architecture, configuration)
|
||||
return cls(architecture, configuration) # should never happen
|
||||
|
||||
try:
|
||||
report.generate(packages)
|
||||
except Exception:
|
||||
report.logger.exception(f"report generation failed for target {provider.name}")
|
||||
raise ReportFailed()
|
||||
|
||||
def generate(self, packages: Iterable[Package]) -> None:
|
||||
def generate(self, packages: Iterable[Package], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
generate report for the specified packages
|
||||
:param packages: list of packages to generate report
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
|
||||
def run(self, packages: Iterable[Package], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
run report generation
|
||||
:param packages: list of packages to generate report
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
try:
|
||||
self.generate(packages, built_packages)
|
||||
except Exception:
|
||||
self.logger.exception("report generation failed")
|
||||
raise ReportFailed()
|
||||
|
@ -25,7 +25,7 @@ from typing import Dict, Iterable, List, Optional
|
||||
from ahriman.core.build_tools.task import Task
|
||||
from ahriman.core.report.report import Report
|
||||
from ahriman.core.repository.cleaner import Cleaner
|
||||
from ahriman.core.upload.uploader import Uploader
|
||||
from ahriman.core.upload.upload import Upload
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
@ -49,7 +49,7 @@ class Executor(Cleaner):
|
||||
"""
|
||||
def build_single(package: Package) -> None:
|
||||
self.reporter.set_building(package.base)
|
||||
task = Task(package, self.architecture, self.config, self.paths)
|
||||
task = Task(package, self.configuration, self.paths)
|
||||
task.init()
|
||||
built = task.build()
|
||||
for src in built:
|
||||
@ -61,7 +61,7 @@ class Executor(Cleaner):
|
||||
build_single(single)
|
||||
except Exception:
|
||||
self.reporter.set_failed(single.base)
|
||||
self.logger.exception(f"{single.base} ({self.architecture}) build exception")
|
||||
self.logger.exception("%s (%s) build exception", single.base, self.architecture)
|
||||
self.clear_build()
|
||||
|
||||
return self.packages_built()
|
||||
@ -76,7 +76,7 @@ class Executor(Cleaner):
|
||||
try:
|
||||
self.repo.remove(package, fn)
|
||||
except Exception:
|
||||
self.logger.exception(f"could not remove {package}")
|
||||
self.logger.exception("could not remove %s", package)
|
||||
|
||||
requested = set(packages)
|
||||
for local in self.packages():
|
||||
@ -100,25 +100,29 @@ class Executor(Cleaner):
|
||||
|
||||
return self.repo.repo_path
|
||||
|
||||
def process_report(self, targets: Optional[Iterable[str]]) -> None:
|
||||
def process_report(self, targets: Optional[Iterable[str]], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
generate reports
|
||||
:param targets: list of targets to generate reports. Configuration option will be used if it is not set
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
if targets is None:
|
||||
targets = self.config.getlist("report", "target")
|
||||
targets = self.configuration.getlist("report", "target")
|
||||
for target in targets:
|
||||
Report.run(self.architecture, self.config, target, self.packages())
|
||||
runner = Report.load(self.architecture, self.configuration, target)
|
||||
runner.run(self.packages(), built_packages)
|
||||
|
||||
def process_sync(self, targets: Optional[Iterable[str]]) -> None:
|
||||
def process_sync(self, targets: Optional[Iterable[str]], built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
process synchronization to remote servers
|
||||
:param targets: list of targets to sync. Configuration option will be used if it is not set
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
if targets is None:
|
||||
targets = self.config.getlist("upload", "target")
|
||||
targets = self.configuration.getlist("upload", "target")
|
||||
for target in targets:
|
||||
Uploader.run(self.architecture, self.config, target, self.paths.repository)
|
||||
runner = Upload.load(self.architecture, self.configuration, target)
|
||||
runner.run(self.paths.repository, built_packages)
|
||||
|
||||
def process_update(self, packages: Iterable[Path]) -> Path:
|
||||
"""
|
||||
@ -128,7 +132,7 @@ class Executor(Cleaner):
|
||||
"""
|
||||
def update_single(fn: Optional[str], base: str) -> None:
|
||||
if fn is None:
|
||||
self.logger.warning(f"received empty package name for base {base}")
|
||||
self.logger.warning("received empty package name for base %s", base)
|
||||
return # suppress type checking, it never can be none actually
|
||||
# in theory it might be NOT packages directory, but we suppose it is
|
||||
full_path = self.paths.packages / fn
|
||||
@ -146,7 +150,7 @@ class Executor(Cleaner):
|
||||
local = Package.load(filename, self.pacman, self.aur_url)
|
||||
updates.setdefault(local.base, local).packages.update(local.packages)
|
||||
except Exception:
|
||||
self.logger.exception(f"could not load package from {filename}")
|
||||
self.logger.exception("could not load package from %s", filename)
|
||||
|
||||
for local in updates.values():
|
||||
try:
|
||||
@ -155,7 +159,7 @@ class Executor(Cleaner):
|
||||
self.reporter.set_success(local)
|
||||
except Exception:
|
||||
self.reporter.set_failed(local.base)
|
||||
self.logger.exception(f"could not process {local.base}")
|
||||
self.logger.exception("could not process %s", local.base)
|
||||
self.clear_packages()
|
||||
|
||||
return self.repo.repo_path
|
||||
|
@ -32,7 +32,8 @@ class Properties:
|
||||
repository internal objects holder
|
||||
:ivar architecture: repository architecture
|
||||
:ivar aur_url: base AUR url
|
||||
:ivar config: configuration instance
|
||||
:ivar configuration: configuration instance
|
||||
:ivar ignore_list: package bases which will be ignored during auto updates
|
||||
:ivar logger: class logger
|
||||
:ivar name: repository name
|
||||
:ivar pacman: alpm wrapper instance
|
||||
@ -42,18 +43,19 @@ class Properties:
|
||||
:ivar sign: GPG wrapper instance
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
self.logger = logging.getLogger("builder")
|
||||
self.architecture = architecture
|
||||
self.config = config
|
||||
self.configuration = configuration
|
||||
|
||||
self.aur_url = config.get("alpm", "aur_url")
|
||||
self.name = config.get("repository", "name")
|
||||
self.aur_url = configuration.get("alpm", "aur_url")
|
||||
self.name = configuration.get("repository", "name")
|
||||
|
||||
self.paths = RepositoryPaths(config.getpath("repository", "root"), architecture)
|
||||
self.paths = RepositoryPaths(configuration.getpath("repository", "root"), architecture)
|
||||
self.paths.create_tree()
|
||||
|
||||
self.pacman = Pacman(config)
|
||||
self.sign = GPG(architecture, config)
|
||||
self.ignore_list = configuration.getlist("build", "ignore_packages")
|
||||
self.pacman = Pacman(configuration)
|
||||
self.sign = GPG(architecture, configuration)
|
||||
self.repo = Repo(self.name, self.paths, self.sign.repository_sign_args)
|
||||
self.reporter = Client.load(architecture, config)
|
||||
self.reporter = Client.load(configuration)
|
||||
|
@ -37,14 +37,12 @@ class Repository(Executor, UpdateHandler):
|
||||
:return: list of packages properties
|
||||
"""
|
||||
result: Dict[str, Package] = {}
|
||||
for full_path in self.paths.repository.iterdir():
|
||||
if not package_like(full_path):
|
||||
continue
|
||||
for full_path in filter(package_like, self.paths.repository.iterdir()):
|
||||
try:
|
||||
local = Package.load(full_path, self.pacman, self.aur_url)
|
||||
result.setdefault(local.base, local).packages.update(local.packages)
|
||||
except Exception:
|
||||
self.logger.exception(f"could not load package from {full_path}")
|
||||
self.logger.exception("could not load package from %s", full_path)
|
||||
continue
|
||||
return list(result.values())
|
||||
|
||||
@ -53,4 +51,4 @@ class Repository(Executor, UpdateHandler):
|
||||
get list of files in built packages directory
|
||||
:return: list of filenames from the directory
|
||||
"""
|
||||
return list(self.paths.packages.iterdir())
|
||||
return list(filter(package_like, self.paths.packages.iterdir()))
|
||||
|
@ -44,11 +44,8 @@ class UpdateHandler(Cleaner):
|
||||
"""
|
||||
result: List[Package] = []
|
||||
|
||||
build_section = self.config.get_section_name("build", self.architecture)
|
||||
ignore_list = self.config.getlist(build_section, "ignore_packages")
|
||||
|
||||
for local in self.packages():
|
||||
if local.base in ignore_list:
|
||||
if local.base in self.ignore_list:
|
||||
continue
|
||||
if local.is_vcs and no_vcs:
|
||||
continue
|
||||
@ -62,7 +59,7 @@ class UpdateHandler(Cleaner):
|
||||
result.append(remote)
|
||||
except Exception:
|
||||
self.reporter.set_failed(local.base)
|
||||
self.logger.exception(f"could not load remote package {local.base}")
|
||||
self.logger.exception("could not load remote package %s", local.base)
|
||||
continue
|
||||
|
||||
return result
|
||||
@ -84,7 +81,7 @@ class UpdateHandler(Cleaner):
|
||||
else:
|
||||
self.reporter.set_pending(local.base)
|
||||
except Exception:
|
||||
self.logger.exception(f"could not add package from {fn}")
|
||||
self.logger.exception("could not add package from %s", fn)
|
||||
self.clear_manual()
|
||||
|
||||
return result
|
||||
|
@ -18,13 +18,14 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import logging
|
||||
import requests
|
||||
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
from typing import List, Optional, Set, Tuple
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.exceptions import BuildFailed
|
||||
from ahriman.core.util import check_output
|
||||
from ahriman.core.util import check_output, exception_response_text
|
||||
from ahriman.models.sign_settings import SignSettings
|
||||
|
||||
|
||||
@ -32,37 +33,39 @@ class GPG:
|
||||
"""
|
||||
gnupg wrapper
|
||||
:ivar architecture: repository architecture
|
||||
:ivar config: configuration instance
|
||||
:ivar configuration: configuration instance
|
||||
:ivar default_key: default PGP key ID to use
|
||||
:ivar logger: class logger
|
||||
:ivar target: list of targets to sign (repository, package etc)
|
||||
:ivar targets: list of targets to sign (repository, package etc)
|
||||
"""
|
||||
|
||||
_check_output = check_output
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.logger = logging.getLogger("build_details")
|
||||
self.config = config
|
||||
self.section = config.get_section_name("sign", architecture)
|
||||
self.target = {SignSettings.from_option(opt) for opt in config.getlist(self.section, "target")}
|
||||
self.default_key = config.get(self.section, "key") if self.target else ""
|
||||
self.architecture = architecture
|
||||
self.configuration = configuration
|
||||
self.targets, self.default_key = self.sign_options(configuration)
|
||||
|
||||
@property
|
||||
def repository_sign_args(self) -> List[str]:
|
||||
"""
|
||||
:return: command line arguments for repo-add command to sign database
|
||||
"""
|
||||
if SignSettings.SignRepository not in self.target:
|
||||
if SignSettings.Repository not in self.targets:
|
||||
return []
|
||||
if self.default_key is None:
|
||||
self.logger.error("no default key set, skip repository sign")
|
||||
return []
|
||||
return ["--sign", "--key", self.default_key]
|
||||
|
||||
@staticmethod
|
||||
def sign_cmd(path: Path, key: str) -> List[str]:
|
||||
def sign_command(path: Path, key: str) -> List[str]:
|
||||
"""
|
||||
gpg command to run
|
||||
:param path: path to file to sign
|
||||
@ -71,6 +74,50 @@ class GPG:
|
||||
"""
|
||||
return ["gpg", "-u", key, "-b", str(path)]
|
||||
|
||||
@staticmethod
|
||||
def sign_options(configuration: Configuration) -> Tuple[Set[SignSettings], Optional[str]]:
|
||||
"""
|
||||
extract default sign options from configuration
|
||||
:param configuration: configuration instance
|
||||
:return: tuple of sign targets and default PGP key
|
||||
"""
|
||||
targets = {
|
||||
SignSettings.from_option(option)
|
||||
for option in configuration.getlist("sign", "target")
|
||||
}
|
||||
default_key = configuration.get("sign", "key") if targets else None
|
||||
return targets, default_key
|
||||
|
||||
def download_key(self, server: str, key: str) -> str:
|
||||
"""
|
||||
download key from public PGP server
|
||||
:param server: public PGP server which will be used to download the key
|
||||
:param key: key ID to download
|
||||
:return: key as plain text
|
||||
"""
|
||||
key = key if key.startswith("0x") else f"0x{key}"
|
||||
try:
|
||||
response = requests.get(f"http://{server}/pks/lookup", params={
|
||||
"op": "get",
|
||||
"options": "mr",
|
||||
"search": key
|
||||
})
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception("could not download key %s from %s: %s", key, server, exception_response_text(e))
|
||||
raise
|
||||
return response.text
|
||||
|
||||
def import_key(self, server: str, key: str) -> None:
|
||||
"""
|
||||
import key to current user and sign it locally
|
||||
:param server: public PGP server which will be used to download the key
|
||||
:param key: key ID to import
|
||||
"""
|
||||
key_body = self.download_key(server, key)
|
||||
GPG._check_output("gpg", "--import", input_data=key_body, exception=None, logger=self.logger)
|
||||
GPG._check_output("gpg", "--quick-lsign-key", key, exception=None, logger=self.logger)
|
||||
|
||||
def process(self, path: Path, key: str) -> List[Path]:
|
||||
"""
|
||||
gpg command wrapper
|
||||
@ -79,7 +126,7 @@ class GPG:
|
||||
:return: list of generated files including original file
|
||||
"""
|
||||
GPG._check_output(
|
||||
*GPG.sign_cmd(path, key),
|
||||
*GPG.sign_command(path, key),
|
||||
exception=BuildFailed(path.name),
|
||||
logger=self.logger)
|
||||
return [path, path.parent / f"{path.name}.sig"]
|
||||
@ -91,9 +138,12 @@ class GPG:
|
||||
:param base: package base required to check for key overrides
|
||||
:return: list of generated files including original file
|
||||
"""
|
||||
if SignSettings.SignPackages not in self.target:
|
||||
if SignSettings.Packages not in self.targets:
|
||||
return [path]
|
||||
key = self.configuration.get("sign", f"key_{base}", fallback=self.default_key)
|
||||
if key is None:
|
||||
self.logger.error("no default key set, skip package %s sign", path)
|
||||
return [path]
|
||||
key = self.config.get(self.section, f"key_{base}", fallback=self.default_key)
|
||||
return self.process(path, key)
|
||||
|
||||
def sign_repository(self, path: Path) -> List[Path]:
|
||||
@ -103,6 +153,9 @@ class GPG:
|
||||
:param path: path to repository database
|
||||
:return: list of generated files including original file
|
||||
"""
|
||||
if SignSettings.SignRepository not in self.target:
|
||||
if SignSettings.Repository not in self.targets:
|
||||
return [path]
|
||||
if self.default_key is None:
|
||||
self.logger.error("no default key set, skip repository sign")
|
||||
return [path]
|
||||
return self.process(path, self.default_key)
|
||||
|
@ -19,10 +19,11 @@
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import List, Optional, Tuple
|
||||
from typing import List, Optional, Tuple, Type
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.models.build_status import BuildStatus, BuildStatusEnum
|
||||
from ahriman.models.internal_status import InternalStatus
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
@ -31,6 +32,20 @@ class Client:
|
||||
base build status reporter client
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def load(cls: Type[Client], configuration: Configuration) -> Client:
|
||||
"""
|
||||
load client from settings
|
||||
:param configuration: configuration instance
|
||||
:return: client according to current settings
|
||||
"""
|
||||
host = configuration.get("web", "host", fallback=None)
|
||||
port = configuration.getint("web", "port", fallback=None)
|
||||
if host is not None and port is not None:
|
||||
from ahriman.core.status.web_client import WebClient
|
||||
return WebClient(host, port)
|
||||
return cls()
|
||||
|
||||
def add(self, package: Package, status: BuildStatusEnum) -> None:
|
||||
"""
|
||||
add new package with status
|
||||
@ -38,8 +53,7 @@ class Client:
|
||||
:param status: current package build status
|
||||
"""
|
||||
|
||||
# pylint: disable=no-self-use
|
||||
def get(self, base: Optional[str]) -> List[Tuple[Package, BuildStatus]]:
|
||||
def get(self, base: Optional[str]) -> List[Tuple[Package, BuildStatus]]: # pylint: disable=no-self-use
|
||||
"""
|
||||
get package status
|
||||
:param base: package base to get
|
||||
@ -48,8 +62,14 @@ class Client:
|
||||
del base
|
||||
return []
|
||||
|
||||
# pylint: disable=no-self-use
|
||||
def get_self(self) -> BuildStatus:
|
||||
def get_internal(self) -> InternalStatus: # pylint: disable=no-self-use
|
||||
"""
|
||||
get internal service status
|
||||
:return: current internal (web) service status
|
||||
"""
|
||||
return InternalStatus()
|
||||
|
||||
def get_self(self) -> BuildStatus: # pylint: disable=no-self-use
|
||||
"""
|
||||
get ahriman status itself
|
||||
:return: current ahriman status
|
||||
@ -109,20 +129,3 @@ class Client:
|
||||
:param package: current package properties
|
||||
"""
|
||||
return self.add(package, BuildStatusEnum.Unknown)
|
||||
|
||||
@staticmethod
|
||||
def load(architecture: str, config: Configuration) -> Client:
|
||||
"""
|
||||
load client from settings
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:return: client according to current settings
|
||||
"""
|
||||
section = config.get_section_name("web", architecture)
|
||||
host = config.get(section, "host", fallback=None)
|
||||
port = config.getint(section, "port", fallback=None)
|
||||
if host is None or port is None:
|
||||
return Client()
|
||||
|
||||
from ahriman.core.status.web_client import WebClient
|
||||
return WebClient(host, port)
|
||||
|
@ -40,16 +40,16 @@ class Watcher:
|
||||
:ivar status: daemon status
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.logger = logging.getLogger("http")
|
||||
|
||||
self.architecture = architecture
|
||||
self.repository = Repository(architecture, config)
|
||||
self.repository = Repository(architecture, configuration)
|
||||
|
||||
self.known: Dict[str, Tuple[Package, BuildStatus]] = {}
|
||||
self.status = BuildStatus()
|
||||
@ -90,7 +90,7 @@ class Watcher:
|
||||
try:
|
||||
parse_single(item)
|
||||
except Exception:
|
||||
self.logger.exception(f"cannot parse item f{item} to package")
|
||||
self.logger.exception("cannot parse item %s to package", item)
|
||||
|
||||
def _cache_save(self) -> None:
|
||||
"""
|
||||
|
@ -23,7 +23,9 @@ import requests
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from ahriman.core.status.client import Client
|
||||
from ahriman.core.util import exception_response_text
|
||||
from ahriman.models.build_status import BuildStatusEnum, BuildStatus
|
||||
from ahriman.models.internal_status import InternalStatus
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
@ -60,6 +62,13 @@ class WebClient(Client):
|
||||
"""
|
||||
return f"http://{self.host}:{self.port}/api/v1/packages/{base}"
|
||||
|
||||
def _status_url(self) -> str:
|
||||
"""
|
||||
url generator
|
||||
:return: full url for web service for status
|
||||
"""
|
||||
return f"http://{self.host}:{self.port}/api/v1/status"
|
||||
|
||||
def add(self, package: Package, status: BuildStatusEnum) -> None:
|
||||
"""
|
||||
add new package with status
|
||||
@ -75,9 +84,9 @@ class WebClient(Client):
|
||||
response = requests.post(self._package_url(package.base), json=payload)
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception(f"could not add {package.base}: {e.response.text}")
|
||||
self.logger.exception("could not add %s: %s", package.base, exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception(f"could not add {package.base}")
|
||||
self.logger.exception("could not add %s", package.base)
|
||||
|
||||
def get(self, base: Optional[str]) -> List[Tuple[Package, BuildStatus]]:
|
||||
"""
|
||||
@ -95,11 +104,28 @@ class WebClient(Client):
|
||||
for package in status_json
|
||||
]
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception(f"could not get {base}: {e.response.text}")
|
||||
self.logger.exception("could not get %s: %s", base, exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception(f"could not get {base}")
|
||||
self.logger.exception("could not get %s", base)
|
||||
return []
|
||||
|
||||
def get_internal(self) -> InternalStatus:
|
||||
"""
|
||||
get internal service status
|
||||
:return: current internal (web) service status
|
||||
"""
|
||||
try:
|
||||
response = requests.get(self._status_url())
|
||||
response.raise_for_status()
|
||||
|
||||
status_json = response.json()
|
||||
return InternalStatus.from_json(status_json)
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception("could not get web service status: %s", exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception("could not get web service status")
|
||||
return InternalStatus()
|
||||
|
||||
def get_self(self) -> BuildStatus:
|
||||
"""
|
||||
get ahriman status itself
|
||||
@ -112,7 +138,7 @@ class WebClient(Client):
|
||||
status_json = response.json()
|
||||
return BuildStatus.from_json(status_json)
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception(f"could not get service status: {e.response.text}")
|
||||
self.logger.exception("could not get service status: %s", exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception("could not get service status")
|
||||
return BuildStatus()
|
||||
@ -126,9 +152,9 @@ class WebClient(Client):
|
||||
response = requests.delete(self._package_url(base))
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception(f"could not delete {base}: {e.response.text}")
|
||||
self.logger.exception("could not delete %s: %s", base, exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception(f"could not delete {base}")
|
||||
self.logger.exception("could not delete %s", base)
|
||||
|
||||
def update(self, base: str, status: BuildStatusEnum) -> None:
|
||||
"""
|
||||
@ -142,9 +168,9 @@ class WebClient(Client):
|
||||
response = requests.post(self._package_url(base), json=payload)
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception(f"could not update {base}: {e.response.text}")
|
||||
self.logger.exception("could not update %s: %s", base, exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception(f"could not update {base}")
|
||||
self.logger.exception("could not update %s", base)
|
||||
|
||||
def update_self(self, status: BuildStatusEnum) -> None:
|
||||
"""
|
||||
@ -157,6 +183,6 @@ class WebClient(Client):
|
||||
response = requests.post(self._ahriman_url(), json=payload)
|
||||
response.raise_for_status()
|
||||
except requests.exceptions.HTTPError as e:
|
||||
self.logger.exception(f"could not update service status: {e.response.text}")
|
||||
self.logger.exception("could not update service status: %s", exception_response_text(e))
|
||||
except Exception:
|
||||
self.logger.exception("could not update service status")
|
||||
|
@ -18,43 +18,37 @@
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.upload.uploader import Uploader
|
||||
from ahriman.core.upload.upload import Upload
|
||||
from ahriman.core.util import check_output
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
class Rsync(Uploader):
|
||||
class Rsync(Upload):
|
||||
"""
|
||||
rsync wrapper
|
||||
:ivar command: command arguments for sync
|
||||
:ivar remote: remote address to sync
|
||||
"""
|
||||
|
||||
_check_output = check_output
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Uploader.__init__(self, architecture, config)
|
||||
section = config.get_section_name("rsync", architecture)
|
||||
self.remote = config.get(section, "remote")
|
||||
Upload.__init__(self, architecture, configuration)
|
||||
self.command = configuration.getlist("rsync", "command")
|
||||
self.remote = configuration.get("rsync", "remote")
|
||||
|
||||
def sync(self, path: Path) -> None:
|
||||
def sync(self, path: Path, built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
sync data to remote server
|
||||
:param path: local path to sync
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
Rsync._check_output(
|
||||
"rsync",
|
||||
"--archive",
|
||||
"--verbose",
|
||||
"--compress",
|
||||
"--partial",
|
||||
"--delete",
|
||||
str(path),
|
||||
self.remote,
|
||||
exception=None,
|
||||
logger=self.logger)
|
||||
Rsync._check_output(*self.command, str(path), self.remote, exception=None, logger=self.logger)
|
||||
|
@ -17,37 +17,137 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
import boto3 # type: ignore
|
||||
import hashlib
|
||||
import mimetypes
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Generator, Iterable
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.upload.uploader import Uploader
|
||||
from ahriman.core.util import check_output
|
||||
from ahriman.core.upload.upload import Upload
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
class S3(Uploader):
|
||||
class S3(Upload):
|
||||
"""
|
||||
aws-cli wrapper
|
||||
:ivar bucket: full bucket name
|
||||
:ivar bucket: boto3 S3 bucket object
|
||||
:ivar chunk_size: chunk size for calculating checksums
|
||||
"""
|
||||
|
||||
_check_output = check_output
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
Uploader.__init__(self, architecture, config)
|
||||
section = config.get_section_name("s3", architecture)
|
||||
self.bucket = config.get(section, "bucket")
|
||||
Upload.__init__(self, architecture, configuration)
|
||||
self.bucket = self.get_bucket(configuration)
|
||||
self.chunk_size = configuration.getint("s3", "chunk_size", fallback=8 * 1024 * 1024)
|
||||
|
||||
def sync(self, path: Path) -> None:
|
||||
@staticmethod
|
||||
def calculate_etag(path: Path, chunk_size: int) -> str:
|
||||
"""
|
||||
calculate amazon s3 etag
|
||||
credits to https://teppen.io/2018/10/23/aws_s3_verify_etags/
|
||||
For this method we have to define nosec because it is out of any security context and provided by AWS
|
||||
:param path: path to local file
|
||||
:param chunk_size: read chunk size, which depends on client settings
|
||||
:return: calculated entity tag for local file
|
||||
"""
|
||||
md5s = []
|
||||
with path.open("rb") as local_file:
|
||||
for chunk in iter(lambda: local_file.read(chunk_size), b""):
|
||||
md5s.append(hashlib.md5(chunk)) # nosec
|
||||
|
||||
# in case if there is only one chunk it must be just this checksum
|
||||
# and checksum of joined digest otherwise (including empty list)
|
||||
checksum = md5s[0] if len(md5s) == 1 else hashlib.md5(b"".join(md5.digest() for md5 in md5s)) # nosec
|
||||
# in case if there are more than one chunk it should be appended with amount of chunks
|
||||
suffix = f"-{len(md5s)}" if len(md5s) > 1 else ""
|
||||
return f"{checksum.hexdigest()}{suffix}"
|
||||
|
||||
@staticmethod
|
||||
def get_bucket(configuration: Configuration) -> Any:
|
||||
"""
|
||||
create resource client from configuration
|
||||
:param configuration: configuration instance
|
||||
:return: amazon client
|
||||
"""
|
||||
client = boto3.resource(service_name="s3",
|
||||
region_name=configuration.get("s3", "region"),
|
||||
aws_access_key_id=configuration.get("s3", "access_key"),
|
||||
aws_secret_access_key=configuration.get("s3", "secret_key"))
|
||||
return client.Bucket(configuration.get("s3", "bucket"))
|
||||
|
||||
@staticmethod
|
||||
def remove_files(local_files: Dict[Path, str], remote_objects: Dict[Path, Any]) -> None:
|
||||
"""
|
||||
remove files which have been removed locally
|
||||
:param local_files: map of local path object to its checksum
|
||||
:param remote_objects: map of remote path object to the remote s3 object
|
||||
"""
|
||||
for local_file, remote_object in remote_objects.items():
|
||||
if local_file in local_files:
|
||||
continue
|
||||
remote_object.delete()
|
||||
|
||||
def get_local_files(self, path: Path) -> Dict[Path, str]:
|
||||
"""
|
||||
get all local files and their calculated checksums
|
||||
:param path: local path to sync
|
||||
:return: map of path object to its checksum
|
||||
"""
|
||||
# credits to https://stackoverflow.com/a/64915960
|
||||
def walk(directory_path: Path) -> Generator[Path, None, None]:
|
||||
for element in directory_path.iterdir():
|
||||
if element.is_dir():
|
||||
yield from walk(element)
|
||||
continue
|
||||
yield element
|
||||
return {
|
||||
local_file.relative_to(path): self.calculate_etag(local_file, self.chunk_size)
|
||||
for local_file in walk(path)
|
||||
}
|
||||
|
||||
def get_remote_objects(self) -> Dict[Path, Any]:
|
||||
"""
|
||||
get all remote objects and their checksums
|
||||
:return: map of path object to the remote s3 object
|
||||
"""
|
||||
objects = self.bucket.objects.filter(Prefix=self.architecture)
|
||||
return {Path(item.key).relative_to(self.architecture): item for item in objects}
|
||||
|
||||
def sync(self, path: Path, built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
sync data to remote server
|
||||
:param path: local path to sync
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
# TODO rewrite to boto, but it is bullshit
|
||||
S3._check_output("aws", "s3", "sync", "--quiet", "--delete", str(path), self.bucket,
|
||||
exception=None,
|
||||
logger=self.logger)
|
||||
remote_objects = self.get_remote_objects()
|
||||
local_files = self.get_local_files(path)
|
||||
|
||||
self.upload_files(path, local_files, remote_objects)
|
||||
self.remove_files(local_files, remote_objects)
|
||||
|
||||
def upload_files(self, path: Path, local_files: Dict[Path, str], remote_objects: Dict[Path, Any]) -> None:
|
||||
"""
|
||||
upload changed files to s3
|
||||
:param path: local path to sync
|
||||
:param local_files: map of local path object to its checksum
|
||||
:param remote_objects: map of remote path object to the remote s3 object
|
||||
"""
|
||||
for local_file, checksum in local_files.items():
|
||||
remote_object = remote_objects.get(local_file)
|
||||
# 0 and -1 elements are " (double quote)
|
||||
remote_checksum = remote_object.e_tag[1:-1] if remote_object is not None else None
|
||||
if remote_checksum == checksum:
|
||||
continue
|
||||
|
||||
local_path = path / local_file
|
||||
remote_path = Path(self.architecture) / local_file
|
||||
(mime, _) = mimetypes.guess_type(local_path)
|
||||
extra_args = {"Content-Type": mime} if mime is not None else None
|
||||
|
||||
self.bucket.upload_file(Filename=str(local_path), Key=str(remote_path), ExtraArgs=extra_args)
|
||||
|
@ -17,60 +17,70 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Iterable, Type
|
||||
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.exceptions import SyncFailed
|
||||
from ahriman.models.package import Package
|
||||
from ahriman.models.upload_settings import UploadSettings
|
||||
|
||||
|
||||
class Uploader:
|
||||
class Upload:
|
||||
"""
|
||||
base remote sync class
|
||||
:ivar architecture: repository architecture
|
||||
:ivar config: configuration instance
|
||||
:ivar configuration: configuration instance
|
||||
:ivar logger: application logger
|
||||
"""
|
||||
|
||||
def __init__(self, architecture: str, config: Configuration) -> None:
|
||||
def __init__(self, architecture: str, configuration: Configuration) -> None:
|
||||
"""
|
||||
default constructor
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
"""
|
||||
self.logger = logging.getLogger("builder")
|
||||
self.architecture = architecture
|
||||
self.config = config
|
||||
self.config = configuration
|
||||
|
||||
@staticmethod
|
||||
def run(architecture: str, config: Configuration, target: str, path: Path) -> None:
|
||||
@classmethod
|
||||
def load(cls: Type[Upload], architecture: str, configuration: Configuration, target: str) -> Upload:
|
||||
"""
|
||||
run remote sync
|
||||
load client from settings
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
:param target: target to run sync (e.g. s3)
|
||||
:param path: local path to sync
|
||||
:return: client according to current settings
|
||||
"""
|
||||
provider = UploadSettings.from_option(target)
|
||||
if provider == UploadSettings.Rsync:
|
||||
from ahriman.core.upload.rsync import Rsync
|
||||
uploader: Uploader = Rsync(architecture, config)
|
||||
elif provider == UploadSettings.S3:
|
||||
return Rsync(architecture, configuration)
|
||||
if provider == UploadSettings.S3:
|
||||
from ahriman.core.upload.s3 import S3
|
||||
uploader = S3(architecture, config)
|
||||
else:
|
||||
uploader = Uploader(architecture, config)
|
||||
return S3(architecture, configuration)
|
||||
return cls(architecture, configuration) # should never happen
|
||||
|
||||
def run(self, path: Path, built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
run remote sync
|
||||
:param path: local path to sync
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
||||
try:
|
||||
uploader.sync(path)
|
||||
self.sync(path, built_packages)
|
||||
except Exception:
|
||||
uploader.logger.exception(f"remote sync failed for {provider.name}")
|
||||
self.logger.exception("remote sync failed")
|
||||
raise SyncFailed()
|
||||
|
||||
def sync(self, path: Path) -> None:
|
||||
def sync(self, path: Path, built_packages: Iterable[Package]) -> None:
|
||||
"""
|
||||
sync data to remote server
|
||||
:param path: local path to sync
|
||||
:param built_packages: list of packages which has just been built
|
||||
"""
|
@ -19,37 +19,51 @@
|
||||
#
|
||||
import datetime
|
||||
import subprocess
|
||||
import requests
|
||||
|
||||
from logging import Logger
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from typing import Optional, Union
|
||||
|
||||
from ahriman.core.exceptions import InvalidOption
|
||||
|
||||
|
||||
def check_output(*args: str, exception: Optional[Exception],
|
||||
cwd: Optional[Path] = None, logger: Optional[Logger] = None) -> str:
|
||||
def check_output(*args: str, exception: Optional[Exception], cwd: Optional[Path] = None,
|
||||
input_data: Optional[str] = None, logger: Optional[Logger] = None) -> str:
|
||||
"""
|
||||
subprocess wrapper
|
||||
:param args: command line arguments
|
||||
:param exception: exception which has to be reraised instead of default subprocess exception
|
||||
:param cwd: current working directory
|
||||
:param input_data: data which will be written to command stdin
|
||||
:param logger: logger to log command result if required
|
||||
:return: command output
|
||||
"""
|
||||
try:
|
||||
result = subprocess.check_output(args, cwd=cwd, stderr=subprocess.STDOUT).decode("utf8").strip()
|
||||
# universal_newlines is required to read input from string
|
||||
result: str = subprocess.check_output(args, cwd=cwd, input=input_data, stderr=subprocess.STDOUT,
|
||||
universal_newlines=True).strip()
|
||||
if logger is not None:
|
||||
for line in result.splitlines():
|
||||
logger.debug(line)
|
||||
except subprocess.CalledProcessError as e:
|
||||
if e.output is not None and logger is not None:
|
||||
for line in e.output.decode("utf8").splitlines():
|
||||
for line in e.output.splitlines():
|
||||
logger.debug(line)
|
||||
raise exception or e
|
||||
return result
|
||||
|
||||
|
||||
def exception_response_text(exception: requests.exceptions.HTTPError) -> str:
|
||||
"""
|
||||
safe response exception text generation
|
||||
:param exception: exception raised
|
||||
:return: text of the response if it is not None and empty string otherwise
|
||||
"""
|
||||
result: str = exception.response.text if exception.response is not None else ""
|
||||
return result
|
||||
|
||||
|
||||
def package_like(filename: Path) -> bool:
|
||||
"""
|
||||
check if file looks like package
|
||||
@ -60,7 +74,7 @@ def package_like(filename: Path) -> bool:
|
||||
return ".pkg." in name and not name.endswith(".sig")
|
||||
|
||||
|
||||
def pretty_datetime(timestamp: Optional[int]) -> str:
|
||||
def pretty_datetime(timestamp: Optional[Union[float, int]]) -> str:
|
||||
"""
|
||||
convert datetime object to string
|
||||
:param timestamp: datetime to convert
|
||||
@ -89,6 +103,6 @@ def pretty_size(size: Optional[float], level: int = 0) -> str:
|
||||
|
||||
if size is None:
|
||||
return ""
|
||||
if size < 1024 or level == 3:
|
||||
if size < 1024 or level >= 3:
|
||||
return f"{size:.1f} {str_level()}"
|
||||
return pretty_size(size / 1024, level + 1)
|
||||
|
@ -63,7 +63,7 @@ class BuildStatus:
|
||||
"""
|
||||
build status holder
|
||||
:ivar status: build status
|
||||
:ivar _timestamp: build status update time
|
||||
:ivar timestamp: build status update time
|
||||
"""
|
||||
|
||||
def __init__(self, status: Union[BuildStatusEnum, str, None] = None,
|
||||
|
71
src/ahriman/models/counters.py
Normal file
71
src/ahriman/models/counters.py
Normal file
@ -0,0 +1,71 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, fields
|
||||
from typing import Any, Dict, List, Tuple, Type
|
||||
|
||||
from ahriman.models.build_status import BuildStatus
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
@dataclass
|
||||
class Counters:
|
||||
"""
|
||||
package counters
|
||||
:ivar total: total packages count
|
||||
:ivar unknown: packages in unknown status count
|
||||
:ivar pending: packages in pending status count
|
||||
:ivar building: packages in building status count
|
||||
:ivar failed: packages in failed status count
|
||||
:ivar success: packages in success status count
|
||||
"""
|
||||
total: int
|
||||
unknown: int = 0
|
||||
pending: int = 0
|
||||
building: int = 0
|
||||
failed: int = 0
|
||||
success: int = 0
|
||||
|
||||
@classmethod
|
||||
def from_json(cls: Type[Counters], dump: Dict[str, Any]) -> Counters:
|
||||
"""
|
||||
construct counters from json dump
|
||||
:param dump: json dump body
|
||||
:return: status counters
|
||||
"""
|
||||
# filter to only known fields
|
||||
known_fields = [pair.name for pair in fields(cls)]
|
||||
dump = {key: value for key, value in dump.items() if key in known_fields}
|
||||
return cls(**dump)
|
||||
|
||||
@classmethod
|
||||
def from_packages(cls: Type[Counters], packages: List[Tuple[Package, BuildStatus]]) -> Counters:
|
||||
"""
|
||||
construct counters from packages statuses
|
||||
:param packages: list of package and their status as per watcher property
|
||||
:return: status counters
|
||||
"""
|
||||
per_status = {"total": len(packages)}
|
||||
for _, status in packages:
|
||||
key = status.status.name.lower()
|
||||
per_status.setdefault(key, 0)
|
||||
per_status[key] += 1
|
||||
return cls(**per_status)
|
60
src/ahriman/models/internal_status.py
Normal file
60
src/ahriman/models/internal_status.py
Normal file
@ -0,0 +1,60 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Dict, Optional, Type
|
||||
|
||||
from ahriman.models.counters import Counters
|
||||
|
||||
|
||||
@dataclass
|
||||
class InternalStatus:
|
||||
"""
|
||||
internal server status
|
||||
:ivar architecture: repository architecture
|
||||
:ivar packages: packages statuses counter object
|
||||
:ivar repository: repository name
|
||||
:ivar version: service version
|
||||
"""
|
||||
architecture: Optional[str] = None
|
||||
packages: Counters = field(default=Counters(total=0))
|
||||
repository: Optional[str] = None
|
||||
version: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls: Type[InternalStatus], dump: Dict[str, Any]) -> InternalStatus:
|
||||
"""
|
||||
construct internal status from json dump
|
||||
:param dump: json dump body
|
||||
:return: internal status
|
||||
"""
|
||||
counters = Counters.from_json(dump["packages"]) if "packages" in dump else Counters(total=0)
|
||||
return cls(architecture=dump.get("architecture"),
|
||||
packages=counters,
|
||||
repository=dump.get("repository"),
|
||||
version=dump.get("version"))
|
||||
|
||||
def view(self) -> Dict[str, Any]:
|
||||
"""
|
||||
generate json status view
|
||||
:return: json-friendly dictionary
|
||||
"""
|
||||
return asdict(self)
|
@ -31,7 +31,7 @@ from typing import Any, Dict, List, Optional, Set, Type, Union
|
||||
from ahriman.core.alpm.pacman import Pacman
|
||||
from ahriman.core.exceptions import InvalidPackageInfo
|
||||
from ahriman.core.util import check_output
|
||||
from ahriman.models.package_desciption import PackageDescription
|
||||
from ahriman.models.package_description import PackageDescription
|
||||
from ahriman.models.repository_paths import RepositoryPaths
|
||||
|
||||
|
||||
@ -52,6 +52,13 @@ class Package:
|
||||
|
||||
_check_output = check_output
|
||||
|
||||
@property
|
||||
def depends(self) -> List[str]:
|
||||
"""
|
||||
:return: sum of dependencies per arch package
|
||||
"""
|
||||
return sorted(set(sum([package.depends for package in self.packages.values()], start=[])))
|
||||
|
||||
@property
|
||||
def git_url(self) -> str:
|
||||
"""
|
||||
@ -147,7 +154,7 @@ class Package:
|
||||
:return: package properties
|
||||
"""
|
||||
packages = {
|
||||
key: PackageDescription(**value)
|
||||
key: PackageDescription.from_json(value)
|
||||
for key, value in dump.get("packages", {}).items()
|
||||
}
|
||||
return Package(
|
||||
@ -156,6 +163,27 @@ class Package:
|
||||
aur_url=dump["aur_url"],
|
||||
packages=packages)
|
||||
|
||||
@classmethod
|
||||
def load(cls: Type[Package], path: Union[Path, str], pacman: Pacman, aur_url: str) -> Package:
|
||||
"""
|
||||
package constructor from available sources
|
||||
:param path: one of path to sources directory, path to archive or package name/base
|
||||
:param pacman: alpm wrapper instance (required to load from archive)
|
||||
:param aur_url: AUR root url
|
||||
:return: package properties
|
||||
"""
|
||||
try:
|
||||
maybe_path = Path(path)
|
||||
if maybe_path.is_dir():
|
||||
return cls.from_build(maybe_path, aur_url)
|
||||
if maybe_path.is_file():
|
||||
return cls.from_archive(maybe_path, pacman, aur_url)
|
||||
return cls.from_aur(str(path), aur_url)
|
||||
except InvalidPackageInfo:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise InvalidPackageInfo(str(e))
|
||||
|
||||
@staticmethod
|
||||
def dependencies(path: Path) -> Set[str]:
|
||||
"""
|
||||
@ -194,29 +222,6 @@ class Package:
|
||||
prefix = f"{epoch}:" if epoch else ""
|
||||
return f"{prefix}{pkgver}-{pkgrel}"
|
||||
|
||||
@staticmethod
|
||||
def load(path: Union[Path, str], pacman: Pacman, aur_url: str) -> Package:
|
||||
"""
|
||||
package constructor from available sources
|
||||
:param path: one of path to sources directory, path to archive or package name/base
|
||||
:param pacman: alpm wrapper instance (required to load from archive)
|
||||
:param aur_url: AUR root url
|
||||
:return: package properties
|
||||
"""
|
||||
try:
|
||||
maybe_path = Path(path)
|
||||
if maybe_path.is_dir():
|
||||
package: Package = Package.from_build(maybe_path, aur_url)
|
||||
elif maybe_path.is_file():
|
||||
package = Package.from_archive(maybe_path, pacman, aur_url)
|
||||
else:
|
||||
package = Package.from_aur(str(path), aur_url)
|
||||
return package
|
||||
except InvalidPackageInfo:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise InvalidPackageInfo(str(e))
|
||||
|
||||
def actual_version(self, paths: RepositoryPaths) -> str:
|
||||
"""
|
||||
additional method to handle VCS package versions
|
||||
|
@ -19,10 +19,10 @@
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass, field, fields
|
||||
from pathlib import Path
|
||||
from pyalpm import Package # type: ignore
|
||||
from typing import List, Optional, Type
|
||||
from typing import Any, Dict, List, Optional, Type
|
||||
|
||||
|
||||
@dataclass
|
||||
@ -32,22 +32,26 @@ class PackageDescription:
|
||||
:ivar architecture: package architecture
|
||||
:ivar archive_size: package archive size
|
||||
:ivar build_date: package build date
|
||||
:ivar depends: package dependencies list
|
||||
:ivar description: package description
|
||||
:ivar filename: package archive name
|
||||
:ivar groups: package groups
|
||||
:ivar installed_size: package installed size
|
||||
:ivar licenses: package licenses list
|
||||
:ivar provides: list of provided packages
|
||||
:ivar url: package url
|
||||
"""
|
||||
|
||||
architecture: Optional[str] = None
|
||||
archive_size: Optional[int] = None
|
||||
build_date: Optional[int] = None
|
||||
depends: List[str] = field(default_factory=list)
|
||||
description: Optional[str] = None
|
||||
filename: Optional[str] = None
|
||||
groups: List[str] = field(default_factory=list)
|
||||
installed_size: Optional[int] = None
|
||||
licenses: List[str] = field(default_factory=list)
|
||||
provides: List[str] = field(default_factory=list)
|
||||
url: Optional[str] = None
|
||||
|
||||
@property
|
||||
@ -57,6 +61,18 @@ class PackageDescription:
|
||||
"""
|
||||
return Path(self.filename) if self.filename is not None else None
|
||||
|
||||
@classmethod
|
||||
def from_json(cls: Type[PackageDescription], dump: Dict[str, Any]) -> PackageDescription:
|
||||
"""
|
||||
construct package properties from json dump
|
||||
:param dump: json dump body
|
||||
:return: package properties
|
||||
"""
|
||||
# filter to only known fields
|
||||
known_fields = [pair.name for pair in fields(cls)]
|
||||
dump = {key: value for key, value in dump.items() if key in known_fields}
|
||||
return cls(**dump)
|
||||
|
||||
@classmethod
|
||||
def from_package(cls: Type[PackageDescription], package: Package, path: Path) -> PackageDescription:
|
||||
"""
|
||||
@ -65,13 +81,15 @@ class PackageDescription:
|
||||
:param path: path to package archive
|
||||
:return: package properties based on tarball
|
||||
"""
|
||||
return PackageDescription(
|
||||
return cls(
|
||||
architecture=package.arch,
|
||||
archive_size=package.size,
|
||||
build_date=package.builddate,
|
||||
depends=package.depends,
|
||||
description=package.desc,
|
||||
filename=path.name,
|
||||
groups=package.groups,
|
||||
installed_size=package.isize,
|
||||
licenses=package.licenses,
|
||||
provides=package.provides,
|
||||
url=package.url)
|
@ -20,6 +20,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum, auto
|
||||
from typing import Type
|
||||
|
||||
from ahriman.core.exceptions import InvalidOption
|
||||
|
||||
@ -27,18 +28,24 @@ from ahriman.core.exceptions import InvalidOption
|
||||
class ReportSettings(Enum):
|
||||
"""
|
||||
report targets enumeration
|
||||
:cvar Disabled: option which generates no report for testing purpose
|
||||
:cvar HTML: html report generation
|
||||
:cvar Email: email report generation
|
||||
"""
|
||||
|
||||
Disabled = auto() # for testing purpose
|
||||
HTML = auto()
|
||||
Email = auto()
|
||||
|
||||
@staticmethod
|
||||
def from_option(value: str) -> ReportSettings:
|
||||
@classmethod
|
||||
def from_option(cls: Type[ReportSettings], value: str) -> ReportSettings:
|
||||
"""
|
||||
construct value from configuration
|
||||
:param value: configuration value
|
||||
:return: parsed value
|
||||
"""
|
||||
if value.lower() in ("html",):
|
||||
return ReportSettings.HTML
|
||||
return cls.HTML
|
||||
if value.lower() in ("email",):
|
||||
return cls.Email
|
||||
raise InvalidOption(value)
|
||||
|
@ -17,9 +17,11 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from pathlib import Path
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Set, Type
|
||||
|
||||
|
||||
@dataclass
|
||||
@ -76,6 +78,20 @@ class RepositoryPaths:
|
||||
"""
|
||||
return self.root / "sources" / self.architecture
|
||||
|
||||
@classmethod
|
||||
def known_architectures(cls: Type[RepositoryPaths], root: Path) -> Set[str]:
|
||||
"""
|
||||
get known architectures
|
||||
:param root: repository root
|
||||
:return: list of architectures for which tree is created
|
||||
"""
|
||||
paths = cls(root, "")
|
||||
return {
|
||||
path.name
|
||||
for path in paths.repository.iterdir()
|
||||
if path.is_dir()
|
||||
}
|
||||
|
||||
def create_tree(self) -> None:
|
||||
"""
|
||||
create ahriman working tree
|
||||
|
@ -20,6 +20,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum, auto
|
||||
from typing import Type
|
||||
|
||||
from ahriman.core.exceptions import InvalidOption
|
||||
|
||||
@ -27,22 +28,22 @@ from ahriman.core.exceptions import InvalidOption
|
||||
class SignSettings(Enum):
|
||||
"""
|
||||
sign targets enumeration
|
||||
:cvar SignPackages: sign each package
|
||||
:cvar SignRepository: sign repository database file
|
||||
:cvar Packages: sign each package
|
||||
:cvar Repository: sign repository database file
|
||||
"""
|
||||
|
||||
SignPackages = auto()
|
||||
SignRepository = auto()
|
||||
Packages = auto()
|
||||
Repository = auto()
|
||||
|
||||
@staticmethod
|
||||
def from_option(value: str) -> SignSettings:
|
||||
@classmethod
|
||||
def from_option(cls: Type[SignSettings], value: str) -> SignSettings:
|
||||
"""
|
||||
construct value from configuration
|
||||
:param value: configuration value
|
||||
:return: parsed value
|
||||
"""
|
||||
if value.lower() in ("package", "packages", "sign-package"):
|
||||
return SignSettings.SignPackages
|
||||
return cls.Packages
|
||||
if value.lower() in ("repository", "sign-repository"):
|
||||
return SignSettings.SignRepository
|
||||
return cls.Repository
|
||||
raise InvalidOption(value)
|
||||
|
49
src/ahriman/models/smtp_ssl_settings.py
Normal file
49
src/ahriman/models/smtp_ssl_settings.py
Normal file
@ -0,0 +1,49 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum, auto
|
||||
from typing import Type
|
||||
|
||||
|
||||
class SmtpSSLSettings(Enum):
|
||||
"""
|
||||
SMTP SSL mode enumeration
|
||||
:cvar Disabled: no SSL enabled
|
||||
:cvar SSL: use SMTP_SSL instead of normal SMTP client
|
||||
:cvar STARTTLS: use STARTTLS in normal SMTP client
|
||||
"""
|
||||
|
||||
Disabled = auto()
|
||||
SSL = auto()
|
||||
STARTTLS = auto()
|
||||
|
||||
@classmethod
|
||||
def from_option(cls: Type[SmtpSSLSettings], value: str) -> SmtpSSLSettings:
|
||||
"""
|
||||
construct value from configuration
|
||||
:param value: configuration value
|
||||
:return: parsed value
|
||||
"""
|
||||
if value.lower() in ("ssl", "ssl/tls"):
|
||||
return cls.SSL
|
||||
if value.lower() in ("starttls",):
|
||||
return cls.STARTTLS
|
||||
return cls.Disabled
|
@ -20,6 +20,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum, auto
|
||||
from typing import Type
|
||||
|
||||
from ahriman.core.exceptions import InvalidOption
|
||||
|
||||
@ -27,22 +28,24 @@ from ahriman.core.exceptions import InvalidOption
|
||||
class UploadSettings(Enum):
|
||||
"""
|
||||
remote synchronization targets enumeration
|
||||
:cvar Disabled: no sync will be performed, required for testing purpose
|
||||
:cvar Rsync: sync via rsync
|
||||
:cvar S3: sync to Amazon S3
|
||||
"""
|
||||
|
||||
Disabled = auto() # for testing purpose
|
||||
Rsync = auto()
|
||||
S3 = auto()
|
||||
|
||||
@staticmethod
|
||||
def from_option(value: str) -> UploadSettings:
|
||||
@classmethod
|
||||
def from_option(cls: Type[UploadSettings], value: str) -> UploadSettings:
|
||||
"""
|
||||
construct value from configuration
|
||||
:param value: configuration value
|
||||
:return: parsed value
|
||||
"""
|
||||
if value.lower() in ("rsync",):
|
||||
return UploadSettings.Rsync
|
||||
return cls.Rsync
|
||||
if value.lower() in ("s3",):
|
||||
return UploadSettings.S3
|
||||
return cls.S3
|
||||
raise InvalidOption(value)
|
||||
|
@ -17,4 +17,4 @@
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
__version__ = "0.18.0"
|
||||
__version__ = "1.2.5"
|
||||
|
@ -40,7 +40,7 @@ def exception_handler(logger: Logger) -> Callable[[Request, HandlerType], Awaita
|
||||
except HTTPClientError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.exception(f"exception during performing request to {request.path}")
|
||||
logger.exception("exception during performing request to %s", request.path)
|
||||
raise
|
||||
|
||||
return handle
|
||||
|
@ -23,6 +23,7 @@ from ahriman.web.views.ahriman import AhrimanView
|
||||
from ahriman.web.views.index import IndexView
|
||||
from ahriman.web.views.package import PackageView
|
||||
from ahriman.web.views.packages import PackagesView
|
||||
from ahriman.web.views.status import StatusView
|
||||
|
||||
|
||||
def setup_routes(application: Application) -> None:
|
||||
@ -44,6 +45,8 @@ def setup_routes(application: Application) -> None:
|
||||
GET /api/v1/package/:base get package base status
|
||||
POST /api/v1/package/:base update package base status
|
||||
|
||||
GET /api/v1/status get web service status itself
|
||||
|
||||
:param application: web application instance
|
||||
"""
|
||||
application.router.add_get("/", IndexView)
|
||||
@ -58,3 +61,5 @@ def setup_routes(application: Application) -> None:
|
||||
application.router.add_delete("/api/v1/packages/{package}", PackageView)
|
||||
application.router.add_get("/api/v1/packages/{package}", PackageView)
|
||||
application.router.add_post("/api/v1/packages/{package}", PackageView)
|
||||
|
||||
application.router.add_get("/api/v1/status", StatusView)
|
||||
|
@ -21,8 +21,7 @@ import aiohttp_jinja2
|
||||
|
||||
from typing import Any, Dict
|
||||
|
||||
import ahriman.version as version
|
||||
|
||||
from ahriman import version
|
||||
from ahriman.core.util import pretty_datetime
|
||||
from ahriman.web.views.base import BaseView
|
||||
|
||||
@ -36,6 +35,7 @@ class IndexView(BaseView):
|
||||
architecture - repository architecture, string, required
|
||||
packages - sorted list of packages properties, required
|
||||
* base, string
|
||||
* depends, sorted list of strings
|
||||
* groups, sorted list of strings
|
||||
* licenses, sorted list of strings
|
||||
* packages, sorted list of strings
|
||||
@ -61,6 +61,7 @@ class IndexView(BaseView):
|
||||
packages = [
|
||||
{
|
||||
"base": package.base,
|
||||
"depends": package.depends,
|
||||
"groups": package.groups,
|
||||
"licenses": package.licenses,
|
||||
"packages": list(sorted(package.packages)),
|
||||
|
45
src/ahriman/web/views/status.py
Normal file
45
src/ahriman/web/views/status.py
Normal file
@ -0,0 +1,45 @@
|
||||
#
|
||||
# Copyright (c) 2021 ahriman team.
|
||||
#
|
||||
# This file is part of ahriman
|
||||
# (see https://github.com/arcan1s/ahriman).
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
from aiohttp.web import Response, json_response
|
||||
|
||||
from ahriman import version
|
||||
from ahriman.models.counters import Counters
|
||||
from ahriman.models.internal_status import InternalStatus
|
||||
from ahriman.web.views.base import BaseView
|
||||
|
||||
|
||||
class StatusView(BaseView):
|
||||
"""
|
||||
web service status web view
|
||||
"""
|
||||
|
||||
async def get(self) -> Response:
|
||||
"""
|
||||
get current service status
|
||||
:return: 200 with service status object
|
||||
"""
|
||||
counters = Counters.from_packages(self.service.packages)
|
||||
status = InternalStatus(
|
||||
architecture=self.service.architecture,
|
||||
packages=counters,
|
||||
repository=self.service.repository.name,
|
||||
version=version.__version__)
|
||||
|
||||
return json_response(status.view())
|
@ -58,19 +58,19 @@ def run_server(application: web.Application) -> None:
|
||||
"""
|
||||
application.logger.info("start server")
|
||||
|
||||
section = application["config"].get_section_name("web", application["architecture"])
|
||||
host = application["config"].get(section, "host")
|
||||
port = application["config"].getint(section, "port")
|
||||
configuration: Configuration = application["configuration"]
|
||||
host = configuration.get("web", "host")
|
||||
port = configuration.getint("web", "port")
|
||||
|
||||
web.run_app(application, host=host, port=port, handle_signals=False,
|
||||
access_log=logging.getLogger("http"))
|
||||
|
||||
|
||||
def setup_service(architecture: str, config: Configuration) -> web.Application:
|
||||
def setup_service(architecture: str, configuration: Configuration) -> web.Application:
|
||||
"""
|
||||
create web application
|
||||
:param architecture: repository architecture
|
||||
:param config: configuration instance
|
||||
:param configuration: configuration instance
|
||||
:return: web application instance
|
||||
"""
|
||||
application = web.Application(logger=logging.getLogger("http"))
|
||||
@ -84,13 +84,12 @@ def setup_service(architecture: str, config: Configuration) -> web.Application:
|
||||
setup_routes(application)
|
||||
|
||||
application.logger.info("setup templates")
|
||||
aiohttp_jinja2.setup(application, loader=jinja2.FileSystemLoader(config.getpath("web", "templates")))
|
||||
aiohttp_jinja2.setup(application, loader=jinja2.FileSystemLoader(configuration.getpath("web", "templates")))
|
||||
|
||||
application.logger.info("setup configuration")
|
||||
application["config"] = config
|
||||
application["architecture"] = architecture
|
||||
application["configuration"] = configuration
|
||||
|
||||
application.logger.info("setup watcher")
|
||||
application["watcher"] = Watcher(architecture, config)
|
||||
application["watcher"] = Watcher(architecture, configuration)
|
||||
|
||||
return application
|
||||
|
@ -1,4 +1,5 @@
|
||||
import argparse
|
||||
import aur
|
||||
import pytest
|
||||
|
||||
from pytest_mock import MockerFixture
|
||||
@ -7,24 +8,70 @@ from ahriman.application.ahriman import _parser
|
||||
from ahriman.application.application import Application
|
||||
from ahriman.application.lock import Lock
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def application(configuration: Configuration, mocker: MockerFixture) -> Application:
|
||||
"""
|
||||
fixture for application
|
||||
:param configuration: configuration fixture
|
||||
:param mocker: mocker object
|
||||
:return: application test instance
|
||||
"""
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
return Application("x86_64", configuration)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def args() -> argparse.Namespace:
|
||||
"""
|
||||
fixture for command line arguments
|
||||
:return: command line arguments test instance
|
||||
"""
|
||||
return argparse.Namespace(lock=None, force=False, unsafe=False, no_report=True)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def aur_package_ahriman(package_ahriman: Package) -> aur.Package:
|
||||
"""
|
||||
fixture for AUR package
|
||||
:param package_ahriman: package fixture
|
||||
:return: AUR package test instance
|
||||
"""
|
||||
return aur.Package(
|
||||
num_votes=None,
|
||||
description=package_ahriman.packages[package_ahriman.base].description,
|
||||
url_path=package_ahriman.web_url,
|
||||
last_modified=None,
|
||||
name=package_ahriman.base,
|
||||
out_of_date=None,
|
||||
id=None,
|
||||
first_submitted=None,
|
||||
maintainer=None,
|
||||
version=package_ahriman.version,
|
||||
license=package_ahriman.packages[package_ahriman.base].licenses,
|
||||
url=None,
|
||||
package_base=package_ahriman.base,
|
||||
package_base_id=None,
|
||||
category_id=None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def lock(args: argparse.Namespace, configuration: Configuration) -> Lock:
|
||||
"""
|
||||
fixture for file lock
|
||||
:param args: command line arguments fixture
|
||||
:param configuration: configuration fixture
|
||||
:return: file lock test instance
|
||||
"""
|
||||
return Lock(args, "x86_64", configuration)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def parser() -> argparse.ArgumentParser:
|
||||
"""
|
||||
fixture for command line arguments parser
|
||||
:return: command line arguments parser test instance
|
||||
"""
|
||||
return _parser()
|
||||
|
@ -1,27 +1,97 @@
|
||||
import argparse
|
||||
import pytest
|
||||
|
||||
from pathlib import Path
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import Handler
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.core.exceptions import MissingArchitecture
|
||||
|
||||
|
||||
def test_call(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
def test_call(args: argparse.Namespace, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must call inside lock
|
||||
"""
|
||||
args.configuration = Path("")
|
||||
args.no_log = False
|
||||
mocker.patch("ahriman.application.handlers.Handler.run")
|
||||
mocker.patch("ahriman.core.configuration.Configuration.from_path")
|
||||
enter_mock = mocker.patch("ahriman.application.lock.Lock.__enter__")
|
||||
exit_mock = mocker.patch("ahriman.application.lock.Lock.__exit__")
|
||||
|
||||
assert Handler._call(args, "x86_64", configuration)
|
||||
assert Handler._call(args, "x86_64")
|
||||
enter_mock.assert_called_once()
|
||||
exit_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_call_exception(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
def test_call_exception(args: argparse.Namespace, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must process exception
|
||||
"""
|
||||
mocker.patch("ahriman.application.lock.Lock.__enter__", side_effect=Exception())
|
||||
assert not Handler._call(args, "x86_64", configuration)
|
||||
assert not Handler._call(args, "x86_64")
|
||||
|
||||
|
||||
def test_execute(args: argparse.Namespace, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run execution in multiple processes
|
||||
"""
|
||||
args.architecture = ["i686", "x86_64"]
|
||||
starmap_mock = mocker.patch("multiprocessing.pool.Pool.starmap")
|
||||
|
||||
Handler.execute(args)
|
||||
starmap_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_extract_architectures(args: argparse.Namespace, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must generate list of available architectures
|
||||
"""
|
||||
args.architecture = []
|
||||
args.configuration = Path("")
|
||||
mocker.patch("ahriman.core.configuration.Configuration.getpath")
|
||||
known_architectures_mock = mocker.patch("ahriman.models.repository_paths.RepositoryPaths.known_architectures")
|
||||
|
||||
Handler.extract_architectures(args)
|
||||
known_architectures_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_extract_architectures_empty(args: argparse.Namespace, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must raise exception if no available architectures found
|
||||
"""
|
||||
args.architecture = []
|
||||
args.command = "config"
|
||||
args.configuration = Path("")
|
||||
mocker.patch("ahriman.core.configuration.Configuration.getpath")
|
||||
mocker.patch("ahriman.models.repository_paths.RepositoryPaths.known_architectures", return_value=set())
|
||||
|
||||
with pytest.raises(MissingArchitecture):
|
||||
Handler.extract_architectures(args)
|
||||
|
||||
|
||||
def test_extract_architectures_exception(args: argparse.Namespace) -> None:
|
||||
"""
|
||||
must raise exception on missing architectures
|
||||
"""
|
||||
args.command = "config"
|
||||
args.architecture = None
|
||||
with pytest.raises(MissingArchitecture):
|
||||
Handler.extract_architectures(args)
|
||||
|
||||
|
||||
def test_extract_architectures_specified(args: argparse.Namespace) -> None:
|
||||
"""
|
||||
must return architecture list if it has been specified
|
||||
"""
|
||||
architectures = args.architecture = ["i686", "x86_64"]
|
||||
assert Handler.extract_architectures(args) == set(architectures)
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration) -> None:
|
||||
"""
|
||||
must raise NotImplemented for missing method
|
||||
"""
|
||||
with pytest.raises(NotImplementedError):
|
||||
Handler.run(args, "x86_64", configuration)
|
||||
|
@ -7,7 +7,13 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.package = []
|
||||
args.now = False
|
||||
args.without_dependencies = False
|
||||
return args
|
||||
|
||||
@ -22,3 +28,19 @@ def test_run(args: argparse.Namespace, configuration: Configuration, mocker: Moc
|
||||
|
||||
Add.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_run_with_updates(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command with updates after
|
||||
"""
|
||||
args = _default_args(args)
|
||||
args.now = True
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
mocker.patch("ahriman.application.application.Application.add")
|
||||
application_mock = mocker.patch("ahriman.application.application.Application.update")
|
||||
updates_mock = mocker.patch("ahriman.application.application.Application.get_updates")
|
||||
|
||||
Add.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_once()
|
||||
updates_mock.assert_called_once()
|
||||
|
@ -7,6 +7,11 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.no_build = False
|
||||
args.no_cache = False
|
||||
args.no_chroot = False
|
||||
|
@ -11,7 +11,10 @@ def test_run(args: argparse.Namespace, configuration: Configuration, mocker: Moc
|
||||
must run command
|
||||
"""
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
application_mock = mocker.patch("ahriman.core.configuration.Configuration.dump")
|
||||
print_mock = mocker.patch("ahriman.application.handlers.dump.Dump._print")
|
||||
application_mock = mocker.patch("ahriman.core.configuration.Configuration.dump",
|
||||
return_value=configuration.dump())
|
||||
|
||||
Dump.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_once()
|
||||
print_mock.assert_called()
|
||||
|
18
tests/ahriman/application/handlers/test_handler_init.py
Normal file
18
tests/ahriman/application/handlers/test_handler_init.py
Normal file
@ -0,0 +1,18 @@
|
||||
import argparse
|
||||
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import Init
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command
|
||||
"""
|
||||
create_tree_mock = mocker.patch("ahriman.models.repository_paths.RepositoryPaths.create_tree")
|
||||
init_mock = mocker.patch("ahriman.core.alpm.repo.Repo.init")
|
||||
|
||||
Init.run(args, "x86_64", configuration)
|
||||
create_tree_mock.assert_called_once()
|
||||
init_mock.assert_called_once()
|
@ -0,0 +1,29 @@
|
||||
import argparse
|
||||
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import KeyImport
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.key = "0xE989490C"
|
||||
args.key_server = "keys.gnupg.net"
|
||||
return args
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command
|
||||
"""
|
||||
args = _default_args(args)
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
application_mock = mocker.patch("ahriman.core.sign.gpg.GPG.import_key")
|
||||
|
||||
KeyImport.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_once()
|
@ -4,12 +4,24 @@ from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import Rebuild
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.depends_on = []
|
||||
return args
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command
|
||||
"""
|
||||
args = _default_args(args)
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
application_packages_mock = mocker.patch("ahriman.core.repository.repository.Repository.packages")
|
||||
application_mock = mocker.patch("ahriman.application.application.Application.update")
|
||||
@ -17,3 +29,36 @@ def test_run(args: argparse.Namespace, configuration: Configuration, mocker: Moc
|
||||
Rebuild.run(args, "x86_64", configuration)
|
||||
application_packages_mock.assert_called_once()
|
||||
application_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_run_filter(args: argparse.Namespace, configuration: Configuration,
|
||||
package_ahriman: Package, package_python_schedule: Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command with depends filter
|
||||
"""
|
||||
args = _default_args(args)
|
||||
args.depends_on = ["python-aur"]
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
mocker.patch("ahriman.core.repository.repository.Repository.packages",
|
||||
return_value=[package_ahriman, package_python_schedule])
|
||||
application_mock = mocker.patch("ahriman.application.application.Application.update")
|
||||
|
||||
Rebuild.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_with([package_ahriman])
|
||||
|
||||
|
||||
def test_run_without_filter(args: argparse.Namespace, configuration: Configuration,
|
||||
package_ahriman: Package, package_python_schedule: Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command for all packages if no filter supplied
|
||||
"""
|
||||
args = _default_args(args)
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
mocker.patch("ahriman.core.repository.repository.Repository.packages",
|
||||
return_value=[package_ahriman, package_python_schedule])
|
||||
application_mock = mocker.patch("ahriman.application.application.Application.update")
|
||||
|
||||
Rebuild.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_with([package_ahriman, package_python_schedule])
|
||||
|
@ -7,6 +7,11 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.package = []
|
||||
return args
|
||||
|
||||
|
@ -7,6 +7,11 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.target = []
|
||||
return args
|
||||
|
||||
|
55
tests/ahriman/application/handlers/test_handler_search.py
Normal file
55
tests/ahriman/application/handlers/test_handler_search.py
Normal file
@ -0,0 +1,55 @@
|
||||
import argparse
|
||||
import aur
|
||||
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import Search
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.search = ["ahriman"]
|
||||
return args
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration, aur_package_ahriman: aur.Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command
|
||||
"""
|
||||
args = _default_args(args)
|
||||
mocker.patch("aur.search", return_value=[aur_package_ahriman])
|
||||
log_mock = mocker.patch("ahriman.application.handlers.search.Search.log_fn")
|
||||
|
||||
Search.run(args, "x86_64", configuration)
|
||||
log_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_run_multiple_search(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command with multiple search arguments
|
||||
"""
|
||||
args = _default_args(args)
|
||||
args.search = ["ahriman", "is", "cool"]
|
||||
search_mock = mocker.patch("aur.search")
|
||||
|
||||
Search.run(args, "x86_64", configuration)
|
||||
search_mock.assert_called_with(" ".join(args.search))
|
||||
|
||||
|
||||
def test_log_fn(args: argparse.Namespace, configuration: Configuration, aur_package_ahriman: aur.Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
log function must call print built-in
|
||||
"""
|
||||
args = _default_args(args)
|
||||
mocker.patch("aur.search", return_value=[aur_package_ahriman])
|
||||
print_mock = mocker.patch("builtins.print")
|
||||
|
||||
Search.run(args, "x86_64", configuration)
|
||||
print_mock.assert_called() # we don't really care about call details tbh
|
@ -7,14 +7,23 @@ from unittest import mock
|
||||
from ahriman.application.handlers import Setup
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.models.repository_paths import RepositoryPaths
|
||||
from ahriman.models.sign_settings import SignSettings
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.build_command = "ahriman"
|
||||
args.from_config = "/usr/share/devtools/pacman-extra.conf"
|
||||
args.from_configuration = Path("/usr/share/devtools/pacman-extra.conf")
|
||||
args.no_multilib = False
|
||||
args.packager = "John Doe <john@doe.com>"
|
||||
args.repository = "aur-clone"
|
||||
args.sign_key = "key"
|
||||
args.sign_target = [SignSettings.Packages]
|
||||
args.web_port = 8080
|
||||
return args
|
||||
|
||||
|
||||
@ -58,14 +67,20 @@ def test_create_ahriman_configuration(args: argparse.Namespace, configuration: C
|
||||
write_mock = mocker.patch("configparser.RawConfigParser.write")
|
||||
|
||||
command = Setup.build_command(args.build_command, "x86_64")
|
||||
Setup.create_ahriman_configuration(args.build_command, "x86_64", args.repository, configuration.include)
|
||||
Setup.create_ahriman_configuration(args, "x86_64", args.repository, configuration.include)
|
||||
add_section_mock.assert_has_calls([
|
||||
mock.call("build"),
|
||||
mock.call(Configuration.section_name("build", "x86_64")),
|
||||
mock.call("repository"),
|
||||
mock.call(Configuration.section_name("sign", "x86_64")),
|
||||
mock.call(Configuration.section_name("web", "x86_64")),
|
||||
])
|
||||
set_mock.assert_has_calls([
|
||||
mock.call("build", "build_command", str(command)),
|
||||
mock.call(Configuration.section_name("build", "x86_64"), "build_command", str(command)),
|
||||
mock.call("repository", "name", args.repository),
|
||||
mock.call(Configuration.section_name("sign", "x86_64"), "target",
|
||||
" ".join([target.name.lower() for target in args.sign_target])),
|
||||
mock.call(Configuration.section_name("sign", "x86_64"), "key", args.sign_key),
|
||||
mock.call(Configuration.section_name("web", "x86_64"), "port", str(args.web_port)),
|
||||
])
|
||||
write_mock.assert_called_once()
|
||||
|
||||
@ -81,8 +96,8 @@ def test_create_devtools_configuration(args: argparse.Namespace, repository_path
|
||||
add_section_mock = mocker.patch("configparser.RawConfigParser.add_section")
|
||||
write_mock = mocker.patch("configparser.RawConfigParser.write")
|
||||
|
||||
Setup.create_devtools_configuration(args.build_command, "x86_64", Path(args.from_config), args.no_multilib,
|
||||
args.repository, repository_paths)
|
||||
Setup.create_devtools_configuration(args.build_command, "x86_64", args.from_configuration,
|
||||
args.no_multilib, args.repository, repository_paths)
|
||||
add_section_mock.assert_has_calls([
|
||||
mock.call("multilib"),
|
||||
mock.call(args.repository)
|
||||
@ -101,8 +116,8 @@ def test_create_devtools_configuration_no_multilib(args: argparse.Namespace, rep
|
||||
add_section_mock = mocker.patch("configparser.RawConfigParser.add_section")
|
||||
write_mock = mocker.patch("configparser.RawConfigParser.write")
|
||||
|
||||
Setup.create_devtools_configuration(args.build_command, "x86_64", Path(args.from_config), True,
|
||||
args.repository, repository_paths)
|
||||
Setup.create_devtools_configuration(args.build_command, "x86_64", args.from_configuration,
|
||||
True, args.repository, repository_paths)
|
||||
add_section_mock.assert_called_once()
|
||||
write_mock.assert_called_once()
|
||||
|
||||
|
@ -7,6 +7,11 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.package = []
|
||||
return args
|
||||
|
||||
|
@ -4,23 +4,47 @@ from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import Status
|
||||
from ahriman.core.configuration import Configuration
|
||||
from ahriman.models.build_status import BuildStatus
|
||||
from ahriman.models.package import Package
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.ahriman = True
|
||||
args.package = []
|
||||
return args
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration, mocker: MockerFixture) -> None:
|
||||
def test_run(args: argparse.Namespace, configuration: Configuration, package_ahriman: Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command
|
||||
"""
|
||||
args = _default_args(args)
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
application_mock = mocker.patch("ahriman.core.status.client.Client.get_self")
|
||||
packages_mock = mocker.patch("ahriman.core.status.client.Client.get")
|
||||
packages_mock = mocker.patch("ahriman.core.status.client.Client.get",
|
||||
return_value=[(package_ahriman, BuildStatus())])
|
||||
|
||||
Status.run(args, "x86_64", configuration)
|
||||
application_mock.assert_called_once()
|
||||
packages_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_run_with_package_filter(args: argparse.Namespace, configuration: Configuration, package_ahriman: Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must run command
|
||||
"""
|
||||
args = _default_args(args)
|
||||
args.package = [package_ahriman.base]
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
packages_mock = mocker.patch("ahriman.core.status.client.Client.get",
|
||||
return_value=[(package_ahriman, BuildStatus())])
|
||||
|
||||
Status.run(args, "x86_64", configuration)
|
||||
packages_mock.assert_called_once()
|
||||
|
@ -9,8 +9,14 @@ from ahriman.models.package import Package
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
args.status = BuildStatusEnum.Success.value
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.status = BuildStatusEnum.Success
|
||||
args.package = None
|
||||
args.remove = False
|
||||
return args
|
||||
|
||||
|
||||
@ -38,3 +44,18 @@ def test_run_packages(args: argparse.Namespace, configuration: Configuration, pa
|
||||
|
||||
StatusUpdate.run(args, "x86_64", configuration)
|
||||
update_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_run_remove(args: argparse.Namespace, configuration: Configuration, package_ahriman: Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must remove package from status page
|
||||
"""
|
||||
args = _default_args(args)
|
||||
args.package = [package_ahriman.base]
|
||||
args.remove = True
|
||||
mocker.patch("pathlib.Path.mkdir")
|
||||
update_mock = mocker.patch("ahriman.core.status.client.Client.remove")
|
||||
|
||||
StatusUpdate.run(args, "x86_64", configuration)
|
||||
update_mock.assert_called_once()
|
||||
|
@ -7,6 +7,11 @@ from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.target = []
|
||||
return args
|
||||
|
||||
|
@ -2,11 +2,17 @@ import argparse
|
||||
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.application import Application
|
||||
from ahriman.application.handlers import Update
|
||||
from ahriman.core.configuration import Configuration
|
||||
|
||||
|
||||
def _default_args(args: argparse.Namespace) -> argparse.Namespace:
|
||||
"""
|
||||
default arguments for these test cases
|
||||
:param args: command line arguments fixture
|
||||
:return: generated arguments for these test cases
|
||||
"""
|
||||
args.package = []
|
||||
args.dry_run = False
|
||||
args.no_aur = False
|
||||
@ -40,3 +46,12 @@ def test_run_dry_run(args: argparse.Namespace, configuration: Configuration, moc
|
||||
|
||||
Update.run(args, "x86_64", configuration)
|
||||
updates_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_log_fn(application: Application, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must print package updates
|
||||
"""
|
||||
logger_mock = mocker.patch("logging.Logger.info")
|
||||
Update.log_fn(application, False)("hello")
|
||||
logger_mock.assert_called_once()
|
||||
|
@ -1,5 +1,12 @@
|
||||
import argparse
|
||||
|
||||
from pathlib import Path
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from ahriman.application.handlers import Handler
|
||||
from ahriman.models.build_status import BuildStatusEnum
|
||||
from ahriman.models.sign_settings import SignSettings
|
||||
|
||||
|
||||
def test_parser(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
@ -8,6 +15,26 @@ def test_parser(parser: argparse.ArgumentParser) -> None:
|
||||
parser.parse_args(["-a", "x86_64", "config"])
|
||||
|
||||
|
||||
def test_parser_option_configuration(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
must convert configuration option to Path instance
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "config"])
|
||||
assert isinstance(args.configuration, Path)
|
||||
args = parser.parse_args(["-a", "x86_64", "-c", "ahriman.ini", "config"])
|
||||
assert isinstance(args.configuration, Path)
|
||||
|
||||
|
||||
def test_parser_option_lock(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
must convert lock option to Path instance
|
||||
"""
|
||||
args = parser.parse_args(["update"])
|
||||
assert isinstance(args.lock, Path)
|
||||
args = parser.parse_args(["-l", "ahriman.lock", "update"])
|
||||
assert isinstance(args.lock, Path)
|
||||
|
||||
|
||||
def test_multiple_architectures(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
must accept multiple architectures
|
||||
@ -16,11 +43,20 @@ def test_multiple_architectures(parser: argparse.ArgumentParser) -> None:
|
||||
assert len(args.architecture) == 2
|
||||
|
||||
|
||||
def test_subparsers_add(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
add command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["add", "ahriman"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_check(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
check command must imply no_aur, no_manual and dry_run
|
||||
check command must imply empty architecture list, no-aur, no-manual and dry-run
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "check"])
|
||||
args = parser.parse_args(["check"])
|
||||
assert args.architecture == []
|
||||
assert not args.no_aur
|
||||
assert args.no_manual
|
||||
assert args.dry_run
|
||||
@ -28,52 +64,169 @@ def test_subparsers_check(parser: argparse.ArgumentParser) -> None:
|
||||
|
||||
def test_subparsers_clean(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
clean command must imply unsafe
|
||||
clean command must imply empty architectures list, unsafe and no-log
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "clean"])
|
||||
args = parser.parse_args(["clean"])
|
||||
assert args.architecture == []
|
||||
assert args.no_log
|
||||
assert args.unsafe
|
||||
|
||||
|
||||
def test_subparsers_config(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
config command must imply lock, no_report and unsafe
|
||||
config command must imply lock, no-log, no-report and unsafe
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "config"])
|
||||
args = parser.parse_args(["config"])
|
||||
assert args.lock is None
|
||||
assert args.no_log
|
||||
assert args.no_report
|
||||
assert args.unsafe
|
||||
|
||||
|
||||
def test_subparsers_init(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
init command must imply no_report
|
||||
"""
|
||||
args = parser.parse_args(["init"])
|
||||
assert args.no_report
|
||||
|
||||
|
||||
def test_subparsers_key_import(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
key-import command must imply architecture list, lock and no-report
|
||||
"""
|
||||
args = parser.parse_args(["key-import", "key"])
|
||||
assert args.architecture == [""]
|
||||
assert args.lock is None
|
||||
assert args.no_report
|
||||
|
||||
|
||||
def test_subparsers_rebuild(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
rebuild command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["rebuild"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_remove(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
remove command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["remove", "ahriman"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_report(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
report command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["report"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_search(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
search command must imply architecture list, lock, no-log, no-report and unsafe
|
||||
"""
|
||||
args = parser.parse_args(["search", "ahriman"])
|
||||
assert args.architecture == [""]
|
||||
assert args.lock is None
|
||||
assert args.no_log
|
||||
assert args.no_report
|
||||
assert args.unsafe
|
||||
|
||||
|
||||
def test_subparsers_setup(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
setup command must imply lock, no_report and unsafe
|
||||
setup command must imply lock, no-log, no-report and unsafe
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "setup", "--packager", "John Doe <john@doe.com>"])
|
||||
args = parser.parse_args(["-a", "x86_64", "setup", "--packager", "John Doe <john@doe.com>",
|
||||
"--repository", "aur-clone"])
|
||||
assert args.lock is None
|
||||
assert args.no_log
|
||||
assert args.no_report
|
||||
assert args.unsafe
|
||||
|
||||
|
||||
def test_subparsers_setup_option_from_configuration(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
setup command must convert from-configuration option to path instance
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "setup", "--packager", "John Doe <john@doe.com>",
|
||||
"--repository", "aur-clone"])
|
||||
assert isinstance(args.from_configuration, Path)
|
||||
args = parser.parse_args(["-a", "x86_64", "setup", "--packager", "John Doe <john@doe.com>",
|
||||
"--repository", "aur-clone", "--from-configuration", "path"])
|
||||
assert isinstance(args.from_configuration, Path)
|
||||
|
||||
|
||||
def test_subparsers_setup_option_sign_target(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
setup command must convert sign-target option to signsettings instance
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "setup", "--packager", "John Doe <john@doe.com>",
|
||||
"--repository", "aur-clone", "--sign-target", "packages"])
|
||||
assert args.sign_target
|
||||
assert all(isinstance(target, SignSettings) for target in args.sign_target)
|
||||
|
||||
|
||||
def test_subparsers_sign(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
sign command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["sign"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_status(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
status command must imply lock, no_report and unsafe
|
||||
status command must imply lock, no-log, no-report and unsafe
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "status"])
|
||||
assert args.lock is None
|
||||
assert args.no_log
|
||||
assert args.no_report
|
||||
assert args.unsafe
|
||||
|
||||
|
||||
def test_subparsers_status_update(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
status-update command must imply lock, no_report and unsafe
|
||||
status-update command must imply lock, no-log, no-report and unsafe
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "status-update"])
|
||||
assert args.lock is None
|
||||
assert args.no_log
|
||||
assert args.no_report
|
||||
assert args.unsafe
|
||||
|
||||
|
||||
def test_subparsers_status_update_option_status(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
status-update command must convert status option to buildstatusenum instance
|
||||
"""
|
||||
args = parser.parse_args(["-a", "x86_64", "status-update"])
|
||||
assert isinstance(args.status, BuildStatusEnum)
|
||||
args = parser.parse_args(["-a", "x86_64", "status-update", "--status", "failed"])
|
||||
assert isinstance(args.status, BuildStatusEnum)
|
||||
|
||||
|
||||
def test_subparsers_sync(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
sync command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["sync"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_update(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
update command must imply empty architectures list
|
||||
"""
|
||||
args = parser.parse_args(["update"])
|
||||
assert args.architecture == []
|
||||
|
||||
|
||||
def test_subparsers_web(parser: argparse.ArgumentParser) -> None:
|
||||
"""
|
||||
web command must imply lock and no_report
|
||||
@ -81,3 +234,19 @@ def test_subparsers_web(parser: argparse.ArgumentParser) -> None:
|
||||
args = parser.parse_args(["-a", "x86_64", "web"])
|
||||
assert args.lock is None
|
||||
assert args.no_report
|
||||
|
||||
|
||||
def test_run(args: argparse.Namespace, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
application must be run
|
||||
"""
|
||||
args.architecture = "x86_64"
|
||||
args.handler = Handler
|
||||
|
||||
from ahriman.application import ahriman
|
||||
mocker.patch.object(ahriman, "__name__", "__main__")
|
||||
mocker.patch("argparse.ArgumentParser.parse_args", return_value=args)
|
||||
exit_mock = mocker.patch("sys.exit")
|
||||
|
||||
ahriman.run()
|
||||
exit_mock.assert_called_once()
|
||||
|
@ -15,16 +15,27 @@ def test_finalize(application: Application, mocker: MockerFixture) -> None:
|
||||
report_mock = mocker.patch("ahriman.application.application.Application.report")
|
||||
sync_mock = mocker.patch("ahriman.application.application.Application.sync")
|
||||
|
||||
application._finalize()
|
||||
application._finalize([])
|
||||
report_mock.assert_called_once()
|
||||
sync_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_get_updates_all(application: Application, mocker: MockerFixture) -> None:
|
||||
def test_known_packages(application: Application, package_ahriman: Package, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must return not empty list of known packages
|
||||
"""
|
||||
mocker.patch("ahriman.core.repository.repository.Repository.packages", return_value=[package_ahriman])
|
||||
packages = application._known_packages()
|
||||
assert len(packages) > 1
|
||||
assert package_ahriman.base in packages
|
||||
|
||||
|
||||
def test_get_updates_all(application: Application, package_ahriman: Package, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must get updates for all
|
||||
"""
|
||||
updates_aur_mock = mocker.patch("ahriman.core.repository.update_handler.UpdateHandler.updates_aur")
|
||||
updates_aur_mock = mocker.patch("ahriman.core.repository.update_handler.UpdateHandler.updates_aur",
|
||||
return_value=[package_ahriman])
|
||||
updates_manual_mock = mocker.patch("ahriman.core.repository.update_handler.UpdateHandler.updates_manual")
|
||||
|
||||
application.get_updates([], no_aur=False, no_manual=False, no_vcs=False, log_fn=print)
|
||||
@ -207,7 +218,7 @@ def test_report(application: Application, mocker: MockerFixture) -> None:
|
||||
must generate report
|
||||
"""
|
||||
executor_mock = mocker.patch("ahriman.core.repository.executor.Executor.process_report")
|
||||
application.report([])
|
||||
application.report([], [])
|
||||
executor_mock.assert_called_once()
|
||||
|
||||
|
||||
@ -233,6 +244,17 @@ def test_sign(application: Application, package_ahriman: Package, package_python
|
||||
finalize_mock.assert_called_once()
|
||||
|
||||
|
||||
def test_sign_skip(application: Application, package_ahriman: Package, mocker: MockerFixture) -> None:
|
||||
"""
|
||||
must skip sign packages with empty filename
|
||||
"""
|
||||
package_ahriman.packages[package_ahriman.base].filename = None
|
||||
mocker.patch("ahriman.core.repository.repository.Repository.packages", return_value=[package_ahriman])
|
||||
mocker.patch("ahriman.application.application.Application.update")
|
||||
|
||||
application.sign([])
|
||||
|
||||
|
||||
def test_sign_specific(application: Application, package_ahriman: Package, package_python_schedule: Package,
|
||||
mocker: MockerFixture) -> None:
|
||||
"""
|
||||
@ -257,7 +279,7 @@ def test_sync(application: Application, mocker: MockerFixture) -> None:
|
||||
must sync to remote
|
||||
"""
|
||||
executor_mock = mocker.patch("ahriman.core.repository.executor.Executor.process_sync")
|
||||
application.sync([])
|
||||
application.sync([], [])
|
||||
executor_mock.assert_called_once()
|
||||
|
||||
|
||||
@ -270,11 +292,12 @@ def test_update(application: Application, package_ahriman: Package, mocker: Mock
|
||||
|
||||
mocker.patch("ahriman.core.tree.Tree.load", return_value=tree)
|
||||
mocker.patch("ahriman.core.repository.repository.Repository.packages_built", return_value=[])
|
||||
mocker.patch("ahriman.models.package.Package.load", return_value=package_ahriman)
|
||||
build_mock = mocker.patch("ahriman.core.repository.executor.Executor.process_build", return_value=paths)
|
||||
update_mock = mocker.patch("ahriman.core.repository.executor.Executor.process_update")
|
||||
finalize_mock = mocker.patch("ahriman.application.application.Application._finalize")
|
||||
|
||||
application.update([package_ahriman])
|
||||
build_mock.assert_called_once()
|
||||
update_mock.assert_has_calls([mock.call([]), mock.call(paths)])
|
||||
finalize_mock.assert_has_calls([mock.call(), mock.call()])
|
||||
update_mock.assert_called_with(paths)
|
||||
finalize_mock.assert_called_with([package_ahriman])
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user