bdbackup 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bdbackup/__init__.py +15 -0
- bdbackup/backends.py +56 -0
- bdbackup/cli.py +1045 -0
- bdbackup/config.py +114 -0
- bdbackup/dboperations.py +88 -0
- bdbackup/engines.py +167 -0
- bdbackup/filebackup.py +305 -0
- bdbackup/history.py +180 -0
- bdbackup/mysql/__init__.py +26 -0
- bdbackup/mysql/helpers.py +50 -0
- bdbackup/mysql/mysqldump.py +161 -0
- bdbackup/mysql/xtrabackup.py +471 -0
- bdbackup/recovery.py +80 -0
- bdbackup/retention.py +636 -0
- bdbackup/scheduling.py +196 -0
- bdbackup/templates/__init__.py +163 -0
- bdbackup/templates/_matching.py +159 -0
- bdbackup/templates/python_dev.py +54 -0
- bdbackup/utils.py +58 -0
- bdbackup/validation.py +400 -0
- bdbackup-0.6.1.dist-info/METADATA +752 -0
- bdbackup-0.6.1.dist-info/RECORD +25 -0
- bdbackup-0.6.1.dist-info/WHEEL +4 -0
- bdbackup-0.6.1.dist-info/entry_points.txt +2 -0
- bdbackup-0.6.1.dist-info/licenses/LICENSE +21 -0
bdbackup/scheduling.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Read-only crontab inspection and safely quoted job recommendations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import pwd
|
|
7
|
+
import re
|
|
8
|
+
import shlex
|
|
9
|
+
import shutil
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from bdbackup.config import Config, Job
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def validate_schedule(value: str) -> str:
|
|
20
|
+
"""Accept portable five-field numeric cron expressions."""
|
|
21
|
+
if not isinstance(value, str) or len(value.split()) != 5 or any(c in value for c in "\r\n"):
|
|
22
|
+
raise ValueError("schedule must contain five numeric cron fields (e.g. 0 2 * * *)")
|
|
23
|
+
for field, (low, high) in zip(
|
|
24
|
+
value.split(), [(0, 59), (0, 23), (1, 31), (1, 12), (0, 7)], strict=True
|
|
25
|
+
):
|
|
26
|
+
for part in field.split(","):
|
|
27
|
+
match = re.fullmatch(r"(\*|[0-9]+(?:-[0-9]+)?)(?:/([0-9]+))?", part)
|
|
28
|
+
if not match:
|
|
29
|
+
raise ValueError(f"Invalid cron field: {field!r}")
|
|
30
|
+
base, step = match.groups()
|
|
31
|
+
if step is not None and not 1 <= int(step) <= high - low + 1:
|
|
32
|
+
raise ValueError(f"Invalid cron step: {field!r}")
|
|
33
|
+
if base != "*":
|
|
34
|
+
bounds = list(map(int, base.split("-")))
|
|
35
|
+
if any(n < low or n > high for n in bounds) or bounds[0] > bounds[-1]:
|
|
36
|
+
raise ValueError(f"Cron field out of range: {field!r}")
|
|
37
|
+
return " ".join(value.split())
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def os_user() -> str:
|
|
41
|
+
return pwd.getpwuid(os.geteuid()).pw_name
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _command(config: Config, job: Job) -> str:
|
|
45
|
+
executable = shutil.which("bdbackup")
|
|
46
|
+
prefix = (
|
|
47
|
+
[str(Path(executable).absolute())]
|
|
48
|
+
if executable
|
|
49
|
+
else [
|
|
50
|
+
str(Path(sys.executable).absolute()),
|
|
51
|
+
"-m",
|
|
52
|
+
"bdbackup.cli",
|
|
53
|
+
]
|
|
54
|
+
)
|
|
55
|
+
args = [*prefix, "run", "--config", str(config.path), "--", job.name]
|
|
56
|
+
# Cron interprets percent signs before invoking the shell, even inside quotes.
|
|
57
|
+
command = f"cd {shlex.quote(str(Path.cwd()))} && {shlex.join(args)}"
|
|
58
|
+
if any(c in command for c in "\r\n\x00"):
|
|
59
|
+
raise ValueError("Cron paths and job names must not contain control characters")
|
|
60
|
+
return command.replace("%", r"\%")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _scheduled_jobs(crontab: str, config: Config) -> dict[str, list[str]]:
|
|
64
|
+
"""Recognize ordinary bdbackup run commands, including our own recommendations."""
|
|
65
|
+
found: dict[str, list[str]] = {}
|
|
66
|
+
for line in crontab.splitlines():
|
|
67
|
+
line = line.strip()
|
|
68
|
+
if not line or line.startswith("#"):
|
|
69
|
+
continue
|
|
70
|
+
fields = line.split(None, 1 if line.startswith("@") else 5)
|
|
71
|
+
if len(fields) not in (2, 6):
|
|
72
|
+
continue
|
|
73
|
+
schedule, command = " ".join(fields[:-1]), fields[-1]
|
|
74
|
+
if len(fields) == 2 and not fields[0].startswith("@"):
|
|
75
|
+
continue
|
|
76
|
+
try:
|
|
77
|
+
tokens = shlex.split(command.replace(r"\%", "%"), comments=True)
|
|
78
|
+
except ValueError:
|
|
79
|
+
continue
|
|
80
|
+
cwd = Path.home()
|
|
81
|
+
if len(tokens) >= 3 and tokens[0] == "cd" and tokens[2] == "&&":
|
|
82
|
+
cwd = Path(tokens[1]).expanduser()
|
|
83
|
+
tokens = tokens[3:]
|
|
84
|
+
# Only recognize an actual command, never an echo/comment containing its name.
|
|
85
|
+
if not tokens:
|
|
86
|
+
continue
|
|
87
|
+
if Path(tokens[0]).name == "bdbackup":
|
|
88
|
+
args = tokens[1:]
|
|
89
|
+
elif (
|
|
90
|
+
len(tokens) > 3
|
|
91
|
+
and Path(tokens[0]).name.startswith("python")
|
|
92
|
+
and tokens[1:3] == ["-m", "bdbackup.cli"]
|
|
93
|
+
):
|
|
94
|
+
args = tokens[3:]
|
|
95
|
+
else:
|
|
96
|
+
continue
|
|
97
|
+
if any(flag in args for flag in ("--validate", "--cron")):
|
|
98
|
+
continue
|
|
99
|
+
config_path = None
|
|
100
|
+
positional = []
|
|
101
|
+
all_jobs = False
|
|
102
|
+
index = 0
|
|
103
|
+
while index < len(args):
|
|
104
|
+
arg = args[index]
|
|
105
|
+
if arg in {"&&", ";", "||", "|", ">", ">>", "2>&1"}:
|
|
106
|
+
break
|
|
107
|
+
if arg in {"--config", "-c", "--logging"} and index + 1 < len(args):
|
|
108
|
+
if arg != "--logging":
|
|
109
|
+
config_path = args[index + 1]
|
|
110
|
+
index += 2
|
|
111
|
+
continue
|
|
112
|
+
if arg.startswith("--config="):
|
|
113
|
+
config_path = arg.split("=", 1)[1]
|
|
114
|
+
elif arg == "--all":
|
|
115
|
+
all_jobs = True
|
|
116
|
+
elif not arg.startswith("-"):
|
|
117
|
+
positional.append(arg)
|
|
118
|
+
elif arg == "--" and index + 1 < len(args):
|
|
119
|
+
positional.append(args[index + 1])
|
|
120
|
+
break
|
|
121
|
+
index += 1
|
|
122
|
+
if not config_path or not positional or positional[0] != "run":
|
|
123
|
+
continue
|
|
124
|
+
if (cwd / Path(config_path).expanduser()).resolve() != config.path:
|
|
125
|
+
continue
|
|
126
|
+
names = list(config.jobs) if all_jobs else positional[1:2]
|
|
127
|
+
for name in names:
|
|
128
|
+
if name in config.jobs:
|
|
129
|
+
found.setdefault(name, []).append(schedule)
|
|
130
|
+
return found
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def recommend_cron(config: Config, jobs: list[Job]) -> tuple[list[str], bool]:
|
|
134
|
+
lines = [f"Crontab for OS user {os_user()} (read-only; no entries installed)."]
|
|
135
|
+
content = ""
|
|
136
|
+
checked = True
|
|
137
|
+
binary = shutil.which("crontab")
|
|
138
|
+
if binary is None:
|
|
139
|
+
lines.append("[FAIL] crontab executable not found; existing schedules cannot be checked.")
|
|
140
|
+
checked = False
|
|
141
|
+
else:
|
|
142
|
+
try:
|
|
143
|
+
result = subprocess.run( # noqa: S603
|
|
144
|
+
[binary, "-l"],
|
|
145
|
+
capture_output=True,
|
|
146
|
+
text=True,
|
|
147
|
+
timeout=10,
|
|
148
|
+
env={**os.environ, "LC_ALL": "C"},
|
|
149
|
+
)
|
|
150
|
+
if result.returncode == 0:
|
|
151
|
+
content = result.stdout
|
|
152
|
+
elif result.returncode == 1 and "no crontab for" in result.stderr.lower():
|
|
153
|
+
lines.append("No crontab is installed for this user.")
|
|
154
|
+
else:
|
|
155
|
+
lines.append("[FAIL] Cannot read crontab; existing schedules are unknown.")
|
|
156
|
+
checked = False
|
|
157
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
158
|
+
lines.append("[FAIL] Cannot read crontab; existing schedules are unknown.")
|
|
159
|
+
checked = False
|
|
160
|
+
existing = _scheduled_jobs(content, config)
|
|
161
|
+
lines.append("Suggested user crontab entries (review times in the cron daemon's timezone):")
|
|
162
|
+
lines.append("SHELL=/bin/sh")
|
|
163
|
+
path = os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin")
|
|
164
|
+
if not any(c in path for c in "\n\r\x00\"'"):
|
|
165
|
+
lines.append(f'PATH="{path}"')
|
|
166
|
+
lines.append("# Defaults: backups daily from 02:00; retention daily from 04:00.")
|
|
167
|
+
counters = {False: 0, True: 0}
|
|
168
|
+
# Use all config jobs to keep defaults stable when checking only one job.
|
|
169
|
+
defaults = {}
|
|
170
|
+
for job in config.jobs.values():
|
|
171
|
+
retention = job.type == "retention"
|
|
172
|
+
minute = (240 if retention else 120) + counters[retention] * 15
|
|
173
|
+
counters[retention] += 1
|
|
174
|
+
defaults[job.name] = f"{minute % 60} {(minute // 60) % 24} * * *"
|
|
175
|
+
for job in jobs:
|
|
176
|
+
schedule = job.schedule or defaults[job.name]
|
|
177
|
+
label = repr(job.name)
|
|
178
|
+
if job.name in existing:
|
|
179
|
+
times = ", ".join(existing[job.name])
|
|
180
|
+
lines.append(f"# {label}: already scheduled at {times}; no duplicate suggested.")
|
|
181
|
+
if job.schedule and job.schedule not in existing[job.name]:
|
|
182
|
+
lines.append(f"# Configured schedule is {job.schedule}; review the existing entry.")
|
|
183
|
+
continue
|
|
184
|
+
if job.type == "retention" and not job.params.get("apply", False):
|
|
185
|
+
lines.append(f"# {label}: dry-run retention (apply = false); no files deleted.")
|
|
186
|
+
if job.type == "xtrabackup":
|
|
187
|
+
lines.append(f"# {label}: full backup; includes automatic XtraBackup pruning.")
|
|
188
|
+
try:
|
|
189
|
+
lines.append(f"{schedule} {_command(config, job)}")
|
|
190
|
+
except ValueError as exc:
|
|
191
|
+
lines.append(f"[FAIL] {exc}")
|
|
192
|
+
checked = False
|
|
193
|
+
lines.append(
|
|
194
|
+
"Allow for actual backup duration before retention; times do not enforce ordering."
|
|
195
|
+
)
|
|
196
|
+
return lines, checked
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Named, reusable exclusion templates for file backups.
|
|
2
|
+
|
|
3
|
+
A template is a named bundle of gitignore-style exclusion patterns (see
|
|
4
|
+
:mod:`bdbackup.templates._matching` for the supported syntax). Templates are
|
|
5
|
+
discovered from two locations and merged by name:
|
|
6
|
+
|
|
7
|
+
1. Built-in presets shipped as modules inside this package (e.g.
|
|
8
|
+
``python_dev.py``), so they work with ``uv tool install``.
|
|
9
|
+
2. User presets: any ``*.py`` file in ``<config dir>/templates/`` where the
|
|
10
|
+
config dir resolves via :func:`bdbackup.utils.config_dir`
|
|
11
|
+
(``$BDBACKUP_CONFIG_DIR`` -> ``$XDG_CONFIG_HOME/bdbackup`` ->
|
|
12
|
+
``~/.config/bdbackup``).
|
|
13
|
+
|
|
14
|
+
A preset module self-registers by defining either::
|
|
15
|
+
|
|
16
|
+
TEMPLATE = ExclusionTemplate(name="my-dev", patterns=(...), description="...")
|
|
17
|
+
|
|
18
|
+
or::
|
|
19
|
+
|
|
20
|
+
def register() -> ExclusionTemplate: ...
|
|
21
|
+
|
|
22
|
+
Adding a new preset (built-in or user) never requires editing existing code:
|
|
23
|
+
drop in a new module and it is picked up on the next run.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import importlib
|
|
29
|
+
import importlib.util
|
|
30
|
+
import logging
|
|
31
|
+
import pkgutil
|
|
32
|
+
from collections.abc import Iterable
|
|
33
|
+
from dataclasses import dataclass
|
|
34
|
+
|
|
35
|
+
from bdbackup.templates._matching import GitignoreMatcher, build_matcher
|
|
36
|
+
from bdbackup.utils import config_dir
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
"ExclusionTemplate",
|
|
40
|
+
"GitignoreMatcher",
|
|
41
|
+
"TemplateError",
|
|
42
|
+
"build_matcher",
|
|
43
|
+
"get_template",
|
|
44
|
+
"list_templates",
|
|
45
|
+
"register_template",
|
|
46
|
+
"resolve_patterns",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
logger = logging.getLogger("bdbackup.templates")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class ExclusionTemplate:
|
|
54
|
+
"""A named bundle of gitignore-style exclusion patterns."""
|
|
55
|
+
|
|
56
|
+
name: str
|
|
57
|
+
patterns: tuple[str, ...]
|
|
58
|
+
description: str = ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class TemplateError(Exception):
|
|
62
|
+
"""Raised when an exclusion template cannot be found or loaded."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_REGISTRY: dict[str, ExclusionTemplate] = {}
|
|
66
|
+
_LOADED = False
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def register_template(template: ExclusionTemplate) -> None:
|
|
70
|
+
"""Register *template*, replacing any existing template with the same name."""
|
|
71
|
+
_REGISTRY[template.name] = template
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _collect(module) -> None:
|
|
75
|
+
"""Register whatever a preset module exposes (TEMPLATE or register())."""
|
|
76
|
+
template = getattr(module, "TEMPLATE", None)
|
|
77
|
+
if isinstance(template, ExclusionTemplate):
|
|
78
|
+
register_template(template)
|
|
79
|
+
hook = getattr(module, "register", None)
|
|
80
|
+
if callable(hook):
|
|
81
|
+
produced = hook()
|
|
82
|
+
if isinstance(produced, ExclusionTemplate):
|
|
83
|
+
register_template(produced)
|
|
84
|
+
elif isinstance(produced, Iterable):
|
|
85
|
+
for item in produced:
|
|
86
|
+
if isinstance(item, ExclusionTemplate):
|
|
87
|
+
register_template(item)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _load_builtin() -> None:
|
|
91
|
+
"""Import every preset module shipped inside this package."""
|
|
92
|
+
for info in pkgutil.iter_modules(__path__):
|
|
93
|
+
if info.name.startswith("_"):
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
module = importlib.import_module(f"{__name__}.{info.name}")
|
|
97
|
+
_collect(module)
|
|
98
|
+
except Exception as exc: # pragma: no cover - defensive
|
|
99
|
+
logger.warning("Failed to load built-in template %r: %s", info.name, exc)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _load_user() -> None:
|
|
103
|
+
"""Import user preset modules from <config dir>/templates/*.py."""
|
|
104
|
+
user_dir = config_dir() / "templates"
|
|
105
|
+
if not user_dir.is_dir():
|
|
106
|
+
return
|
|
107
|
+
for file in sorted(user_dir.glob("*.py")):
|
|
108
|
+
if file.name.startswith("_"):
|
|
109
|
+
continue
|
|
110
|
+
try:
|
|
111
|
+
spec = importlib.util.spec_from_file_location(
|
|
112
|
+
f"bdbackup_user_template_{file.stem}", file
|
|
113
|
+
)
|
|
114
|
+
if spec is None or spec.loader is None: # pragma: no cover - defensive
|
|
115
|
+
continue
|
|
116
|
+
module = importlib.util.module_from_spec(spec)
|
|
117
|
+
spec.loader.exec_module(module)
|
|
118
|
+
_collect(module)
|
|
119
|
+
except Exception as exc:
|
|
120
|
+
logger.warning("Failed to load user template %s: %s", file, exc)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _ensure_loaded() -> None:
|
|
124
|
+
global _LOADED
|
|
125
|
+
if _LOADED:
|
|
126
|
+
return
|
|
127
|
+
_load_builtin()
|
|
128
|
+
_load_user()
|
|
129
|
+
_LOADED = True
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def list_templates() -> dict[str, ExclusionTemplate]:
|
|
133
|
+
"""Return all registered templates, keyed by name."""
|
|
134
|
+
_ensure_loaded()
|
|
135
|
+
return dict(_REGISTRY)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def get_template(name: str) -> ExclusionTemplate:
|
|
139
|
+
"""Return the template called *name* or raise :class:`TemplateError`."""
|
|
140
|
+
_ensure_loaded()
|
|
141
|
+
try:
|
|
142
|
+
return _REGISTRY[name]
|
|
143
|
+
except KeyError:
|
|
144
|
+
available = ", ".join(sorted(_REGISTRY)) or "<none>"
|
|
145
|
+
raise TemplateError(
|
|
146
|
+
f"Unknown exclusion template {name!r}. Available: {available}. "
|
|
147
|
+
f"User templates are loaded from {config_dir() / 'templates'}/*.py"
|
|
148
|
+
) from None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def resolve_patterns(names: Iterable[str]) -> list[str]:
|
|
152
|
+
"""Return the combined patterns of the named templates, in order."""
|
|
153
|
+
patterns: list[str] = []
|
|
154
|
+
for name in names:
|
|
155
|
+
patterns.extend(get_template(name).patterns)
|
|
156
|
+
return patterns
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _reset_for_tests() -> None:
|
|
160
|
+
"""Clear the registry and loaded flag (test isolation only)."""
|
|
161
|
+
global _LOADED
|
|
162
|
+
_REGISTRY.clear()
|
|
163
|
+
_LOADED = False
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Gitignore-style pattern matching for exclusion templates.
|
|
2
|
+
|
|
3
|
+
This is a deliberately small subset of gitignore semantics ("gitignore-lite"),
|
|
4
|
+
sufficient for backup exclusions without pulling in an external dependency:
|
|
5
|
+
|
|
6
|
+
- ``*.pyc`` basename glob, matches at any depth
|
|
7
|
+
- ``__pycache__/`` trailing slash: directories only, matches at any depth
|
|
8
|
+
- ``tests/containers/*`` contains a slash: matched against the path relative
|
|
9
|
+
to the candidate root(s)
|
|
10
|
+
- ``/build/`` leading slash: additionally anchored to the root
|
|
11
|
+
- ``!important.log`` negation: re-includes a previously excluded path
|
|
12
|
+
|
|
13
|
+
Directory rules apply to descendants. Later negation rules can re-include
|
|
14
|
+
individual descendants; traversal keeps excluded directories open when such
|
|
15
|
+
rules are present.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import fnmatch
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Iterable
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _translate(pattern: str) -> re.Pattern[str]:
|
|
27
|
+
"""Translate a gitignore-style glob to a regex.
|
|
28
|
+
|
|
29
|
+
Unlike :func:`fnmatch.translate`, ``*`` and ``?`` never match ``/``;
|
|
30
|
+
``**`` matches any number of characters including ``/``.
|
|
31
|
+
"""
|
|
32
|
+
regex = ""
|
|
33
|
+
i = 0
|
|
34
|
+
n = len(pattern)
|
|
35
|
+
while i < n:
|
|
36
|
+
char = pattern[i]
|
|
37
|
+
if char == "*":
|
|
38
|
+
if pattern[i : i + 2] == "**":
|
|
39
|
+
regex += ".*"
|
|
40
|
+
i += 2
|
|
41
|
+
else:
|
|
42
|
+
regex += "[^/]*"
|
|
43
|
+
i += 1
|
|
44
|
+
elif char == "?":
|
|
45
|
+
regex += "[^/]"
|
|
46
|
+
i += 1
|
|
47
|
+
elif char == "[":
|
|
48
|
+
j = i + 1
|
|
49
|
+
if j < n and pattern[j] == "!":
|
|
50
|
+
j += 1
|
|
51
|
+
if j < n and pattern[j] == "]":
|
|
52
|
+
j += 1
|
|
53
|
+
while j < n and pattern[j] != "]":
|
|
54
|
+
j += 1
|
|
55
|
+
if j >= n:
|
|
56
|
+
regex += re.escape("[")
|
|
57
|
+
i += 1
|
|
58
|
+
else:
|
|
59
|
+
stuff = pattern[i + 1 : j].replace("\\", "\\\\")
|
|
60
|
+
if stuff.startswith("!"):
|
|
61
|
+
stuff = "^" + stuff[1:]
|
|
62
|
+
regex += f"[{stuff}]"
|
|
63
|
+
i = j + 1
|
|
64
|
+
else:
|
|
65
|
+
regex += re.escape(char)
|
|
66
|
+
i += 1
|
|
67
|
+
return re.compile(f"(?s:{regex})\\Z")
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _Rule:
|
|
71
|
+
"""A single compiled gitignore-style pattern."""
|
|
72
|
+
|
|
73
|
+
__slots__ = ("pattern", "negated", "dir_only", "anchored", "regex")
|
|
74
|
+
|
|
75
|
+
def __init__(self, raw: str):
|
|
76
|
+
pattern = raw.strip()
|
|
77
|
+
self.negated = pattern.startswith("!")
|
|
78
|
+
if self.negated:
|
|
79
|
+
pattern = pattern[1:]
|
|
80
|
+
self.dir_only = pattern.endswith("/")
|
|
81
|
+
if self.dir_only:
|
|
82
|
+
pattern = pattern.rstrip("/")
|
|
83
|
+
self.anchored = pattern.startswith("/")
|
|
84
|
+
if self.anchored:
|
|
85
|
+
pattern = pattern.lstrip("/")
|
|
86
|
+
if not pattern:
|
|
87
|
+
raise ValueError(f"Empty exclusion pattern: {raw!r}")
|
|
88
|
+
self.pattern = pattern
|
|
89
|
+
self.regex = _translate(pattern)
|
|
90
|
+
|
|
91
|
+
def matches(self, path: Path, is_dir: bool, roots: Iterable[Path]) -> bool:
|
|
92
|
+
if self.dir_only and not is_dir:
|
|
93
|
+
return False
|
|
94
|
+
if "/" in self.pattern:
|
|
95
|
+
if self.anchored:
|
|
96
|
+
# Anchored: match the full path relative to a root only.
|
|
97
|
+
for root in roots:
|
|
98
|
+
try:
|
|
99
|
+
candidate = path.relative_to(root).as_posix()
|
|
100
|
+
except ValueError:
|
|
101
|
+
continue
|
|
102
|
+
if self.regex.match(candidate):
|
|
103
|
+
return True
|
|
104
|
+
return False
|
|
105
|
+
# Unanchored: the pattern may match at any depth, so try the
|
|
106
|
+
# root-relative path, the absolute path, and every trailing
|
|
107
|
+
# suffix of them.
|
|
108
|
+
candidates = []
|
|
109
|
+
for root in roots:
|
|
110
|
+
try:
|
|
111
|
+
candidates.append(path.relative_to(root).as_posix())
|
|
112
|
+
except ValueError:
|
|
113
|
+
continue
|
|
114
|
+
candidates.append(path.as_posix())
|
|
115
|
+
for candidate in candidates:
|
|
116
|
+
parts = candidate.split("/")
|
|
117
|
+
for start in range(len(parts)):
|
|
118
|
+
if self.regex.match("/".join(parts[start:])):
|
|
119
|
+
return True
|
|
120
|
+
return False
|
|
121
|
+
# Basename pattern: matches at any depth, unless anchored to a root.
|
|
122
|
+
if self.anchored:
|
|
123
|
+
for root in roots:
|
|
124
|
+
try:
|
|
125
|
+
candidate = path.relative_to(root).as_posix()
|
|
126
|
+
except ValueError:
|
|
127
|
+
continue
|
|
128
|
+
if fnmatch.fnmatchcase(candidate, self.pattern):
|
|
129
|
+
return True
|
|
130
|
+
return False
|
|
131
|
+
return fnmatch.fnmatchcase(path.name, self.pattern)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class GitignoreMatcher:
|
|
135
|
+
"""Ordered gitignore-style rules; the last matching rule wins."""
|
|
136
|
+
|
|
137
|
+
def __init__(self, patterns: Iterable[str]):
|
|
138
|
+
self.rules = [_Rule(p) for p in patterns if p and p.strip()]
|
|
139
|
+
self.has_negations = any(rule.negated for rule in self.rules)
|
|
140
|
+
|
|
141
|
+
def matches(self, path: Path, is_dir: bool, roots: Iterable[Path]) -> bool:
|
|
142
|
+
roots = tuple(roots)
|
|
143
|
+
ancestors = [
|
|
144
|
+
parent
|
|
145
|
+
for parent in path.parents
|
|
146
|
+
if any(parent == root or parent.is_relative_to(root) for root in roots)
|
|
147
|
+
]
|
|
148
|
+
excluded = False
|
|
149
|
+
for rule in self.rules:
|
|
150
|
+
if rule.matches(path, is_dir, roots) or any(
|
|
151
|
+
rule.matches(parent, True, roots) for parent in ancestors
|
|
152
|
+
):
|
|
153
|
+
excluded = not rule.negated
|
|
154
|
+
return excluded
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def build_matcher(patterns: Iterable[str]) -> GitignoreMatcher:
|
|
158
|
+
"""Compile gitignore-style *patterns* into a matcher."""
|
|
159
|
+
return GitignoreMatcher(patterns)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Built-in exclusion template for Python development artifacts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from bdbackup.templates import ExclusionTemplate
|
|
6
|
+
|
|
7
|
+
TEMPLATE = ExclusionTemplate(
|
|
8
|
+
name="python-dev",
|
|
9
|
+
description="Python development artifacts: caches, virtualenvs, lockfiles, build output",
|
|
10
|
+
patterns=(
|
|
11
|
+
# Bytecode and tool caches
|
|
12
|
+
"__pycache__/",
|
|
13
|
+
"__pycache__/**",
|
|
14
|
+
"*.py[cod]",
|
|
15
|
+
".mypy_cache/",
|
|
16
|
+
".mypy_cache/**",
|
|
17
|
+
".pytest_cache/",
|
|
18
|
+
".pytest_cache/**",
|
|
19
|
+
".ruff_cache/",
|
|
20
|
+
".ruff_cache/**",
|
|
21
|
+
".tox/",
|
|
22
|
+
".tox/**",
|
|
23
|
+
".nox/",
|
|
24
|
+
".nox/**",
|
|
25
|
+
".ipynb_checkpoints/",
|
|
26
|
+
".ipynb_checkpoints/**",
|
|
27
|
+
".hypothesis/",
|
|
28
|
+
".hypothesis/**",
|
|
29
|
+
# Virtual environments
|
|
30
|
+
".venv/",
|
|
31
|
+
".venv/**",
|
|
32
|
+
"venv/",
|
|
33
|
+
"venv/**",
|
|
34
|
+
# Lockfiles
|
|
35
|
+
"uv.lock",
|
|
36
|
+
"Pipfile.lock",
|
|
37
|
+
"poetry.lock",
|
|
38
|
+
"pdm.lock",
|
|
39
|
+
# Build and packaging output
|
|
40
|
+
"build/",
|
|
41
|
+
"build/**",
|
|
42
|
+
"dist/",
|
|
43
|
+
"dist/**",
|
|
44
|
+
"*.egg-info/",
|
|
45
|
+
"*.egg-info/**",
|
|
46
|
+
".eggs/",
|
|
47
|
+
".eggs/**",
|
|
48
|
+
# Coverage artifacts
|
|
49
|
+
".coverage",
|
|
50
|
+
".coverage.*",
|
|
51
|
+
"htmlcov/",
|
|
52
|
+
"htmlcov/**",
|
|
53
|
+
),
|
|
54
|
+
)
|
bdbackup/utils.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Shared utilities for bdbackup."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fcntl
|
|
6
|
+
import os
|
|
7
|
+
from collections.abc import Iterable
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from datetime import UTC
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@contextmanager
|
|
14
|
+
def process_lock(lock_path: str | Path):
|
|
15
|
+
"""Advisory process lock using fcntl (POSIX only).
|
|
16
|
+
|
|
17
|
+
Raises BlockingIOError if another process already holds the lock.
|
|
18
|
+
"""
|
|
19
|
+
lock_file = Path(lock_path)
|
|
20
|
+
lock_file.parent.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
fd = os.open(lock_file, os.O_RDWR | os.O_CREAT, 0o644)
|
|
22
|
+
try:
|
|
23
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
24
|
+
yield
|
|
25
|
+
finally:
|
|
26
|
+
try:
|
|
27
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
28
|
+
except OSError:
|
|
29
|
+
pass
|
|
30
|
+
os.close(fd)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def config_dir() -> Path:
|
|
34
|
+
"""Return the bdbackup user configuration directory.
|
|
35
|
+
|
|
36
|
+
Resolution order: $BDBACKUP_CONFIG_DIR, then $XDG_CONFIG_HOME/bdbackup,
|
|
37
|
+
then ~/.config/bdbackup. The directory is not created implicitly.
|
|
38
|
+
"""
|
|
39
|
+
env = os.environ.get("BDBACKUP_CONFIG_DIR")
|
|
40
|
+
if env:
|
|
41
|
+
return Path(env)
|
|
42
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
43
|
+
if xdg:
|
|
44
|
+
return Path(xdg) / "bdbackup"
|
|
45
|
+
return Path.home() / ".config" / "bdbackup"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def today_stamp() -> str:
|
|
49
|
+
"""Return a UTC YYYY-MM-DD-HHMMSS style timestamp."""
|
|
50
|
+
from datetime import datetime
|
|
51
|
+
|
|
52
|
+
return datetime.now(UTC).strftime("%Y-%m-%d-%H%M%S")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def redact_cmd(cmd: Iterable[str | Path], secrets: Iterable[str]) -> list[str]:
|
|
56
|
+
"""Return a copy of *cmd* with any secret value replaced by '***'."""
|
|
57
|
+
secret_set = {str(s) for s in secrets if s}
|
|
58
|
+
return ["***" if str(part) in secret_set else str(part) for part in cmd]
|