Skip to content

Commit

Permalink
first working version
Browse files Browse the repository at this point in the history
  • Loading branch information
romintomasetti committed Oct 7, 2024
1 parent a49dd46 commit 96c0699
Show file tree
Hide file tree
Showing 14 changed files with 516 additions and 2 deletions.
14 changes: 14 additions & 0 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"dockerFile": "dockerfile",
"context": "..",
"extensions" : [
"eamodio.gitlens",
"mhutchie.git-graph",
"ms-python.python",
"GitHub.vscode-pull-request-github",
],
"runArgs": [
"--privileged",
],
"onCreateCommand": "git config --global --add safe.directory $PWD"
}
12 changes: 12 additions & 0 deletions .devcontainer/dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM python:3.10

RUN --mount=target=/requirements,type=bind,source=requirements <<EOF

set -ex

apt update

apt --yes install git

pip install typeguard -r /requirements/requirements.python.test.txt
EOF
52 changes: 52 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
name: Test

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:

test:
runs-on: ubuntu-latest
container:
image: python:3.10
steps:
- uses: actions/checkout@v4

- name: Install dependencies.
run : |
python -m pip install typeguard -r requirements/requirements.python.test.txt
- name: Run tests.
run : |
python -m pytest tests -s --log-cli-level=info
install-as-package-and-test:
runs-on: [ubuntu-latest]
container:
image: python:${{ matrix.version }}
strategy:
matrix:
version: ['3.10', '3.12']
steps:
- name: Install as package.
run : |
pip install git+https://github.com/uliegecsm/system-helpers.git@${{ github.sha }}
- name: Test 'apt' helpers CLI directly.
run : |
apt-helpers install-packages --update --clean --upgrade --packages jq
jq --version
- name: Test 'update-alternatives' helpers CLI directly.
run : |
update-alternatives-helpers --help
- name: Check that we can import packages in Python.
run : |
python -c "from system_helpers.apt import install as u;print(u)"
python -c "from system_helpers.update_alternatives import alternatives as u;print(u)"
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 ULiege CSM

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,11 @@
# apt-helpers
This repository contains useful standalone helper scripts for `apt`.
# System helpers

This repository contains useful standalone helper scripts for `Linux` systems.

## `apt`

Useful for dealing with `apt` related tasks.

## `update-alternatives`

Useful for dealing with `update-alternatives` tasks.
2 changes: 2 additions & 0 deletions requirements/requirements.python.test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pytest
pytest_console_scripts
25 changes: 25 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from setuptools import setup

setup(
name = 'system-helpers',
version = '0.1',
license = 'MIT',
url = 'https://github.com/uliegecsm/system-helpers',
install_requires = [
'typeguard',
],
packages = [
'system_helpers.apt',
'system_helpers.update_alternatives',
],
package_dir = {
'system_helpers.apt' : 'system_helpers/apt',
'system_helpers.update_alternatives' : 'system_helpers/update_alternatives',
},
entry_points = {
'console_scripts': [
'apt-helpers = system_helpers.apt.script:main',
'update-alternatives-helpers = system_helpers.update_alternatives.script:main',
],
},
)
85 changes: 85 additions & 0 deletions system_helpers/apt/install.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import logging
import pathlib
import shutil
import subprocess
import typing

import typeguard

@typeguard.typechecked
def get_list_of_packages_from_requirements_file(*, file : pathlib.Path) -> typing.List[str]:
"""
Get list of packages from a requirements file.
Note that this function only supports skipping empty lines and comment lines, *i.e.*,
not all features from https://pip.pypa.io/en/stable/reference/requirements-file-format/
are supported.
"""
packages = []
with file.open(mode = "r") as file:
for line in file:
line = line.strip()
if line and not line.startswith('#'):
packages.extend(line.strip().split())
return packages

@typeguard.typechecked
def install_command(*, yes : bool = True, no_install_recommends : bool = True) -> typing.List[str]:
"""
Get the `apt` command to install packages.
"""
cmd = ['apt']

if yes:
cmd.append('--yes')

if no_install_recommends:
cmd.append('--no-install-recommends')

cmd.append('install')
return cmd

@typeguard.typechecked
def install_packages(*,
packages : typing.Optional[typing.List[str]] = None,
requirements : typing.Optional[typing.List[pathlib.Path]] = None,
update : bool = False,
upgrade : bool = False,
clean: bool = False,
) -> None:
"""
Install list of packages by using `apt`.
Optionally:
* update
* upgrade
* clean
"""
to_be_installed = []

if packages:
to_be_installed += packages

if requirements:
for file in requirements:
to_be_installed += get_list_of_packages_from_requirements_file(file = file)

if len(to_be_installed) == 0:
raise RuntimeError('There is no package to be installed.')

logging.info(f"Installing 'apt' packages {to_be_installed} (update={update}, upgrade={upgrade}, clean={clean})")

if update:
subprocess.check_call(['apt', 'update'])

if upgrade:
subprocess.check_call(['apt', '--yes', 'upgrade'])

args = install_command(yes = True, no_install_recommends = True)
args += to_be_installed

subprocess.check_call(args)

if clean:
subprocess.check_call(['apt', 'clean'])
shutil.rmtree(pathlib.Path("/var/lib/apt/lists"))
60 changes: 60 additions & 0 deletions system_helpers/apt/script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import argparse
import logging
import pathlib

import typeguard

from system_helpers.apt.install import install_packages

@typeguard.typechecked
def parse_args() -> argparse.Namespace:
"""
Parse CLI arguments.
"""
parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(required = True)

parser_ip = subparsers.add_parser('install-packages')

parser_ip.add_argument('--clean', action = 'store_true')
parser_ip.add_argument('--update', action = 'store_true')
parser_ip.add_argument('--upgrade', action = 'store_true')

parser_ip.add_argument(
'--packages',
help = "List of packages to install.",
nargs = '*',
required = False,
dest = 'packages',
)

parser_ip.add_argument(
'--requirement',
help = 'Requirement file à la pip.',
dest = 'requirements',
action = 'append',
type = pathlib.Path,
required = False,
)

parser_ip.set_defaults(func = install_packages)

return parser.parse_args()

@typeguard.typechecked
def main() -> None:

logging.basicConfig(level=logging.INFO)

args = parse_args()

kwargs = vars(args)

func = kwargs.pop('func')

func(**kwargs)

if __name__ == "__main__":

main()
25 changes: 25 additions & 0 deletions system_helpers/update_alternatives/alternatives.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import pathlib
import subprocess
import typing

import typeguard

@typeguard.typechecked
def update_alternatives(*,
for_each_of : typing.Dict[str, str],
prefix : pathlib.Path,
level : int,
display : bool,
) -> None:
"""
Update alternatives for a list of 'apps'.
"""
for link, command in for_each_of.items():
subprocess.check_call([
'update-alternatives',
'--install', prefix / link, link, prefix / command,
str(level),
])

if display:
subprocess.check_call(['update-alternatives', '--display', link])
17 changes: 17 additions & 0 deletions system_helpers/update_alternatives/argparse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import argparse

import typeguard

class ParseKwargs(argparse.Action):
"""
Parse dictionary-like key-value pairs.
References:
* https://sumit-ghosh.com/posts/parsing-dictionary-key-value-pairs-kwargs-argparse-python/
"""
@typeguard.typechecked
def __call__(self, parser : argparse.ArgumentParser, namespace : argparse.Namespace, values : list, *args, **kwargs):
setattr(namespace, self.dest, dict())
for value in values:
key, value = value.split('=', 2)
getattr(namespace, self.dest)[key] = value
56 changes: 56 additions & 0 deletions system_helpers/update_alternatives/script.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import argparse
import logging
import pathlib

import typeguard

from system_helpers.update_alternatives.alternatives import update_alternatives
from system_helpers.update_alternatives.argparse import ParseKwargs

@typeguard.typechecked
def parse_args() -> argparse.Namespace:
"""
Parse CLI arguments.
"""
parser = argparse.ArgumentParser()

parser.add_argument(
'--prefix',
help = "Directory where alternatives are created.",
required = False, type = pathlib.Path, default = pathlib.Path("/usr/bin"),
)

parser.add_argument(
'--for-each-of',
help = "List of link-command pairs.",
nargs ='*',
required = True,
action = ParseKwargs,
)

parser.add_argument(
'--level',
help = "Priority level.",
required = False, type = int, default = 10,
)

parser.add_argument(
'--display',
help = "Whether to display information.",
required = False, action = 'store_true', default = True,
)

return parser.parse_args()

@typeguard.typechecked
def main() -> None:

logging.basicConfig(level=logging.INFO)

args = parse_args()

update_alternatives(**vars(args))

if __name__ == "__main__":

main()
Loading

0 comments on commit 96c0699

Please sign in to comment.