Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ RUN add-apt-repository ppa:deadsnakes/ppa \
ENV PIPX_HOME=/usr/local/py-utils \
PIPX_BIN_DIR=/usr/local/py-utils/bin
ENV PATH=${PATH}:${PIPX_BIN_DIR}
RUN pipx install black
RUN pipx install ruff
RUN pipx install isort
RUN pipx install mypy
RUN pipx install poetry
Expand Down
53 changes: 27 additions & 26 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,34 @@
}
},
// Set *default* container specific settings.json values on container create.
"settings": {
"python.defaultInterpreterPath": "/usr/local/bin/python",
"python.languageServer": "Pylance",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
// "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
// "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
// "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
// "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
"python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
"python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
"python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
"python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
"customizations": {
"vscode": {
"settings": {
"python.defaultInterpreterPath": "/usr/local/bin/python",
"python.languageServer": "Pylance",
"python.linting.enabled": true,
"python.linting.pylintEnabled": true,
"python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
"python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
"python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
"python.linting.pylintPath": "/usr/local/py-utils/bin/pylint",
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff"
}
},
"extensions": [
"ms-python.python",
"ms-python.vscode-pylance",
"charliermarsh.ruff",
"ms-python.isort",
"donjayamanne.githistory",
"eamodio.gitlens",
"davidanson.vscode-markdownlint",
"njpwerner.autodocstring",
"streetsidesoftware.code-spell-checker"
]
}
},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"ms-python.python",
"ms-python.vscode-pylance",
"ms-python.black-formatter",
"ms-python.isort",
"donjayamanne.githistory",
"eamodio.gitlens",
"davidanson.vscode-markdownlint",
"njpwerner.autodocstring",
"streetsidesoftware.code-spell-checker"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Use 'postCreateCommand' to run commands after the container is created.
Expand Down
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ install:
- poetry install

script:
- poetry run black . --check
- poetry run ruff format --check
- poetry run mypy runrestic --ignore-missing-imports --strict
- poetry run pytest
7 changes: 2 additions & 5 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@
],
"autoDocstring.docstringFormat": "numpy",
"python.linting.pylintArgs": [
"--max-line-length=88"
],
"python.formatting.provider": "black",
"python.formatting.blackArgs": [
"-l 88"
"--max-line-length=120"
],
"python.formatting.provider": "ruff",
}
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
![python version](https://img.shields.io/badge/python-3.7+-blue.svg)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Code style: ruff](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/psf/ruff)
![Travis (.com)](https://api.travis-ci.com/sinnwerkstatt/runrestic.svg?branch=main)
![PyPI](https://img.shields.io/pypi/v/runrestic)
[![Stackshare: runrestic](https://img.shields.io/badge/stackshare-runrestic-068DFE.svg)](https://stackshare.io/runrestic)
Expand Down Expand Up @@ -143,6 +143,7 @@ sudo chmod +x /etc/cron.d/runrestic
- Add and update docstrings
- Add and update type hints
- Minor code improvements and test coverage
- Replace `black` formatter with `ruff` and increase max line length
- v0.5.30
- Fix metric setting in restic runner for "check"
- Support Python 3.13
Expand Down Expand Up @@ -203,6 +204,12 @@ poetry install
poetry run pytest
```

### Format files

```bash
poetry run ruff format
```

### Using VScode devcontainer

The project contains a `.devcontainer` folder with the settings for VScode to [develop inside container](https://code.visualstudio.com/docs/remote/containers). The Python virtual environment
Expand Down
247 changes: 98 additions & 149 deletions poetry.lock

Large diffs are not rendered by default.

20 changes: 8 additions & 12 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ requests = ">2.27.1"

[tool.poetry.group.dev.dependencies]
ipdb = "*"
black = { version = "*", allow-prereleases = true }
ruff = { version = ">=0.11" }
mypy = "*"
pytest = "*"
pytest-cov = "*"
Expand All @@ -37,16 +37,13 @@ types-toml = "*"
[tool.poetry.scripts]
runrestic = 'runrestic.runrestic.runrestic:runrestic'

[tool.black]
line-length = 88
target-version = ['py310', 'py311', 'py312', 'py313']
include = '\.pyi?$'
exclude = '''
/(
\.eggs
| \.git
)/
'''
[tool.ruff]
target-version = "py310"
line-length = 120
fix = true

[tool.ruff.format]
preview = true

[tool.isort]
multi_line_output = 3
Expand All @@ -58,4 +55,3 @@ known_first_party = 'apps'
default_section = 'THIRDPARTY'
sections = 'FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER'
no_lines_before = 'LOCALFOLDER'

12 changes: 3 additions & 9 deletions runrestic/metrics/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,9 +302,7 @@ def prune_metrics(metrics: dict[str, Any], name: str) -> str:
retval = _restic_help_prune
for repo, mtrx in metrics.items():
if mtrx["rc"] != 0:
retval += (
f'restic_prune_rc{{config="{name}",repository="{repo}"}} {mtrx["rc"]}\n'
)
retval += f'restic_prune_rc{{config="{name}",repository="{repo}"}} {mtrx["rc"]}\n'
else:
try:
retval += _restic_prune.format(name=name, repository=repo, **mtrx)
Expand All @@ -327,9 +325,7 @@ def check_metrics(metrics: dict[str, Any], name: str) -> str:
retval = _restic_help_check
for repo, mtrx in metrics.items():
if mtrx["rc"] != 0:
retval += (
f'restic_check_rc{{config="{name}",repository="{repo}"}} {mtrx["rc"]}\n'
)
retval += f'restic_check_rc{{config="{name}",repository="{repo}"}} {mtrx["rc"]}\n'
else:
retval += _restic_check.format(name=name, repository=repo, **mtrx)
return retval
Expand All @@ -349,9 +345,7 @@ def stats_metrics(metrics: dict[str, Any], name: str) -> str:
retval = _restic_help_stats
for repo, mtrx in metrics.items():
if mtrx["rc"] != 0:
retval += (
f'restic_stats_rc{{config="{name}",repository="{repo}"}} {mtrx["rc"]}\n'
)
retval += f'restic_stats_rc{{config="{name}",repository="{repo}"}} {mtrx["rc"]}\n'
else:
retval += _restic_stats.format(name=name, repository=repo, **mtrx)
return retval
8 changes: 2 additions & 6 deletions runrestic/restic/installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,7 @@ def restic_check() -> bool:
"""
if which("restic"):
return True
carry_on = input(
"There seems to be no restic on your system. Should I install it now? [Y/n] "
)
carry_on = input("There seems to be no restic on your system. Should I install it now? [Y/n] ")
if carry_on in ["", "y", "Y"]:
download_restic()
return True
Expand All @@ -46,9 +44,7 @@ def download_restic() -> None:
If permissions are insufficient, the user is prompted to provide an alternative path.
"""
try:
response = requests.get(
"https://api.github.com/repos/restic/restic/releases/latest", timeout=10
)
response = requests.get("https://api.github.com/repos/restic/restic/releases/latest", timeout=10)
response.raise_for_status()
github_json = json.loads(response.content)
except requests.exceptions.Timeout:
Expand Down
81 changes: 19 additions & 62 deletions runrestic/restic/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@ class ResticRunner:
pw_replacement (str): Replacement string for sensitive information in logs.
"""

def __init__(
self, config: dict[str, Any], args: Namespace, restic_args: list[str]
) -> None:
def __init__(self, config: dict[str, Any], args: Namespace, restic_args: list[str]) -> None:
"""
Initialize the ResticRunner with configuration, arguments, and Restic-specific arguments.

Expand All @@ -58,11 +56,7 @@ def __init__(

self.metrics: dict[str, Any] = {"errors": 0}
self.log_metrics: Any = config.get("metrics") and not args.dry_run
self.pw_replacement: str = (
config.get("metrics", {})
.get("prometheus", {})
.get("password_replacement", "")
)
self.pw_replacement: str = config.get("metrics", {}).get("prometheus", {}).get("password_replacement", "")

initialize_environment(self.config["environment"])

Expand Down Expand Up @@ -111,14 +105,10 @@ def init(self) -> None:
"""
Initialize the Restic repository for each configured repository.
"""
commands = [
["restic", "-r", repo, "init", *self.restic_args] for repo in self.repos
]
commands = [["restic", "-r", repo, "init", *self.restic_args] for repo in self.repos]

direct_abort_reasons = ["config file already exists"]
cmd_runs = MultiCommand(
commands, self.config["execution"], direct_abort_reasons
).run()
cmd_runs = MultiCommand(commands, self.config["execution"], direct_abort_reasons).run()

for process_infos in cmd_runs:
if process_infos["output"][-1][0] > 0:
Expand Down Expand Up @@ -171,22 +161,16 @@ def backup(self) -> None:
"Fatal: unable to open config file",
"Fatal: wrong password",
]
cmd_runs = MultiCommand(
commands, self.config["execution"], direct_abort_reasons
).run()
cmd_runs = MultiCommand(commands, self.config["execution"], direct_abort_reasons).run()

for repo, process_infos in zip(self.repos, cmd_runs):
return_code = process_infos["output"][-1][0]
if return_code > 0:
logger.warning(process_infos)
metrics[redact_password(repo, self.pw_replacement)] = {
"rc": return_code
}
metrics[redact_password(repo, self.pw_replacement)] = {"rc": return_code}
self.metrics["errors"] += 1
else:
metrics[redact_password(repo, self.pw_replacement)] = parse_backup(
process_infos
)
metrics[redact_password(repo, self.pw_replacement)] = parse_backup(process_infos)

# backup post_hooks
if cfg.get("post_hooks"):
Expand All @@ -204,9 +188,7 @@ def unlock(self) -> None:
"Fatal: unable to open config file",
"Fatal: wrong password",
]
commands = [
["restic", "-r", repo, "unlock", *self.restic_args] for repo in self.repos
]
commands = [["restic", "-r", repo, "unlock", *self.restic_args] for repo in self.repos]

cmd_runs = MultiCommand(
commands,
Expand Down Expand Up @@ -238,10 +220,7 @@ def forget(self) -> None:
"Fatal: unable to open config file",
"Fatal: wrong password",
]
commands = [
["restic", "-r", repo, "forget", *self.restic_args, *extra_args]
for repo in self.repos
]
commands = [["restic", "-r", repo, "forget", *self.restic_args, *extra_args] for repo in self.repos]
cmd_runs = MultiCommand(
commands,
config=self.config["execution"],
Expand All @@ -252,14 +231,10 @@ def forget(self) -> None:
return_code = process_infos["output"][-1][0]
if return_code > 0:
logger.warning(process_infos["output"])
metrics[redact_password(repo, self.pw_replacement)] = {
"rc": return_code
}
metrics[redact_password(repo, self.pw_replacement)] = {"rc": return_code}
self.metrics["errors"] += 1
else:
metrics[redact_password(repo, self.pw_replacement)] = parse_forget(
process_infos
)
metrics[redact_password(repo, self.pw_replacement)] = parse_forget(process_infos)

def prune(self) -> None:
"""
Expand All @@ -271,9 +246,7 @@ def prune(self) -> None:
"Fatal: unable to open config file",
"Fatal: wrong password",
]
commands = [
["restic", "-r", repo, "prune", *self.restic_args] for repo in self.repos
]
commands = [["restic", "-r", repo, "prune", *self.restic_args] for repo in self.repos]
cmd_runs = MultiCommand(
commands,
config=self.config["execution"],
Expand All @@ -284,20 +257,14 @@ def prune(self) -> None:
return_code = process_infos["output"][-1][0]
if return_code > 0:
logger.warning(process_infos["output"])
metrics[redact_password(repo, self.pw_replacement)] = {
"rc": return_code
}
metrics[redact_password(repo, self.pw_replacement)] = {"rc": return_code}
self.metrics["errors"] += 1
else:
try:
metrics[redact_password(repo, self.pw_replacement)] = (
parse_new_prune(process_infos)
)
metrics[redact_password(repo, self.pw_replacement)] = parse_new_prune(process_infos)
except IndexError:
# assume we're dealing with restic <0.12.0
metrics[redact_password(repo, self.pw_replacement)] = parse_prune(
process_infos
)
metrics[redact_password(repo, self.pw_replacement)] = parse_prune(process_infos)

def check(self) -> None:
"""
Expand All @@ -318,10 +285,7 @@ def check(self) -> None:
"Fatal: unable to open config file",
"Fatal: wrong password",
]
commands = [
["restic", "-r", repo, "check", *self.restic_args, *extra_args]
for repo in self.repos
]
commands = [["restic", "-r", repo, "check", *self.restic_args, *extra_args] for repo in self.repos]
cmd_runs = MultiCommand(
commands,
config=self.config["execution"],
Expand Down Expand Up @@ -363,10 +327,7 @@ def stats(self) -> None:
# quiet and verbose arguments are mutually exclusive
verbose = re.compile(r"^--verbose")
quiet = [] if list(filter(verbose.match, self.restic_args)) else ["-q"]
commands = [
["restic", "-r", repo, "stats", "--json", *quiet, *self.restic_args]
for repo in self.repos
]
commands = [["restic", "-r", repo, "stats", "--json", *quiet, *self.restic_args] for repo in self.repos]
cmd_runs = MultiCommand(
commands,
config=self.config["execution"],
Expand All @@ -377,11 +338,7 @@ def stats(self) -> None:
return_code = process_infos["output"][-1][0]
if return_code > 0:
logger.warning(process_infos["output"])
metrics[redact_password(repo, self.pw_replacement)] = {
"rc": return_code
}
metrics[redact_password(repo, self.pw_replacement)] = {"rc": return_code}
self.metrics["errors"] += 1
else:
metrics[redact_password(repo, self.pw_replacement)] = parse_stats(
process_infos
)
metrics[redact_password(repo, self.pw_replacement)] = parse_stats(process_infos)
Loading