Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bfcb81e90b | ||
|
|
22757ece58 | ||
|
|
699c569cc2 | ||
|
|
4a4797e959 | ||
|
|
87cdb5cadb | ||
|
|
934482086f | ||
|
|
91b7bb133c | ||
|
|
e3c8acf954 | ||
|
|
7618ef7ffb | ||
|
|
d696f2aebb | ||
|
|
4461fe2359 | ||
|
|
33dcbe6c58 | ||
|
|
248204fe41 | ||
|
|
a29517e2fc | ||
|
|
b4db7c806b | ||
|
|
cc61aed10c | ||
|
|
fd613edad0 | ||
|
|
72a8fe2b59 | ||
|
|
a987180653 | ||
|
|
a48eaf8117 | ||
|
|
48ebb7f9ae | ||
|
|
96f063d877 | ||
|
|
79b56d770f | ||
|
|
7c54bf3823 | ||
|
|
52b4fef814 | ||
|
|
84c8425422 | ||
|
|
e9a65a9b88 | ||
|
|
95614b6eec | ||
|
|
3214b48ae8 | ||
|
|
f0894584d4 | ||
|
|
06583f7e1a | ||
|
|
fb9dcbd392 | ||
|
|
dc9bc2e5e4 | ||
|
|
fe48010fc9 | ||
|
|
ee1df4cb21 | ||
|
|
5dc9235992 | ||
|
|
7c59bbc90b | ||
|
|
32ce113608 | ||
|
|
6fd6051642 | ||
|
|
22933d7520 | ||
|
|
6839d21a77 | ||
|
|
6d6038b027 | ||
|
|
5746a9bc82 | ||
|
|
45c2480778 | ||
|
|
62fcfe5881 | ||
|
|
775234a433 | ||
|
|
ae95856a58 | ||
|
|
2631b78d4d | ||
|
|
04692be42d | ||
|
|
e7774a5e5a |
No files matched your search
@@ -0,0 +1,37 @@
|
||||
name: Run tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [master]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "3.14"]
|
||||
include:
|
||||
# macOS runners cost 10x Linux minutes - only test the oldest
|
||||
# and newest supported Python there to catch platform-specific
|
||||
# issues without running the full matrix twice.
|
||||
- os: macos-latest
|
||||
python-version: "3.8"
|
||||
- os: macos-latest
|
||||
python-version: "3.14"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- name: Install uv and set the Python version
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install the project
|
||||
run: uv sync --all-extras --dev
|
||||
|
||||
- name: Run tests
|
||||
run: uv run pytest tests
|
||||
+5
-1
@@ -25,6 +25,9 @@ wheels/
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Version file generated by setuptools_scm
|
||||
curateipsum/_version.py
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
@@ -72,8 +75,9 @@ target/
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# pyenv
|
||||
# uv
|
||||
.python-version
|
||||
uv.lock
|
||||
|
||||
# celery beat schedule file
|
||||
celerybeat-schedule
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working
|
||||
with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
cura-te-ipsum is a space-efficient incremental backup utility for Linux and
|
||||
macOS. It creates hardlink-based snapshots similar to Time Machine/rsnapshot,
|
||||
where unchanged files share inodes between backups to minimize storage.
|
||||
|
||||
## Development Commands
|
||||
|
||||
### Environment Setup
|
||||
Project uses `uv` for Python version and dependency management:
|
||||
```bash
|
||||
uv sync --all-extras --dev
|
||||
```
|
||||
|
||||
### Testing
|
||||
```bash
|
||||
uv run pytest # run all tests
|
||||
uv run pytest -v # verbose output
|
||||
uv run pytest tests/test_fs.py # run specific test file
|
||||
```
|
||||
|
||||
### Installation
|
||||
```bash
|
||||
uv pip install . # install from source
|
||||
```
|
||||
|
||||
### Running the Tool
|
||||
```bash
|
||||
cura-te-ipsum -b /path/to/backups /path/to/source
|
||||
cura-te-ipsum -b /backups /src1 /src2 --dry-run --verbose
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core Modules
|
||||
|
||||
**curateipsum/backup.py**: Main backup orchestration
|
||||
- `initiate_backup()`: Main entry point - coordinates hardlinking from
|
||||
previous backup and rsync from sources
|
||||
- `cleanup_old_backups()`: Implements grandfather-father-son retention
|
||||
(daily/weekly/monthly/yearly) with configurable thresholds
|
||||
- Lock management (`set_backups_lock`, `release_backups_lock`): Prevents
|
||||
concurrent backups using PID-based lock file
|
||||
- Backup markers (`set_backup_marker`, `_is_backup`): Tracks completed vs
|
||||
incomplete backups
|
||||
|
||||
**curateipsum/fs.py**: Low-level filesystem operations
|
||||
- `rsync()`: Pure Python rsync implementation - syncs source to destination
|
||||
with delete support
|
||||
- `rsync_ext()`: Wrapper for external rsync command
|
||||
- `hardlink_dir()`: Recursively hardlinks entire directory tree (Python or
|
||||
external cp)
|
||||
- `nest_hardlink()`: Hardlinks individual files to `.backup_delta` directory
|
||||
preserving structure
|
||||
- `scantree()`: Recursive directory iterator
|
||||
- `copy_direntry()`, `update_direntry()`, `rm_direntry()`: DirEntry
|
||||
manipulation utilities
|
||||
|
||||
**curateipsum/cli.py**: Command-line interface
|
||||
- Argument parsing and validation
|
||||
- Platform check (Linux/macOS only)
|
||||
- Logging setup and execution flow
|
||||
|
||||
### Key Data Structures
|
||||
|
||||
**PseudoDirEntry**: Emulates os.DirEntry for paths that don't exist yet or
|
||||
for consistency in handling both real and pseudo entries. Used extensively
|
||||
in backup operations.
|
||||
|
||||
**Actions enum**: Tracks filesystem changes during rsync (NOTHING, DELETE,
|
||||
REWRITE, UPDATE_TIME, UPDATE_PERM, UPDATE_OWNER, CREATE, ERROR).
|
||||
|
||||
### Backup Process Flow
|
||||
|
||||
1. Acquire lock file (`.backups_lock`) with PID
|
||||
2. Clean up old backups per retention policy
|
||||
3. Hardlink entire previous backup directory to new timestamped directory
|
||||
4. Remove backup markers from hardlinked copy
|
||||
5. Delete `.backup_delta` directory from hardlinked copy
|
||||
6. Rsync each source to new backup (overwrites changed files, breaking
|
||||
hardlinks)
|
||||
7. For each changed file, hardlink to `.backup_delta` directory
|
||||
8. Set backup marker (`.backup_finished_TIMESTAMP`)
|
||||
9. Release lock
|
||||
|
||||
### Important Implementation Details
|
||||
|
||||
**Retention policy**: `cleanup_old_backups()` implements threshold-based
|
||||
retention where each threshold is inclusive. For example, `keep_weekly=1`
|
||||
on Thursday keeps one backup from current week AND one from previous week.
|
||||
|
||||
**Delta tracking**: Changed files are hardlinked to `.backup_delta/` within
|
||||
each backup to track what changed in that specific backup snapshot.
|
||||
|
||||
**Hardlink breakage**: When rsync overwrites a hardlinked file, it breaks
|
||||
the hardlink, creating a new inode. This is how changed files get tracked
|
||||
while unchanged files continue sharing inodes.
|
||||
|
||||
**External tools**: Can use external rsync (--external-rsync) or GNU cp/gcp
|
||||
for hardlinking (--external-hardlink) instead of Python implementations.
|
||||
macOS requires `gcp` (GNU cp) for external hardlinking.
|
||||
|
||||
**Dry run behavior**: Creates backup directory and performs operations but
|
||||
removes directory at end without setting backup marker.
|
||||
|
||||
## Platform Specifics
|
||||
|
||||
- Linux: Uses standard `cp` command
|
||||
- macOS: Requires `gcp` (GNU coreutils) for external hardlinking
|
||||
- Only these platforms are supported (checked in cli.py)
|
||||
|
||||
## Testing
|
||||
|
||||
Tests use unittest.TestCase with mock.patch for datetime manipulation.
|
||||
Focus is on backup cleanup logic with various retention scenarios.
|
||||
Tests create temporary backup directories and verify correct backups are
|
||||
kept/removed.
|
||||
|
||||
## Version Management
|
||||
|
||||
Version is automatically derived from git tags using `setuptools_scm`.
|
||||
The version file `curateipsum/_version.py` is auto-generated during build
|
||||
and should not be committed to version control.
|
||||
|
||||
To create a new release, tag the commit:
|
||||
```bash
|
||||
git tag -a v0.0.4 -m "Release 0.0.4"
|
||||
git push origin v0.0.4
|
||||
```
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
# Improvement Plan
|
||||
|
||||
This project manipulates backup data, so correctness and recovery guarantees
|
||||
come before packaging or profile presentation. The current implementation has
|
||||
known cases where a failed or incomplete backup can be treated as successful
|
||||
and where an older snapshot can be modified indirectly.
|
||||
|
||||
Until the P0 items are complete, the README should describe the project as
|
||||
experimental and should not claim that it is safe for production backups.
|
||||
|
||||
## P0 - Data-safety requirements
|
||||
|
||||
### Make snapshot creation transactional
|
||||
|
||||
- [x] Build each snapshot in a unique `.incomplete-<id>` staging directory.
|
||||
- [x] Treat every copy error, parse error, unsupported entry, and nonzero
|
||||
subprocess exit as fatal.
|
||||
- [x] Return structured results or raise one documented backup exception.
|
||||
- [x] Write and `fsync` a manifest only after every source succeeds.
|
||||
- [x] Atomically rename the staging directory to its final snapshot name.
|
||||
- [x] Release the backup lock in `finally` and return a nonzero CLI exit code.
|
||||
- [x] Quarantine or clean abandoned staging directories safely on startup.
|
||||
- [x] Prevent same-second snapshot-name collisions.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Injected failures never leave a final snapshot or completion marker.
|
||||
- The previous completed snapshot remains unchanged.
|
||||
- A failed run exits nonzero, releases its lock, and can be retried.
|
||||
|
||||
### Replace PID-file process killing with a real lock
|
||||
|
||||
- [x] Use `fcntl.flock()` and hold the descriptor for the full operation.
|
||||
- [x] Keep PID and process-start metadata for diagnostics only.
|
||||
- [x] Remove process killing from `--force` behavior.
|
||||
- [x] Verify lock ownership before releasing or replacing metadata.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Multiprocess tests prove that only one backup or cleanup can run.
|
||||
- Stale metadata and PID reuse cannot terminate an unrelated process.
|
||||
- Kernel lock release works after normal exit, signals, and crashes.
|
||||
|
||||
### Preserve symlinks and old-snapshot immutability
|
||||
|
||||
- [x] Classify entries with `lstat()` and process symlinks before directories.
|
||||
- [x] Never follow symlinks while applying symlink metadata.
|
||||
- [x] Break shared hardlinks before changing mode, ownership, flags, or times.
|
||||
- [x] Define copy-on-write invariants for every mutation.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Relative, absolute, broken, file, and directory symlinks remain symlinks.
|
||||
- External symlink targets are never modified.
|
||||
- Content and metadata in every older snapshot remain unchanged.
|
||||
|
||||
### Validate topology and destructive path boundaries
|
||||
|
||||
- [x] Canonicalize source and backup paths and reject every overlap.
|
||||
- [x] Reject duplicate sources and destination basename collisions, or require
|
||||
explicit source labels.
|
||||
- [x] Require normalized relative paths for nested operations.
|
||||
- [x] Verify `commonpath` before every write, rename, or deletion.
|
||||
- [x] Give each backup repository an identity recorded in its manifest.
|
||||
- [x] Validate repository identity, snapshot type, marker, and device before
|
||||
recursive deletion.
|
||||
- [x] Refuse to cross mount points during deletion.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Tests reject output inside source, source inside output, aliases, absolute
|
||||
paths, parent traversal, duplicate basenames, and forged markers.
|
||||
- Bind mounts and nested mount points cannot cause external data deletion.
|
||||
|
||||
### Prevent stale, truncated, or changing-file copies
|
||||
|
||||
- [x] Handle partial writes correctly or use a proven copy primitive.
|
||||
- [x] Use nanosecond timestamps and a documented integrity strategy.
|
||||
- [x] Add checksum verification, either always or through an explicit mode.
|
||||
- [x] Stat files before and after copying and retry or fail if they changed.
|
||||
- [x] Record integrity information in the completion manifest.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Tests cover partial writes and files changed, replaced, truncated, or renamed
|
||||
during copying.
|
||||
- Same-size content changes with restored timestamps cannot be missed silently.
|
||||
- A completed snapshot passes manifest verification.
|
||||
|
||||
### Correct retention before enabling automatic deletion
|
||||
|
||||
- [x] Compute retained snapshots independently for each policy tier and keep
|
||||
the union of those sets.
|
||||
- [x] Compare ISO year and ISO week together.
|
||||
- [x] Generate and validate a retention plan before deleting anything.
|
||||
- [x] Run retention only after a new snapshot is durable and complete.
|
||||
- [x] Quarantine deletion candidates before recursive removal.
|
||||
- [x] Convert the existing retention `xfail` cases into passing tests.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Property tests prove that the latest snapshot and every tier guarantee are
|
||||
preserved.
|
||||
- Backup failure prevents every retention deletion.
|
||||
- Cross-year weekly retention behaves correctly.
|
||||
|
||||
### Handle special filesystem entries explicitly
|
||||
|
||||
- [x] Distinguish regular files, directories, symlinks, sockets, FIFOs, block
|
||||
devices, and character devices.
|
||||
- [x] Never open an unsupported entry as a regular file.
|
||||
- [x] Define a fail or recorded-exclusion policy for every unsupported type.
|
||||
- [x] Record exclusions in the snapshot manifest.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- A FIFO without a writer cannot block the backup.
|
||||
- Tests cover sockets and platform-available device types.
|
||||
- Unsupported entries produce a visible result and nonzero exit when required.
|
||||
|
||||
### Add an immediate safety warning
|
||||
|
||||
- [x] Remove the current production-use claim from `README.md`.
|
||||
- [x] State that the software is experimental until the P0 release gate passes.
|
||||
- [x] Warn users not to modify hardlinked snapshots in place.
|
||||
- [x] Document current recovery and metadata limitations honestly.
|
||||
|
||||
## P1 - Recovery and release readiness
|
||||
|
||||
### Provide a safe restoration workflow
|
||||
|
||||
- [x] Implement a restore command or a complete tested restore procedure.
|
||||
- [x] Support dry-run, partial restore, overwrite policy, and destination
|
||||
boundary checks.
|
||||
- [x] Preserve supported metadata and verify restored content against the
|
||||
manifest.
|
||||
- [x] Test restoration from current and older snapshots.
|
||||
|
||||
### Define filesystem compatibility
|
||||
|
||||
- [x] Document behavior for ACLs, xattrs, flags, sparse files, source hardlinks,
|
||||
ownership, permissions, and timestamps.
|
||||
- [x] Add an explicit one-filesystem policy.
|
||||
- [x] Make Python and external implementations provide equivalent guarantees or
|
||||
document every difference.
|
||||
- [x] Test supported behavior on Linux and macOS.
|
||||
|
||||
### Make dry-run genuinely non-mutating
|
||||
|
||||
- [x] Separate operation planning from execution.
|
||||
- [x] Ensure dry-run creates no files, hardlinks, locks, metadata updates, or
|
||||
temporary snapshots.
|
||||
- [x] Print proposed copy, exclusion, and deletion operations.
|
||||
- [x] Expose validated retention policy through CLI options or configuration.
|
||||
|
||||
### Strengthen tests and CI
|
||||
|
||||
- [x] Run CI on pull requests as well as pushes.
|
||||
- [x] Add macOS CI because macOS is an advertised platform.
|
||||
- [x] Fix the Unix-socket path test that currently fails on a local macOS run.
|
||||
- [x] Replace nonexistent issue references in `xfail` markers with real tracked
|
||||
work, then remove the markers as fixes land.
|
||||
- [ ] Add subprocess-based concurrency, signal, interruption, and fault tests.
|
||||
- [ ] Add filesystem-boundary and build/install smoke tests.
|
||||
- [x] Fix tests that change global state or assert against the wrong path.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- All known correctness defects have normal passing regression tests.
|
||||
- Linux and macOS CI pass without unexplained skips or xfails.
|
||||
|
||||
### Repair packaging and releases
|
||||
|
||||
- [ ] Make source archives build without a `.git` directory.
|
||||
- [ ] Test wheel and source distribution installation in clean environments.
|
||||
- [ ] Commit a reproducible development dependency lock or define another
|
||||
deterministic policy.
|
||||
- [ ] Correct OS classifiers and license metadata in `pyproject.toml`.
|
||||
- [ ] Decide whether PyPI publication is supported and document the decision.
|
||||
- [ ] Publish GitHub Releases with checksums and release notes.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Clean clone, source archive, sdist, and wheel builds all install successfully.
|
||||
- Each installation can report its version and complete a smoke backup.
|
||||
|
||||
### Correct operational documentation
|
||||
|
||||
- [ ] Fix the timestamp format, cleanup order, and marker names in `README.md`.
|
||||
- [ ] Replace the deleted `requirements-dev.txt` installation command.
|
||||
- [ ] Correct the documented Python matrix to 3.8 through 3.14.
|
||||
- [ ] Document failure semantics, restore steps, immutable snapshots, mount
|
||||
behavior, and implementation differences.
|
||||
- [ ] Generate or validate examples from integration tests.
|
||||
|
||||
## P2 - Maintainability and public presentation
|
||||
|
||||
### Separate safety-critical responsibilities
|
||||
|
||||
- [ ] Separate planning, copying, locking, retention, and snapshot commit logic.
|
||||
- [ ] Define typed operation plans and backend interfaces.
|
||||
- [ ] Share safety checks between Python and external implementations.
|
||||
- [ ] Add backend contract tests.
|
||||
|
||||
### Establish scalability expectations
|
||||
|
||||
- [ ] Avoid retaining every source directory entry in memory, or document the
|
||||
supported scale explicitly.
|
||||
- [ ] Benchmark runtime and peak memory on large and deeply nested trees.
|
||||
- [ ] Publish the benchmark method and expected operating envelope.
|
||||
|
||||
### Improve repository maintenance signals
|
||||
|
||||
- [ ] Create real issues for every known defect and remove stale annotations.
|
||||
- [ ] Protect the default branch and require pull-request CI.
|
||||
- [ ] Add a changelog before the next release.
|
||||
- [ ] Add concise security and contribution guidance.
|
||||
- [ ] Align the package author name with the professional profile identity.
|
||||
- [ ] Replace unclear CLI wording and validate that sources are directories.
|
||||
|
||||
### Improve the public project page
|
||||
|
||||
- [ ] Add a concise repository description and relevant topics.
|
||||
- [ ] Add a small architecture diagram showing planning, copy, commit, and
|
||||
retention phases.
|
||||
- [ ] Add a safety-guarantee and limitations table.
|
||||
- [ ] Add CI and release badges only after those signals are trustworthy.
|
||||
|
||||
## Release gate
|
||||
|
||||
Do not publish a stable release until all of the following are true:
|
||||
|
||||
- [ ] Failed or interrupted backups cannot be marked complete.
|
||||
- [ ] Previous snapshots are immutable in content and metadata.
|
||||
- [ ] Locking cannot race or signal unrelated processes.
|
||||
- [ ] Source, destination, mount, and deletion boundaries are enforced.
|
||||
- [ ] Retention cannot delete required snapshots or run after backup failure.
|
||||
- [ ] Unsupported files cannot block or disappear silently.
|
||||
- [ ] A documented restore has been tested end to end.
|
||||
- [ ] Linux and macOS CI cover failure and recovery paths.
|
||||
- [ ] Installable release artifacts work without repository metadata.
|
||||
- [ ] The README describes tested guarantees and remaining limitations.
|
||||
@@ -0,0 +1,278 @@
|
||||
# cura-te-ipsum
|
||||
|
||||
> **⚠️ Experimental — not yet safe for production use.** This project is
|
||||
> still working through its data-safety checklist (see
|
||||
> [IMPROVEMENTS.md](IMPROVEMENTS.md)). Do not rely on it as your only
|
||||
> backup, and see [Limitations](#limitations) before using it.
|
||||
|
||||
**cura-te-ipsum** is a space-efficient incremental backup utility for Linux and macOS that uses hardlinks to minimize storage usage while maintaining complete directory snapshots.
|
||||
|
||||
Similar to Time Machine or rsnapshot, cura-te-ipsum creates backups that appear as complete directory trees but intelligently share unchanged files between snapshots, dramatically reducing storage requirements.
|
||||
|
||||
## Features
|
||||
|
||||
- **Space-Efficient Incremental Backups**: Creates full directory snapshots using hardlinks, unchanged files share inodes with previous backups
|
||||
- **Intelligent Retention Policies**: Automatic cleanup with configurable grandfather-father-son rotation (daily/weekly/monthly/yearly)
|
||||
- **Pure Python Implementation**: No external dependencies required for basic operation (optional rsync support available)
|
||||
- **Delta Tracking**: Automatically identifies and tracks changed files between backups
|
||||
- **Backup Integrity**: Lock files and completion markers prevent concurrent runs and identify incomplete backups
|
||||
- **Safe Operations**: Dry-run mode to preview changes before execution
|
||||
- **Cross-Platform**: Supports both Linux and macOS
|
||||
|
||||
## Installation
|
||||
|
||||
### From Source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/snegov/cura-te-ipsum.git
|
||||
cd cura-te-ipsum
|
||||
pip install .
|
||||
```
|
||||
|
||||
### Requirements
|
||||
|
||||
- Python 3.8 or higher
|
||||
- Linux or macOS operating system
|
||||
- Optional: `rsync` and GNU `cp` for alternative implementation modes
|
||||
|
||||
## Usage
|
||||
|
||||
cura-te-ipsum has two subcommands, `backup` and `restore`. For backwards
|
||||
compatibility, `backup` is implied when the first argument isn't a
|
||||
recognized subcommand - so `cura-te-ipsum -b DIR SOURCE` and
|
||||
`cura-te-ipsum backup -b DIR SOURCE` are equivalent.
|
||||
|
||||
### Basic Backup
|
||||
|
||||
```bash
|
||||
cura-te-ipsum -b /path/to/backups /path/to/source
|
||||
```
|
||||
|
||||
This creates a timestamped backup in `/path/to/backups/YYYY-MM-DD_HH-MM-SS/`.
|
||||
|
||||
### Multiple Sources
|
||||
|
||||
```bash
|
||||
cura-te-ipsum -b /backups /home/user/documents /home/user/photos
|
||||
```
|
||||
|
||||
### Command-Line Options
|
||||
|
||||
```
|
||||
cura-te-ipsum -b BACKUPS_DIR SOURCE [SOURCE ...]
|
||||
|
||||
Required Arguments:
|
||||
-b BACKUPS_DIR Directory where backups will be stored
|
||||
SOURCE One or more directories to backup
|
||||
|
||||
Optional Arguments:
|
||||
-n, --dry-run Preview changes without creating backup
|
||||
-f, --force Force run even if previous backup is in progress
|
||||
-v, --verbose Enable debug logging
|
||||
--external-rsync Use external rsync instead of Python implementation
|
||||
--external-hardlink Use cp/gcp command for hardlinking
|
||||
--keep-all DAYS Keep every backup up to this many days in the past
|
||||
(default: 7)
|
||||
--keep-daily DAYS Keep one backup per day up to this many days in
|
||||
the past (default: 30)
|
||||
--keep-weekly WEEKS Keep one backup per week up to this many weeks in
|
||||
the past (default: 52)
|
||||
--keep-monthly MONTHS
|
||||
Keep one backup per month up to this many months
|
||||
in the past (default: 12)
|
||||
--keep-yearly YEARS Keep one backup per year up to this many years in
|
||||
the past (default: 5)
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
**Dry run to preview changes:**
|
||||
```bash
|
||||
cura-te-ipsum -b /backups /home/user/data --dry-run
|
||||
```
|
||||
|
||||
**Verbose output for debugging:**
|
||||
```bash
|
||||
cura-te-ipsum -b /backups /home/user/data --verbose
|
||||
```
|
||||
|
||||
**Using external rsync:**
|
||||
```bash
|
||||
cura-te-ipsum -b /backups /home/user/data --external-rsync
|
||||
```
|
||||
|
||||
### Restoring a Backup
|
||||
|
||||
```
|
||||
cura-te-ipsum restore -b BACKUPS_DIR DEST [PATH ...]
|
||||
|
||||
Required Arguments:
|
||||
-b BACKUPS_DIR Directory where backups are stored
|
||||
DEST Directory to restore into (created if missing)
|
||||
|
||||
Optional Arguments:
|
||||
PATH Restore only these snapshot-relative paths - each
|
||||
starts with the source directory's basename (e.g.
|
||||
"data/documents/notes.txt" for a source backed up
|
||||
from /home/user/data); default is everything
|
||||
--snapshot NAME Snapshot to restore, e.g. 20260101_120000
|
||||
(default: the latest snapshot)
|
||||
--overwrite {never,always}
|
||||
What to do when a destination path already exists
|
||||
(default: never - existing paths are left alone
|
||||
and reported as skipped)
|
||||
--verify Verify restored content against the snapshot's
|
||||
manifest checksums afterwards
|
||||
-n, --dry-run Show what would be restored without copying
|
||||
anything or creating DEST
|
||||
-f, --force Wait for a running backup/restore instead of
|
||||
exiting immediately
|
||||
-v, --verbose Enable debug logging
|
||||
```
|
||||
|
||||
Restoring the latest snapshot in full:
|
||||
```bash
|
||||
cura-te-ipsum restore -b /backups /tmp/recovered
|
||||
```
|
||||
|
||||
Restoring one file from a specific snapshot, verifying it afterwards
|
||||
(here the source was backed up from `/home/user/data`, so the path
|
||||
starts with `data/`):
|
||||
```bash
|
||||
cura-te-ipsum restore -b /backups --snapshot 20260101_120000 --verify \
|
||||
/tmp/recovered data/documents/notes.txt
|
||||
```
|
||||
|
||||
A restore takes the same `.backups_lock` a backup does, so retention
|
||||
cleanup can never delete a snapshot out from under a restore in progress.
|
||||
Restored files keep the source's mode, ownership (when running as root),
|
||||
and timestamps; symlinks are recreated as symlinks, never followed.
|
||||
|
||||
## How It Works
|
||||
|
||||
### Hardlink-Based Snapshots
|
||||
|
||||
cura-te-ipsum creates complete directory snapshots, but files that haven't changed between backups share the same inode (hardlinked). This means:
|
||||
|
||||
- Each backup appears as a complete, browseable directory tree
|
||||
- Only changed or new files consume additional disk space
|
||||
- Deleting old backups doesn't affect other snapshots until the last reference is removed
|
||||
|
||||
### Backup Process
|
||||
|
||||
1. **Lock Acquisition**: Creates `.backups_lock` to prevent concurrent operations
|
||||
2. **Hardlink Creation**: Hardlinks all files from the most recent backup
|
||||
3. **Rsync Sync**: Syncs source directories to the new backup, updating changed files
|
||||
4. **Delta Tracking**: Copies changed/new files to `.backup_delta` directory
|
||||
5. **Completion Marker**: Creates `.backup_finished` marker file
|
||||
6. **Cleanup**: Removes old backups based on retention policy
|
||||
7. **Lock Release**: Removes lock file
|
||||
|
||||
### Retention Policy
|
||||
|
||||
Default retention (configurable via the `--keep-*` CLI options above):
|
||||
|
||||
- **7 days**: Keep all backups
|
||||
- **30 days**: Keep one backup per day
|
||||
- **52 weeks**: Keep one backup per week
|
||||
- **12 months**: Keep one backup per month
|
||||
- **5+ years**: Keep one backup per year
|
||||
|
||||
The cleanup process never deletes the only remaining backup.
|
||||
|
||||
## Backup Structure
|
||||
|
||||
```
|
||||
backups/
|
||||
2025-01-15_10-30-00/ # backup snapshot
|
||||
.backup_finished # completion marker
|
||||
.backup_delta/ # changed files in this backup
|
||||
[your backed up files] # complete directory tree
|
||||
2025-01-16_10-30-00/
|
||||
.backup_finished
|
||||
.backup_delta/
|
||||
[your backed up files]
|
||||
.backups_lock # lock file (only during backup)
|
||||
```
|
||||
|
||||
## Limitations
|
||||
|
||||
- **Never modify files inside a backup snapshot in place.** Unchanged
|
||||
files are hardlinked between snapshots to save space, so editing or
|
||||
truncating a file in one snapshot changes that same file's content
|
||||
in every other snapshot sharing its inode. Treat every snapshot
|
||||
directory as read-only; copy files out before editing them.
|
||||
- **Restore preserves data content and standard metadata only.** The
|
||||
`restore` command copies file content, mode, ownership, timestamps,
|
||||
and symlinks; it does not preserve ACLs, extended attributes, or
|
||||
filesystem-specific flags.
|
||||
- **Special filesystem entries (FIFOs, sockets, device nodes) are
|
||||
excluded, not backed up** - but only with the default Python
|
||||
implementation, which records them in the snapshot manifest as
|
||||
exclusions rather than copying them. With `--external-rsync`,
|
||||
`rsync`'s `--archive` flag attempts to recreate these entries
|
||||
instead, though device nodes typically require root privileges on
|
||||
the destination and may be skipped or fail without them.
|
||||
- **Symlinks are preserved as symlinks**, including ones pointing
|
||||
outside the source tree - their targets are never followed or
|
||||
copied.
|
||||
- **ACLs, extended attributes, and filesystem-specific flags (e.g.
|
||||
BSD/macOS `chflags`) are never preserved**, by either implementation.
|
||||
The Python backend never reads or sets them; `--external-rsync` uses
|
||||
`--archive` without `-A`/`-X`/`--fileflags`, so they're dropped too.
|
||||
- **Sparse files are not preserved as sparse.** Both implementations
|
||||
do a whole-file copy (`--whole-file` for external rsync), so holes
|
||||
are read and rewritten as allocated zero blocks in the backup.
|
||||
- **Hardlinks between source files are not preserved as hardlinks.**
|
||||
Each hardlinked source file is backed up as an independent file;
|
||||
neither backend passes rsync's `-H`. Only hardlinks *within* the
|
||||
backup repository (across snapshots) are meaningful.
|
||||
- **Mode and timestamps are always preserved.** The Python backend
|
||||
restores mtime with nanosecond precision; `--external-rsync`'s
|
||||
precision depends on the installed rsync build and destination
|
||||
filesystem. **Ownership (uid/gid) is preserved only when running as
|
||||
root.** In the Python backend a failed `chown` is caught and logged,
|
||||
not fatal; with `--external-rsync`, rsync itself just skips
|
||||
ownership it isn't permitted to set.
|
||||
- **Do not mix backends across runs of the same backup.** The default
|
||||
Python backend excludes special entries (see above) and its default
|
||||
hardlink-forward step only understands files, symlinks, and
|
||||
directories - it raises an error on anything else. `--external-rsync`
|
||||
can recreate device nodes and sockets (as `root`, via `--archive`'s
|
||||
`-D`), so a snapshot it created can contain entries the Python
|
||||
backend's hardlinker cannot carry forward into the next backup. Pick
|
||||
one of `--external-rsync`/`--external-hardlink` or the Python
|
||||
defaults and use it consistently for a given backup destination.
|
||||
- **`--dry-run` never writes anything, with either backend.** Neither
|
||||
backend creates a staging directory, hardlink, lock, or any other
|
||||
file or metadata update - each source is compared directly against
|
||||
the latest completed snapshot (never a copy of it), and the proposed
|
||||
create/rewrite/delete/exclude operations are logged. `--external-rsync`
|
||||
runs real rsync with its own `--dry-run` flag (it still reads and
|
||||
stats files to compute what would change); the Python backend performs
|
||||
the same read-only comparison itself.
|
||||
|
||||
## Development
|
||||
|
||||
### Running Tests
|
||||
|
||||
```bash
|
||||
pip install -r requirements-dev.txt
|
||||
pytest
|
||||
```
|
||||
|
||||
### CI/CD
|
||||
|
||||
GitHub Actions automatically runs tests on Python 3.6 through 3.11 for every push and pull request.
|
||||
|
||||
## Author
|
||||
|
||||
Maks Snegov (<snegov@spqr.link>)
|
||||
|
||||
## Project Status
|
||||
|
||||
Development Status: Pre-Alpha, experimental
|
||||
|
||||
This project is under active development and has not yet completed
|
||||
its data-safety checklist (see [IMPROVEMENTS.md](IMPROVEMENTS.md)).
|
||||
The API and configuration options may change in future releases.
|
||||
@@ -1 +0,0 @@
|
||||
version = "master"
|
||||
+853
-129
File diff suppressed because it is too large.
Load diff
+305
-80
@@ -6,12 +6,311 @@ import os.path
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
from datetime import timedelta
|
||||
|
||||
from curateipsum import backup
|
||||
from curateipsum import backup, restore
|
||||
from curateipsum._version import version
|
||||
|
||||
_lg = logging.getLogger("curateipsum")
|
||||
SUPPORTED_PLATFORMS = ("linux", "darwin")
|
||||
_SUBCOMMANDS = ("backup", "restore")
|
||||
_TOP_LEVEL_FLAGS = ("-h", "--help", "-V", "--version")
|
||||
|
||||
|
||||
def _normalize_argv(argv):
|
||||
"""
|
||||
Insert the implicit "backup" subcommand when argv doesn't already
|
||||
start with a known subcommand or a top-level flag (-h/-V), so
|
||||
existing invocations like `cura-te-ipsum -b DIR SRC` keep working
|
||||
unchanged now that `restore` exists alongside `backup`.
|
||||
"""
|
||||
if argv and (argv[0] in _SUBCOMMANDS or argv[0] in _TOP_LEVEL_FLAGS):
|
||||
return argv
|
||||
return ["backup", *argv]
|
||||
|
||||
|
||||
def _nonneg_int(value: str) -> int:
|
||||
"""
|
||||
argparse type for --keep-* options: a negative threshold shifts
|
||||
retention comparisons into the future, which can make cleanup treat
|
||||
every existing backup as eligible for deletion.
|
||||
"""
|
||||
parsed = int(value)
|
||||
if parsed < 0:
|
||||
raise argparse.ArgumentTypeError(
|
||||
"must be zero or a positive integer, got %r" % value
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def _build_parser():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="cura-te-ipsum",
|
||||
description="cura-te-ipsum, my personal backup software.",
|
||||
)
|
||||
parser.add_argument("-V", "--version",
|
||||
action="version",
|
||||
version=f"%(prog)s v{version}")
|
||||
|
||||
common = argparse.ArgumentParser(add_help=False)
|
||||
common.add_argument("-v", "--verbose",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="print verbose information")
|
||||
common.add_argument("-b",
|
||||
dest="backups_dir",
|
||||
metavar="BACKUPS_DIR",
|
||||
type=str,
|
||||
required=True,
|
||||
help="directory, where all backups will be stored")
|
||||
common.add_argument("-f", "--force",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Wait for a running backup/restore to finish "
|
||||
"instead of exiting immediately")
|
||||
common.add_argument("-n", "--dry-run",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="show what would be done, without doing it")
|
||||
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
backup_parser = subparsers.add_parser(
|
||||
"backup", parents=[common], help="create a new backup")
|
||||
backup_parser.add_argument("--external-rsync",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Use external rsync for copying")
|
||||
backup_parser.add_argument("--external-hardlink",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Use cp command for creating hardlink "
|
||||
"copies")
|
||||
backup_parser.add_argument("--keep-all",
|
||||
type=_nonneg_int,
|
||||
default=7,
|
||||
metavar="DAYS",
|
||||
help="keep every backup up to this many days "
|
||||
"in the past (default: %(default)s)")
|
||||
backup_parser.add_argument("--keep-daily",
|
||||
type=_nonneg_int,
|
||||
default=30,
|
||||
metavar="DAYS",
|
||||
help="keep one backup per day up to this "
|
||||
"many days in the past "
|
||||
"(default: %(default)s)")
|
||||
backup_parser.add_argument("--keep-weekly",
|
||||
type=_nonneg_int,
|
||||
default=52,
|
||||
metavar="WEEKS",
|
||||
help="keep one backup per week up to this "
|
||||
"many weeks in the past "
|
||||
"(default: %(default)s)")
|
||||
backup_parser.add_argument("--keep-monthly",
|
||||
type=_nonneg_int,
|
||||
default=12,
|
||||
metavar="MONTHS",
|
||||
help="keep one backup per month up to this "
|
||||
"many months in the past "
|
||||
"(default: %(default)s)")
|
||||
backup_parser.add_argument("--keep-yearly",
|
||||
type=_nonneg_int,
|
||||
default=5,
|
||||
metavar="YEARS",
|
||||
help="keep one backup per year up to this "
|
||||
"many years in the past "
|
||||
"(default: %(default)s)")
|
||||
backup_parser.add_argument("sources",
|
||||
nargs="+",
|
||||
metavar="SOURCE",
|
||||
type=str,
|
||||
help="backup source (file/dir/smth else)")
|
||||
|
||||
restore_parser = subparsers.add_parser(
|
||||
"restore", parents=[common], help="restore a backed-up snapshot")
|
||||
restore_parser.add_argument("--snapshot",
|
||||
dest="snapshot_name",
|
||||
metavar="NAME",
|
||||
default=None,
|
||||
help="snapshot to restore, e.g. "
|
||||
"20260101_120000 (default: latest)")
|
||||
restore_parser.add_argument("--overwrite",
|
||||
choices=restore.OVERWRITE_POLICIES,
|
||||
default=restore.OVERWRITE_NEVER,
|
||||
help="what to do when a destination path "
|
||||
"already exists (default: %(default)s)")
|
||||
restore_parser.add_argument("--verify",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="verify restored content against the "
|
||||
"snapshot manifest afterwards")
|
||||
restore_parser.add_argument("dest",
|
||||
metavar="DEST",
|
||||
type=str,
|
||||
help="directory to restore into")
|
||||
restore_parser.add_argument("paths",
|
||||
nargs="*",
|
||||
metavar="PATH",
|
||||
help="restore only these snapshot-relative "
|
||||
"paths - each starts with the source "
|
||||
"directory's basename, e.g. "
|
||||
"'mydir/subdir/file.txt' for a source "
|
||||
"backed up from /home/user/mydir "
|
||||
"(default: restore everything)")
|
||||
|
||||
return parser
|
||||
|
||||
|
||||
def _run_backup(args) -> int:
|
||||
if args.external_rsync and not shutil.which("rsync"):
|
||||
_lg.error("rsync should be installed to use --external-rsync option.")
|
||||
return 1
|
||||
|
||||
cp_program = "gcp" if sys.platform == "darwin" else "cp"
|
||||
if args.external_hardlink and not shutil.which(cp_program):
|
||||
_lg.error("%s should be installed to use --external-hardlink option.",
|
||||
cp_program)
|
||||
return 1
|
||||
|
||||
backups_dir_abs = os.path.abspath(args.backups_dir)
|
||||
if not os.path.isdir(backups_dir_abs):
|
||||
_lg.error("Backup directory %s does not exist, exiting",
|
||||
args.backups_dir)
|
||||
return 1
|
||||
|
||||
for src_dir in args.sources:
|
||||
if not os.path.isdir(src_dir):
|
||||
_lg.error("Source directory %s does not exist", src_dir)
|
||||
return 1
|
||||
|
||||
try:
|
||||
backup.validate_topology(args.sources, backups_dir_abs)
|
||||
except backup.BackupFailedError as err:
|
||||
_lg.error("Unsafe source/backups layout: %s", err)
|
||||
return 1
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# A dry-run never writes anything, including lock metadata, so it
|
||||
# doesn't need to acquire the lock at all - only a real run has to
|
||||
# serialize against other backups/restores.
|
||||
if not args.dry_run and not backup.set_backups_lock(
|
||||
backups_dir_abs, args.force):
|
||||
return 1
|
||||
|
||||
exit_code = 0
|
||||
try:
|
||||
# Retention deletes old snapshots, so it must only run once the
|
||||
# new snapshot is durable and complete - never before, and never
|
||||
# if the backup below raised. Running it first (or unconditionally
|
||||
# after a failure) would let a failed backup destroy history
|
||||
# that a successful one would have covered.
|
||||
backup.initiate_backup(
|
||||
sources=args.sources,
|
||||
backups_dir=backups_dir_abs,
|
||||
dry_run=args.dry_run,
|
||||
external_rsync=args.external_rsync,
|
||||
external_hardlink=args.external_hardlink,
|
||||
)
|
||||
backup.cleanup_old_backups(
|
||||
backups_dir=backups_dir_abs,
|
||||
dry_run=args.dry_run,
|
||||
keep_all=args.keep_all,
|
||||
keep_daily=args.keep_daily,
|
||||
keep_weekly=args.keep_weekly,
|
||||
keep_monthly=args.keep_monthly,
|
||||
keep_yearly=args.keep_yearly,
|
||||
)
|
||||
except backup.BackupFailedError as err:
|
||||
_lg.error("Backup failed: %s", err)
|
||||
exit_code = 1
|
||||
finally:
|
||||
if not args.dry_run:
|
||||
backup.release_backups_lock(backups_dir_abs)
|
||||
|
||||
end_time = time.time()
|
||||
spent_time = end_time - start_time
|
||||
_lg.info("Finished, time spent: %s", str(timedelta(seconds=spent_time)))
|
||||
|
||||
return exit_code
|
||||
|
||||
|
||||
def _run_restore(args) -> int:
|
||||
backups_dir_abs = os.path.abspath(args.backups_dir)
|
||||
if not os.path.isdir(backups_dir_abs):
|
||||
_lg.error("Backup directory %s does not exist, exiting",
|
||||
args.backups_dir)
|
||||
return 1
|
||||
|
||||
dest_abs = os.path.abspath(args.dest)
|
||||
|
||||
# Locked for the same reason a backup is: retention could otherwise
|
||||
# delete or quarantine the very snapshot this restore is reading from
|
||||
# while it's still in progress. set_backups_lock() already logs why
|
||||
# (e.g. "Previous backup is still in progress") - add restore-specific
|
||||
# context here so a restore failure doesn't read like a backup one.
|
||||
# A dry-run never writes to dest_dir, so it doesn't need this
|
||||
# protection - nothing it reads can be invalidated by a concurrent
|
||||
# writer in a way that produces anything worse than a stale preview.
|
||||
if not args.dry_run and not backup.set_backups_lock(
|
||||
backups_dir_abs, args.force):
|
||||
_lg.error("Could not acquire the backups lock, restore aborted "
|
||||
"(use --force to wait for it instead)")
|
||||
return 1
|
||||
|
||||
exit_code = 0
|
||||
try:
|
||||
try:
|
||||
snapshot_entry = backup.find_backup(backups_dir_abs,
|
||||
args.snapshot_name)
|
||||
except backup.BackupFailedError as err:
|
||||
_lg.error("%s", err)
|
||||
return 1
|
||||
|
||||
_lg.info("Restoring snapshot %s to %s%s",
|
||||
snapshot_entry.name, args.dest,
|
||||
" (dry-run)" if args.dry_run else "")
|
||||
|
||||
if not args.dry_run:
|
||||
os.makedirs(dest_abs, exist_ok=True)
|
||||
elif not os.path.isdir(dest_abs):
|
||||
_lg.warning("Destination %s does not exist (dry-run, not "
|
||||
"creating it)", args.dest)
|
||||
|
||||
try:
|
||||
skipped = restore.restore_snapshot(
|
||||
snapshot_entry=snapshot_entry,
|
||||
dest_dir=dest_abs,
|
||||
dry_run=args.dry_run,
|
||||
overwrite=args.overwrite,
|
||||
rel_paths=args.paths or None,
|
||||
)
|
||||
except restore.RestoreError as err:
|
||||
_lg.error("Restore failed: %s", err)
|
||||
return 1
|
||||
|
||||
if skipped:
|
||||
_lg.warning("Skipped %d existing path(s) (use --overwrite "
|
||||
"always to replace them): %s",
|
||||
len(skipped), ", ".join(skipped))
|
||||
|
||||
if args.verify and not args.dry_run:
|
||||
mismatches = restore.verify_restored(
|
||||
snapshot_entry=snapshot_entry,
|
||||
dest_dir=dest_abs,
|
||||
rel_paths=args.paths or None,
|
||||
)
|
||||
if mismatches:
|
||||
_lg.error("Verification failed for %d path(s): %s",
|
||||
len(mismatches), ", ".join(mismatches))
|
||||
exit_code = 1
|
||||
else:
|
||||
_lg.info("Verified: restored content matches the manifest")
|
||||
finally:
|
||||
if not args.dry_run:
|
||||
backup.release_backups_lock(backups_dir_abs)
|
||||
|
||||
return exit_code
|
||||
|
||||
|
||||
def main():
|
||||
@@ -19,44 +318,8 @@ def main():
|
||||
console_handler = logging.StreamHandler()
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="cura-te-ipsum", description="cura-te-ipsum, my personal backup software.",
|
||||
)
|
||||
parser.add_argument("-V", "--version",
|
||||
action="version",
|
||||
version=f"%(prog)s {version}")
|
||||
parser.add_argument("-v", "--verbose",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="print verbose information")
|
||||
parser.add_argument("-b",
|
||||
dest="backup_dir",
|
||||
metavar="BACKUP_DIR",
|
||||
type=str,
|
||||
required=True,
|
||||
help="directory, where all backups will be stored")
|
||||
parser.add_argument("-n", "--dry-run",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Do not do create backup")
|
||||
parser.add_argument("-f", "--force",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Force run when previous backup is still in process")
|
||||
parser.add_argument("--external-rsync",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Use external rsync for copying")
|
||||
parser.add_argument("--external-hardlink",
|
||||
action="store_true",
|
||||
default=False,
|
||||
help="Use cp command for creating hardlink copies")
|
||||
parser.add_argument("sources",
|
||||
nargs="+",
|
||||
metavar="SOURCE",
|
||||
type=str,
|
||||
help="backup source (file/dir/smth else)")
|
||||
args = parser.parse_args()
|
||||
parser = _build_parser()
|
||||
args = parser.parse_args(_normalize_argv(sys.argv[1:]))
|
||||
|
||||
loglevel = logging.DEBUG if args.verbose else logging.INFO
|
||||
logging.basicConfig(level=loglevel, handlers=[console_handler])
|
||||
@@ -68,47 +331,9 @@ def main():
|
||||
sys.platform, SUPPORTED_PLATFORMS)
|
||||
return 1
|
||||
|
||||
if args.external_rsync and not shutil.which("rsync"):
|
||||
_lg.error("rsync should be installed to use --external-rsync option.")
|
||||
return 1
|
||||
|
||||
cp_program = "gcp" if sys.platform == "darwin" else "cp"
|
||||
if args.external_hardlink and not shutil.which(cp_program):
|
||||
_lg.error("%s should be installed to use --external-hardlink option.",
|
||||
cp_program)
|
||||
return 1
|
||||
|
||||
backup_dir_abs = os.path.abspath(args.backup_dir)
|
||||
if not os.path.isdir(backup_dir_abs):
|
||||
_lg.error("Backup directory %s does not exist, exiting", args.backup_dir)
|
||||
return 1
|
||||
|
||||
for src_dir in args.sources:
|
||||
if not os.path.isdir(src_dir):
|
||||
_lg.error("Source directory %s does not exist", src_dir)
|
||||
return 1
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
if not backup.set_backups_lock(backup_dir_abs, args.force):
|
||||
_lg.warning("Previous backup is still in process, exiting")
|
||||
return 1
|
||||
|
||||
backup.cleanup_old_backups(backup_dir=backup_dir_abs, dry_run=args.dry_run)
|
||||
backup.initiate_backup(
|
||||
sources=args.sources,
|
||||
backup_dir=backup_dir_abs,
|
||||
dry_run=args.dry_run,
|
||||
external_rsync=args.external_rsync,
|
||||
external_hardlink=args.external_hardlink,
|
||||
)
|
||||
|
||||
backup.release_backups_lock(backup_dir_abs)
|
||||
end_time = time.time()
|
||||
spent_time = end_time - start_time
|
||||
_lg.info("Finished, time spent: %.3fs", spent_time)
|
||||
|
||||
return 0
|
||||
if args.command == "restore":
|
||||
return _run_restore(args)
|
||||
return _run_backup(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+470
-134
@@ -4,15 +4,22 @@ Module with filesystem-related functions.
|
||||
|
||||
import enum
|
||||
import glob
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
from typing import Iterable, Tuple
|
||||
import uuid
|
||||
from typing import Iterable, Optional, Tuple, Union
|
||||
|
||||
_lg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BackupCreationError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Actions(enum.Enum):
|
||||
NOTHING = enum.auto()
|
||||
DELETE = enum.auto()
|
||||
@@ -21,34 +28,123 @@ class Actions(enum.Enum):
|
||||
UPDATE_PERM = enum.auto()
|
||||
UPDATE_OWNER = enum.auto()
|
||||
CREATE = enum.auto()
|
||||
ERROR = enum.auto()
|
||||
EXCLUDE = enum.auto()
|
||||
|
||||
|
||||
# Entry kinds copy_direntry() knows how to back up. Everything else
|
||||
# (FIFOs, sockets, block/char devices, and anything lstat() doesn't
|
||||
# recognize) is classified and excluded without ever being opened - a
|
||||
# FIFO with no writer would otherwise block open() for read forever, and
|
||||
# reading a device node can return unbounded or meaningless data.
|
||||
_SUPPORTED_KINDS = frozenset({"file", "dir", "symlink"})
|
||||
|
||||
|
||||
def entry_kind(entry: Union[os.DirEntry, "PseudoDirEntry"]) -> str:
|
||||
"""
|
||||
Classify a filesystem entry via lstat() mode bits alone - never
|
||||
opens it, so classifying a FIFO can't block even without a writer.
|
||||
:return: one of "file", "dir", "symlink", "fifo", "socket",
|
||||
"block_device", "char_device", "unknown".
|
||||
"""
|
||||
mode = entry.stat(follow_symlinks=False).st_mode
|
||||
if stat.S_ISLNK(mode):
|
||||
return "symlink"
|
||||
if stat.S_ISDIR(mode):
|
||||
return "dir"
|
||||
if stat.S_ISREG(mode):
|
||||
return "file"
|
||||
if stat.S_ISFIFO(mode):
|
||||
return "fifo"
|
||||
if stat.S_ISSOCK(mode):
|
||||
return "socket"
|
||||
if stat.S_ISBLK(mode):
|
||||
return "block_device"
|
||||
if stat.S_ISCHR(mode):
|
||||
return "char_device"
|
||||
return "unknown"
|
||||
|
||||
|
||||
class PseudoDirEntry:
|
||||
"""
|
||||
Duck-typed os.DirEntry for paths that don't exist yet or when you need
|
||||
DirEntry-like interface for arbitrary paths.
|
||||
|
||||
Problem: os.DirEntry is created by os.scandir() and cannot be manually
|
||||
constructed. But we need DirEntry-compatible objects for:
|
||||
- Paths that will exist soon (new backup directories)
|
||||
- Constructed paths (marker files)
|
||||
- Uniform interface in functions accepting both real and future entries
|
||||
|
||||
Why not just use strings? Functions like rm_direntry(), copy_direntry()
|
||||
accept Union[os.DirEntry, PseudoDirEntry] and call .is_dir(), .stat()
|
||||
methods. Using this class avoids branching on type throughout the codebase.
|
||||
|
||||
Why not pathlib.Path? We heavily use os.scandir() which returns DirEntry
|
||||
objects with cached stat info. PseudoDirEntry maintains API consistency
|
||||
with minimal overhead.
|
||||
|
||||
Example usage:
|
||||
# Create entry for future backup directory
|
||||
cur_backup = PseudoDirEntry("/backups/20260204_120000")
|
||||
os.mkdir(cur_backup.path)
|
||||
set_backup_marker(cur_backup) # accepts DirEntry-like object
|
||||
|
||||
Caches stat results like real DirEntry to avoid repeated syscalls.
|
||||
"""
|
||||
def __init__(self, path):
|
||||
self.path = os.path.realpath(path)
|
||||
# Use abspath, not realpath - realpath resolves symlinks
|
||||
self.path = os.path.abspath(path)
|
||||
self.name = os.path.basename(self.path)
|
||||
self._is_dir = None
|
||||
self._stat = None
|
||||
self._is_file = None
|
||||
self._is_symlink = None
|
||||
# Cache both stat and lstat separately
|
||||
self._stat_follow = None
|
||||
self._stat_nofollow = None
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
||||
def is_dir(self) -> bool:
|
||||
def is_dir(self, follow_symlinks: bool = True) -> bool:
|
||||
if follow_symlinks:
|
||||
if self._is_dir is None:
|
||||
self._is_dir = os.path.isdir(self.path)
|
||||
return self._is_dir
|
||||
else:
|
||||
# When not following symlinks, must return False if path is symlink
|
||||
return os.path.isdir(self.path) and not os.path.islink(self.path)
|
||||
|
||||
def stat(self):
|
||||
if self._stat is None:
|
||||
self._stat = os.lstat(self.path)
|
||||
return self._stat
|
||||
def is_file(self, follow_symlinks: bool = True) -> bool:
|
||||
if follow_symlinks:
|
||||
if self._is_file is None:
|
||||
self._is_file = os.path.isfile(self.path)
|
||||
return self._is_file
|
||||
else:
|
||||
# When not following symlinks, must return False if path is symlink
|
||||
return os.path.isfile(self.path) and not os.path.islink(self.path)
|
||||
|
||||
def is_symlink(self) -> bool:
|
||||
if self._is_symlink is None:
|
||||
self._is_symlink = os.path.islink(self.path)
|
||||
return self._is_symlink
|
||||
|
||||
def stat(self, follow_symlinks: bool = True):
|
||||
if follow_symlinks:
|
||||
if self._stat_follow is None:
|
||||
self._stat_follow = os.stat(self.path)
|
||||
return self._stat_follow
|
||||
else:
|
||||
if self._stat_nofollow is None:
|
||||
self._stat_nofollow = os.lstat(self.path)
|
||||
return self._stat_nofollow
|
||||
|
||||
|
||||
def _parse_rsync_output(line: str) -> Tuple[str, Actions]:
|
||||
def _parse_rsync_output(line: str) -> Tuple[str, Actions, str]:
|
||||
action = None
|
||||
change_string, relpath = line.split(' ', maxsplit=1)
|
||||
if change_string == "*deleting":
|
||||
return relpath, Actions.DELETE
|
||||
return relpath, Actions.DELETE, ""
|
||||
|
||||
update_type = change_string[0]
|
||||
entity_type = change_string[1]
|
||||
@@ -69,11 +165,14 @@ def _parse_rsync_output(line: str) -> Tuple[str, Actions]:
|
||||
|
||||
if action is None:
|
||||
raise RuntimeError("Not parsed string: %s" % line)
|
||||
return relpath, action
|
||||
return relpath, action, ""
|
||||
|
||||
|
||||
def rsync_ext(src, dst, dry_run=False):
|
||||
"""Call external rsync command"""
|
||||
def rsync_ext(src, dst, dry_run=False) -> Iterable[Tuple[str, Actions, str]]:
|
||||
"""
|
||||
Call external rsync command for syncing files from src to dst.
|
||||
Yield (path, action, error message) tuples.
|
||||
"""
|
||||
rsync_args = ["rsync"]
|
||||
if dry_run:
|
||||
rsync_args.append("--dry-run")
|
||||
@@ -82,6 +181,7 @@ def rsync_ext(src, dst, dry_run=False):
|
||||
# rsync_args.append("--inplace")
|
||||
rsync_args.append("--whole-file")
|
||||
rsync_args.append("--human-readable")
|
||||
rsync_args.append("--one-file-system")
|
||||
rsync_args.append("--delete-during")
|
||||
rsync_args.append("--itemize-changes")
|
||||
rsync_args.append(f"{src}/")
|
||||
@@ -120,32 +220,58 @@ def rsync_ext(src, dst, dry_run=False):
|
||||
process.wait()
|
||||
|
||||
|
||||
def scantree(path, dir_first=True) -> Iterable[os.DirEntry]:
|
||||
"""Recursively yield DirEntry file objects for given directory."""
|
||||
def scantree(path, dir_first=True,
|
||||
one_filesystem=False, _root_dev=None) -> Iterable[os.DirEntry]:
|
||||
"""
|
||||
Recursively yield DirEntry objects (dir/file/symlink) for given directory.
|
||||
|
||||
:param one_filesystem: if True, don't descend into a subdirectory that
|
||||
lives on a different device than `path` (a mount point). The
|
||||
directory itself is still yielded, so it appears as an empty
|
||||
directory in the walk - only its contents are excluded. Matches
|
||||
rsync's --one-file-system behavior.
|
||||
"""
|
||||
if one_filesystem and _root_dev is None:
|
||||
# os.stat(), not os.lstat(): scandir() follows `path` if it's a
|
||||
# symlink, so the root device must be the resolved directory's,
|
||||
# not the symlink's own.
|
||||
_root_dev = os.stat(path).st_dev
|
||||
|
||||
entry: os.DirEntry
|
||||
with os.scandir(path) as scan_it:
|
||||
for entry in scan_it:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
if (one_filesystem
|
||||
and os.lstat(entry.path).st_dev != _root_dev):
|
||||
_lg.warning(
|
||||
"Scantree, excluding mount point contents: %s",
|
||||
entry.path)
|
||||
yield entry
|
||||
continue
|
||||
if dir_first:
|
||||
yield entry
|
||||
yield from scantree(entry.path, dir_first)
|
||||
yield from scantree(entry.path, dir_first,
|
||||
one_filesystem, _root_dev)
|
||||
if not dir_first:
|
||||
yield entry
|
||||
else:
|
||||
yield entry
|
||||
|
||||
|
||||
def rm_direntry(entry: os.DirEntry):
|
||||
""" Recursively delete DirEntry (dir, file or symlink). """
|
||||
if entry.is_file(follow_symlinks=False) or entry.is_symlink():
|
||||
os.unlink(entry.path)
|
||||
return
|
||||
def rm_direntry(entry: Union[os.DirEntry, PseudoDirEntry]):
|
||||
"""
|
||||
Recursively delete DirEntry. Directories are removed recursively;
|
||||
anything else (file, symlink, or a special entry like a FIFO,
|
||||
socket, or device node) is unlinked directly.
|
||||
"""
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
with os.scandir(entry.path) as it:
|
||||
child_entry: os.DirEntry
|
||||
for child_entry in it:
|
||||
rm_direntry(child_entry)
|
||||
os.rmdir(entry.path)
|
||||
else:
|
||||
os.unlink(entry.path)
|
||||
|
||||
|
||||
try:
|
||||
@@ -157,98 +283,190 @@ WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | O_BINARY
|
||||
BUFFER_SIZE = 128 * 1024
|
||||
|
||||
|
||||
def copy_file(src, dst):
|
||||
""" Copy file from src to dst. Faster than shutil.copy. """
|
||||
def _write_all(fd: int, data: bytes):
|
||||
"""os.write() may write fewer bytes than given; loop until it's all out."""
|
||||
view = memoryview(data)
|
||||
while view:
|
||||
written = os.write(fd, view)
|
||||
view = view[written:]
|
||||
|
||||
|
||||
def copy_file(src, dst) -> str:
|
||||
"""
|
||||
Copy file from src to dst. Faster than shutil.copy.
|
||||
|
||||
Compares fstat() on the source's own open file descriptor before and
|
||||
after the read loop - this reflects the underlying inode directly, so
|
||||
it catches the source being truncated, grown, or overwritten in place
|
||||
while being read (and isn't fooled by the source path being renamed
|
||||
or unlinked mid-copy, since the descriptor keeps referring to the
|
||||
same inode regardless). Nanosecond mtime is used so a same-second
|
||||
modification can't slip past undetected.
|
||||
|
||||
:return: sha256 hex digest of the bytes actually copied.
|
||||
:raises BackupCreationError: if the source changed while being read.
|
||||
"""
|
||||
fin = None
|
||||
fout = None
|
||||
try:
|
||||
fin = os.open(src, READ_FLAGS)
|
||||
stat = os.fstat(fin)
|
||||
fout = os.open(dst, WRITE_FLAGS, stat.st_mode)
|
||||
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
|
||||
os.write(fout, x)
|
||||
stat_before = os.fstat(fin)
|
||||
fout = os.open(dst, WRITE_FLAGS, stat_before.st_mode)
|
||||
digest = hashlib.sha256()
|
||||
for chunk in iter(lambda: os.read(fin, BUFFER_SIZE), b""):
|
||||
_write_all(fout, chunk)
|
||||
digest.update(chunk)
|
||||
stat_after = os.fstat(fin)
|
||||
if (stat_after.st_size != stat_before.st_size
|
||||
or stat_after.st_mtime_ns != stat_before.st_mtime_ns):
|
||||
raise BackupCreationError(
|
||||
"Source file changed while being copied: %s" % src
|
||||
)
|
||||
return digest.hexdigest()
|
||||
finally:
|
||||
try: os.close(fout)
|
||||
except: pass
|
||||
try: os.close(fin)
|
||||
except: pass
|
||||
if fout is not None:
|
||||
try:
|
||||
os.close(fout)
|
||||
except OSError:
|
||||
pass
|
||||
if fin is not None:
|
||||
try:
|
||||
os.close(fin)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def copy_entity(src_path: str, dst_path: str):
|
||||
""" Non-recursive fs entity (file, dir or symlink) copy. """
|
||||
src_stat = os.lstat(src_path)
|
||||
is_symlink = os.path.islink(src_path)
|
||||
def _break_shared_hardlink(path: str):
|
||||
"""
|
||||
Give `path` a private inode if it currently shares one with another
|
||||
file (nlink > 1), so a subsequent in-place metadata change (chmod,
|
||||
chown, utime, flags) can never mutate that other file. Files copied
|
||||
into a staging directory via hardlink_dir() start out hardlinked to
|
||||
the previous snapshot; this is the copy-on-write step that keeps
|
||||
that previous, completed snapshot immutable.
|
||||
|
||||
if os.path.isdir(src_path):
|
||||
os.mkdir(dst_path)
|
||||
|
||||
elif is_symlink:
|
||||
link_target = os.readlink(src_path)
|
||||
os.symlink(link_target, dst_path)
|
||||
|
||||
else:
|
||||
copy_file(src_path, dst_path)
|
||||
|
||||
if is_symlink:
|
||||
# change symlink attributes only if supported by OS
|
||||
if os.chown in os.supports_follow_symlinks:
|
||||
os.chown(dst_path, src_stat.st_uid, src_stat.st_gid,
|
||||
follow_symlinks=False)
|
||||
if os.chmod in os.supports_follow_symlinks:
|
||||
os.chmod(dst_path, src_stat.st_mode, follow_symlinks=False)
|
||||
if os.utime in os.supports_follow_symlinks:
|
||||
os.utime(dst_path, (src_stat.st_atime, src_stat.st_mtime),
|
||||
follow_symlinks=False)
|
||||
else:
|
||||
os.chown(dst_path, src_stat.st_uid, src_stat.st_gid)
|
||||
os.chmod(dst_path, src_stat.st_mode)
|
||||
os.utime(dst_path, (src_stat.st_atime, src_stat.st_mtime))
|
||||
The break itself must be metadata-neutral: copy_file() only carries
|
||||
over the mode at file-creation time, not ownership or timestamps, so
|
||||
the new private copy is explicitly restored to the original's full
|
||||
stat before it replaces `path` - otherwise a caller that only meant
|
||||
to update permissions would silently also reset ownership/mtime as a
|
||||
side effect of this implementation detail.
|
||||
"""
|
||||
st = os.lstat(path)
|
||||
if st.st_nlink <= 1:
|
||||
return
|
||||
tmp_path = "%s.cow-%d-%s" % (path, os.getpid(), uuid.uuid4().hex[:8])
|
||||
try:
|
||||
copy_file(path, tmp_path)
|
||||
try:
|
||||
os.chown(tmp_path, st.st_uid, st.st_gid)
|
||||
except PermissionError:
|
||||
_lg.debug("Cannot preserve ownership while breaking hardlink "
|
||||
"(not root): %s", path)
|
||||
os.chmod(tmp_path, st.st_mode)
|
||||
os.utime(tmp_path, ns=(st.st_atime_ns, st.st_mtime_ns))
|
||||
os.replace(tmp_path, path)
|
||||
except (OSError, BackupCreationError):
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
|
||||
|
||||
def copy_direntry(entry: os.DirEntry, dst_path):
|
||||
""" Non-recursive DirEntry (file, dir or symlink) copy. """
|
||||
if entry.is_dir():
|
||||
os.mkdir(dst_path)
|
||||
|
||||
elif entry.is_symlink():
|
||||
def copy_direntry(entry: Union[os.DirEntry, PseudoDirEntry],
|
||||
dst_path) -> Optional[str]:
|
||||
"""
|
||||
Non-recursive DirEntry (file/dir/symlink) copy.
|
||||
:return: sha256 hex digest of the copied content for a regular file,
|
||||
None for a directory or symlink (nothing to hash).
|
||||
"""
|
||||
src_stat = entry.stat(follow_symlinks=False)
|
||||
digest = None
|
||||
# Classify with lstat semantics and check symlink-ness first: is_dir()
|
||||
# (and is_file()) default to follow_symlinks=True, so a symlink
|
||||
# pointing at a directory would otherwise be misclassified as a
|
||||
# directory here and get an empty directory created in its place,
|
||||
# silently losing the symlink and its target.
|
||||
if entry.is_symlink():
|
||||
link_target = os.readlink(entry.path)
|
||||
os.symlink(link_target, dst_path)
|
||||
|
||||
else:
|
||||
copy_file(entry.path, dst_path)
|
||||
elif entry.is_dir(follow_symlinks=False):
|
||||
os.mkdir(dst_path)
|
||||
|
||||
src_stat = entry.stat(follow_symlinks=False)
|
||||
else:
|
||||
digest = copy_file(entry.path, dst_path)
|
||||
|
||||
# Nanosecond timestamps: st_mtime (float seconds) loses sub-second
|
||||
# precision, which could make a real content change on a fast-moving
|
||||
# file look identical to an unrelated file with the same whole-second
|
||||
# mtime once rounded.
|
||||
if entry.is_symlink():
|
||||
# change symlink attributes only if supported by OS
|
||||
if os.chown in os.supports_follow_symlinks:
|
||||
try:
|
||||
os.chown(dst_path, src_stat.st_uid, src_stat.st_gid,
|
||||
follow_symlinks=False)
|
||||
except PermissionError:
|
||||
_lg.debug("Cannot change ownership (not root): %s", dst_path)
|
||||
if os.chmod in os.supports_follow_symlinks:
|
||||
os.chmod(dst_path, src_stat.st_mode, follow_symlinks=False)
|
||||
if os.utime in os.supports_follow_symlinks:
|
||||
os.utime(dst_path, (src_stat.st_atime, src_stat.st_mtime),
|
||||
os.utime(dst_path,
|
||||
ns=(src_stat.st_atime_ns, src_stat.st_mtime_ns),
|
||||
follow_symlinks=False)
|
||||
else:
|
||||
try:
|
||||
os.chown(dst_path, src_stat.st_uid, src_stat.st_gid)
|
||||
except PermissionError:
|
||||
_lg.debug("Cannot change ownership (not root): %s", dst_path)
|
||||
os.chmod(dst_path, src_stat.st_mode)
|
||||
os.utime(dst_path, (src_stat.st_atime, src_stat.st_mtime))
|
||||
os.utime(dst_path, ns=(src_stat.st_atime_ns, src_stat.st_mtime_ns))
|
||||
|
||||
return digest
|
||||
|
||||
|
||||
def update_direntry(src_entry: os.DirEntry, dst_entry: os.DirEntry):
|
||||
def update_direntry(src_entry: os.DirEntry,
|
||||
dst_entry: os.DirEntry) -> Optional[str]:
|
||||
"""
|
||||
Make dst DirEntry (file/dir/symlink) same as src.
|
||||
If dst is directory, its content will be removed.
|
||||
Src dir content will not be copied into dst dir.
|
||||
:return: see copy_direntry().
|
||||
"""
|
||||
rm_direntry(dst_entry)
|
||||
copy_direntry(src_entry, dst_entry.path)
|
||||
return copy_direntry(src_entry, dst_entry.path)
|
||||
|
||||
|
||||
def rsync(src_dir, dst_dir, dry_run=False) -> Iterable[tuple]:
|
||||
def _maybe_update(src_entry: os.DirEntry, dst_entry: os.DirEntry,
|
||||
dry_run: bool) -> Optional[str]:
|
||||
"""
|
||||
Do sync
|
||||
:param src_dir: source dir
|
||||
:param dst_dir: dest dir, create if not exists
|
||||
:param dry_run: not used
|
||||
:return: nothing
|
||||
update_direntry(), unless dry_run - in which case dst_entry is left
|
||||
untouched and no digest is available (nothing was actually copied to
|
||||
hash).
|
||||
"""
|
||||
if dry_run:
|
||||
return None
|
||||
return update_direntry(src_entry, dst_entry)
|
||||
|
||||
|
||||
def rsync(src_dir,
|
||||
dst_dir,
|
||||
dry_run=False) -> Iterable[Tuple[str, Actions, str]]:
|
||||
"""
|
||||
Sync files/dirs/symlinks from src_dir to dst_dir.
|
||||
Yield (path, action, error message) tuples.
|
||||
Entries in dst_dir will be removed if not present in src_dir.
|
||||
Analog of 'rsync --delete -irltpog'.
|
||||
|
||||
With dry_run=True, dst_dir is never created, written to, or mutated
|
||||
in any way (no copy, delete, chmod, chown, or utime call runs) - the
|
||||
same comparison logic that decides each action still runs, so the
|
||||
yielded (path, action, message) tuples describe exactly what a real
|
||||
run would do, but purely by reading src_dir and dst_dir. This lets a
|
||||
dry run diff straight against the previous, immutable snapshot
|
||||
instead of a throwaway hardlinked copy.
|
||||
"""
|
||||
|
||||
_lg.debug("Rsync: %s -> %s", src_dir, dst_dir)
|
||||
@@ -256,22 +474,31 @@ def rsync(src_dir, dst_dir, dry_run=False) -> Iterable[tuple]:
|
||||
dst_root_abs = os.path.abspath(dst_dir)
|
||||
|
||||
if not os.path.isdir(src_root_abs):
|
||||
raise RuntimeError("Error during reading source directory: %s"
|
||||
% src_root_abs)
|
||||
if os.path.exists(dst_root_abs):
|
||||
if not os.path.isdir(dst_root_abs):
|
||||
raise RuntimeError("Destination path is not a directory: %s"
|
||||
% dst_root_abs)
|
||||
raise BackupCreationError(
|
||||
"Error during reading source directory: %s" % src_root_abs
|
||||
)
|
||||
dst_exists = os.path.exists(dst_root_abs)
|
||||
if dst_exists and not os.path.isdir(dst_root_abs):
|
||||
raise BackupCreationError(
|
||||
"Destination path is not a directory: %s" % dst_root_abs
|
||||
)
|
||||
if not dst_exists:
|
||||
if dry_run:
|
||||
# Nothing to compare against and nothing to create - every
|
||||
# source entry below is naturally reported as a CREATE.
|
||||
dst_root_abs = None
|
||||
else:
|
||||
os.mkdir(dst_root_abs)
|
||||
|
||||
# Create source map {rel_path: dir_entry}
|
||||
src_files_map = {
|
||||
ent.path[len(src_root_abs) + 1:]: ent for ent in scantree(src_root_abs)
|
||||
ent.path[len(src_root_abs) + 1:]: ent
|
||||
for ent in scantree(src_root_abs, one_filesystem=True)
|
||||
}
|
||||
|
||||
# process dst tree
|
||||
for dst_entry in scantree(dst_root_abs, dir_first=False):
|
||||
dst_iter = scantree(dst_root_abs, dir_first=False) if dst_root_abs else ()
|
||||
for dst_entry in dst_iter:
|
||||
rel_path = dst_entry.path[len(dst_root_abs) + 1:]
|
||||
|
||||
src_entry = src_files_map.get(rel_path)
|
||||
@@ -279,104 +506,200 @@ def rsync(src_dir, dst_dir, dry_run=False) -> Iterable[tuple]:
|
||||
# remove dst entries not existing in source
|
||||
if src_entry is None:
|
||||
_lg.debug("Rsync, deleting: %s", rel_path)
|
||||
rm_direntry(dst_entry)
|
||||
yield rel_path, Actions.DELETE
|
||||
if dry_run:
|
||||
yield rel_path, Actions.DELETE, ""
|
||||
continue
|
||||
try:
|
||||
rm_direntry(dst_entry)
|
||||
yield rel_path, Actions.DELETE, ""
|
||||
continue
|
||||
except OSError as exc:
|
||||
raise BackupCreationError(exc) from exc
|
||||
|
||||
# mark src entry as taken for processing
|
||||
del src_files_map[rel_path]
|
||||
|
||||
src_entry: os.DirEntry
|
||||
# rewrite dst if it has different than src type
|
||||
src_kind = entry_kind(src_entry)
|
||||
if src_kind not in _SUPPORTED_KINDS:
|
||||
_lg.warning("Rsync, excluding unsupported entry (%s): %s",
|
||||
src_kind, rel_path)
|
||||
# dst_entry may exist here (e.g. inherited via hardlink from
|
||||
# the previous snapshot); an excluded entry must not linger.
|
||||
if not dry_run:
|
||||
try:
|
||||
rm_direntry(dst_entry)
|
||||
except OSError as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
yield rel_path, Actions.EXCLUDE, src_kind
|
||||
continue
|
||||
|
||||
# rewrite dst if it has different type from src
|
||||
if src_entry.is_file(follow_symlinks=False):
|
||||
if not dst_entry.is_file(follow_symlinks=False):
|
||||
_lg.debug("Rsync, rewriting (src is a file, dst is not a file): %s",
|
||||
_lg.debug("Rsync, rewriting"
|
||||
" (src is a file, dst is not a file): %s",
|
||||
rel_path)
|
||||
update_direntry(src_entry, dst_entry)
|
||||
yield rel_path, Actions.REWRITE
|
||||
try:
|
||||
digest = _maybe_update(src_entry, dst_entry, dry_run)
|
||||
yield rel_path, Actions.REWRITE, digest or ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
|
||||
if src_entry.is_dir(follow_symlinks=False):
|
||||
if not dst_entry.is_dir(follow_symlinks=False):
|
||||
_lg.debug("Rsync, rewriting (src is a dir, dst is not a dir): %s",
|
||||
_lg.debug("Rsync, rewriting"
|
||||
" (src is a dir, dst is not a dir): %s",
|
||||
rel_path)
|
||||
update_direntry(src_entry, dst_entry)
|
||||
yield rel_path, Actions.REWRITE
|
||||
try:
|
||||
_maybe_update(src_entry, dst_entry, dry_run)
|
||||
yield rel_path, Actions.REWRITE, ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
|
||||
if src_entry.is_symlink():
|
||||
if not dst_entry.is_symlink():
|
||||
_lg.debug("Rsync, rewriting (src is a symlink, dst is not a symlink): %s",
|
||||
_lg.debug("Rsync, rewriting"
|
||||
" (src is a symlink, dst is not a symlink): %s",
|
||||
rel_path)
|
||||
update_direntry(src_entry, dst_entry)
|
||||
yield rel_path, Actions.REWRITE
|
||||
try:
|
||||
_maybe_update(src_entry, dst_entry, dry_run)
|
||||
yield rel_path, Actions.REWRITE, ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
|
||||
# rewrite dst if it is hard link to src (bad for backups)
|
||||
if src_entry.inode() == dst_entry.inode():
|
||||
_lg.debug("Rsync, rewriting (different inodes): %s", rel_path)
|
||||
update_direntry(src_entry, dst_entry)
|
||||
yield rel_path, Actions.REWRITE
|
||||
_lg.debug("Rsync, rewriting (shared inode with src): %s", rel_path)
|
||||
try:
|
||||
digest = _maybe_update(src_entry, dst_entry, dry_run)
|
||||
yield rel_path, Actions.REWRITE, digest or ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
|
||||
src_stat = src_entry.stat(follow_symlinks=False)
|
||||
dst_stat = dst_entry.stat(follow_symlinks=False)
|
||||
|
||||
# rewrite dst file/symlink which have different with src size or mtime
|
||||
# rewrite dst file/symlink which have different size or mtime than src
|
||||
if src_entry.is_file(follow_symlinks=False):
|
||||
same_size = src_stat.st_size == dst_stat.st_size
|
||||
same_mtime = src_stat.st_mtime == dst_stat.st_mtime
|
||||
same_mtime = src_stat.st_mtime_ns == dst_stat.st_mtime_ns
|
||||
if not (same_size and same_mtime):
|
||||
reason = "size" if not same_size else "time"
|
||||
_lg.debug("Rsync, rewriting (different %s): %s", reason, rel_path)
|
||||
update_direntry(src_entry, dst_entry)
|
||||
yield rel_path, Actions.REWRITE
|
||||
_lg.debug("Rsync, rewriting (different %s): %s",
|
||||
reason, rel_path)
|
||||
try:
|
||||
digest = _maybe_update(src_entry, dst_entry, dry_run)
|
||||
yield rel_path, Actions.REWRITE, digest or ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
|
||||
# rewrite dst symlink if it points somewhere else than src
|
||||
if src_entry.is_symlink():
|
||||
if os.readlink(src_entry.path) != os.readlink(dst_entry.path):
|
||||
_lg.debug("Rsync, rewriting (different symlink target): %s", rel_path)
|
||||
update_direntry(src_entry, dst_entry)
|
||||
_lg.debug("Rsync, rewriting (different symlink target): %s",
|
||||
rel_path)
|
||||
try:
|
||||
_maybe_update(src_entry, dst_entry, dry_run)
|
||||
yield rel_path, Actions.REWRITE, ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
continue
|
||||
|
||||
# Symlinks reaching here already have a matching target (handled
|
||||
# above), and applying chmod/chown to a symlink path without
|
||||
# follow_symlinks=False support would silently modify whatever
|
||||
# the symlink points to - including a target outside the backup
|
||||
# entirely. There's nothing meaningful left to sync for them.
|
||||
if src_entry.is_symlink():
|
||||
continue
|
||||
|
||||
# A regular file reaching here is unchanged in content, but may
|
||||
# still be hardlinked to the same file in the previous, supposedly
|
||||
# immutable snapshot (hardlink_dir() links unchanged files in at
|
||||
# the start of every backup to save space). Break that link
|
||||
# before mutating permissions/ownership in place, or the change
|
||||
# would silently apply to every older snapshot sharing the inode.
|
||||
if src_entry.is_file(follow_symlinks=False):
|
||||
if not dry_run and (src_stat.st_mode != dst_stat.st_mode or (
|
||||
src_stat.st_uid != dst_stat.st_uid
|
||||
or src_stat.st_gid != dst_stat.st_gid)):
|
||||
_break_shared_hardlink(dst_entry.path)
|
||||
|
||||
# update permissions and ownership
|
||||
if src_stat.st_mode != dst_stat.st_mode:
|
||||
_lg.debug("Rsync, updating permissions: %s", rel_path)
|
||||
yield rel_path, Actions.UPDATE_PERM
|
||||
os.chmod(dst_entry.path, dst_stat.st_mode)
|
||||
if not dry_run:
|
||||
os.chmod(dst_entry.path, src_stat.st_mode)
|
||||
yield rel_path, Actions.UPDATE_PERM, ""
|
||||
|
||||
if src_stat.st_uid != dst_stat.st_uid or src_stat.st_gid != dst_stat.st_gid:
|
||||
if (src_stat.st_uid != dst_stat.st_uid
|
||||
or src_stat.st_gid != dst_stat.st_gid):
|
||||
_lg.debug("Rsync, updating owners: %s", rel_path)
|
||||
yield rel_path, Actions.UPDATE_OWNER
|
||||
if dry_run:
|
||||
yield rel_path, Actions.UPDATE_OWNER, ""
|
||||
else:
|
||||
try:
|
||||
os.chown(dst_entry.path, src_stat.st_uid, src_stat.st_gid)
|
||||
yield rel_path, Actions.UPDATE_OWNER, ""
|
||||
except PermissionError:
|
||||
_lg.debug("Cannot change ownership (not root): %s",
|
||||
rel_path)
|
||||
|
||||
# process remained source entries
|
||||
# process remained source entries (new files/dirs/symlinks)
|
||||
for rel_path, src_entry in src_files_map.items():
|
||||
src_kind = entry_kind(src_entry)
|
||||
if src_kind not in _SUPPORTED_KINDS:
|
||||
_lg.warning("Rsync, excluding unsupported entry (%s): %s",
|
||||
src_kind, rel_path)
|
||||
yield rel_path, Actions.EXCLUDE, src_kind
|
||||
continue
|
||||
|
||||
if dry_run:
|
||||
yield rel_path, Actions.CREATE, ""
|
||||
continue
|
||||
|
||||
dst_path = os.path.join(dst_root_abs, rel_path)
|
||||
_lg.debug("Rsync, creating: %s", rel_path)
|
||||
copy_direntry(src_entry, dst_path)
|
||||
yield rel_path, Actions.CREATE
|
||||
try:
|
||||
digest = copy_direntry(src_entry, dst_path)
|
||||
yield rel_path, Actions.CREATE, digest or ""
|
||||
except (OSError, BackupCreationError) as exc:
|
||||
yield rel_path, Actions.ERROR, str(exc)
|
||||
|
||||
if dry_run:
|
||||
# Nothing below this point does anything but restore directory
|
||||
# mtimes disturbed by the mutations above - none of which ran.
|
||||
return
|
||||
|
||||
# restore dir mtimes in dst, updated by updating files
|
||||
for src_entry in scantree(src_root_abs, dir_first=True):
|
||||
if not src_entry.is_dir():
|
||||
for src_entry in scantree(src_root_abs, dir_first=True,
|
||||
one_filesystem=True):
|
||||
if not src_entry.is_dir(follow_symlinks=False):
|
||||
continue
|
||||
rel_path = src_entry.path[len(src_root_abs) + 1:]
|
||||
dst_path = os.path.join(dst_root_abs, rel_path)
|
||||
src_stat = src_entry.stat(follow_symlinks=False)
|
||||
dst_stat = os.lstat(dst_path)
|
||||
if src_stat.st_mtime != dst_stat.st_mtime:
|
||||
if src_stat.st_mtime_ns != dst_stat.st_mtime_ns:
|
||||
_lg.debug("Rsync, restoring directory mtime: %s", dst_path)
|
||||
os.utime(dst_path,
|
||||
(src_stat.st_atime, src_stat.st_mtime),
|
||||
ns=(src_stat.st_atime_ns, src_stat.st_mtime_ns),
|
||||
follow_symlinks=False)
|
||||
|
||||
# restore dst_root dir mtime
|
||||
src_root_stat = os.lstat(src_root_abs)
|
||||
dst_root_stat = os.lstat(dst_root_abs)
|
||||
if src_root_stat.st_mtime != dst_root_stat.st_mtime:
|
||||
_lg.debug("Rsync, restoring root directory mtime: %s", src_root_abs)
|
||||
if src_root_stat.st_mtime_ns != dst_root_stat.st_mtime_ns:
|
||||
_lg.debug("Rsync, restoring root directory mtime: %s", dst_root_abs)
|
||||
os.utime(dst_root_abs,
|
||||
(src_root_stat.st_atime, src_root_stat.st_mtime),
|
||||
ns=(src_root_stat.st_atime_ns, src_root_stat.st_mtime_ns),
|
||||
follow_symlinks=False)
|
||||
|
||||
|
||||
@@ -410,7 +733,7 @@ def _recursive_hardlink(src: str, dst: str) -> bool:
|
||||
Both src and dst directories should exist.
|
||||
:param src: absolute path to source directory.
|
||||
:param dst: absolute path to target directory.
|
||||
:return: None
|
||||
:return: True if success, False otherwise.
|
||||
"""
|
||||
with os.scandir(src) as it:
|
||||
ent: os.DirEntry
|
||||
@@ -426,9 +749,13 @@ def _recursive_hardlink(src: str, dst: str) -> bool:
|
||||
|
||||
# save directory's metainfo
|
||||
ent_stat = ent.stat(follow_symlinks=False)
|
||||
try:
|
||||
os.chown(ent_dst_path, ent_stat.st_uid, ent_stat.st_gid)
|
||||
except PermissionError:
|
||||
_lg.debug("Cannot change ownership (not root): %s", ent_dst_path)
|
||||
os.chmod(ent_dst_path, ent_stat.st_mode)
|
||||
os.utime(ent_dst_path, (ent_stat.st_atime, ent_stat.st_mtime))
|
||||
os.utime(ent_dst_path,
|
||||
ns=(ent_stat.st_atime_ns, ent_stat.st_mtime_ns))
|
||||
|
||||
continue
|
||||
if ent.is_file(follow_symlinks=False) or ent.is_symlink():
|
||||
@@ -448,7 +775,7 @@ def hardlink_dir(src_dir, dst_dir, use_external: bool = False) -> bool:
|
||||
:param src_dir: path to source directory
|
||||
:param dst_dir: path to target directory
|
||||
:param use_external: whether to use external cp -al command
|
||||
:return: success or not
|
||||
:return: True if success, False otherwise.
|
||||
"""
|
||||
_lg.debug("Recursive hardlinking: %s -> %s", src_dir, dst_dir)
|
||||
src_abs = os.path.abspath(src_dir)
|
||||
@@ -461,24 +788,32 @@ def hardlink_dir(src_dir, dst_dir, use_external: bool = False) -> bool:
|
||||
_lg.debug("Hardlink, creating directory: %s", dst_abs)
|
||||
os.mkdir(dst_abs)
|
||||
|
||||
hardlink_func = _recursive_hardlink_ext if use_external else _recursive_hardlink
|
||||
hardlink_func = (_recursive_hardlink_ext if use_external
|
||||
else _recursive_hardlink)
|
||||
return hardlink_func(src_abs, dst_abs)
|
||||
|
||||
|
||||
def nest_hardlink(src_dir: str, src_relpath: str, dst_dir: str):
|
||||
"""
|
||||
Hardlink entity from (src_dir + src_relpath) to dst_dir preserving dir structure.
|
||||
Hardlink entity from (src_dir + src_relpath) to dst_dir preserving dir
|
||||
structure of src_relpath.
|
||||
"""
|
||||
_lg.debug("Nested hardlinking: %s/%s -> %s", src_dir, src_relpath, dst_dir)
|
||||
_lg.debug("Nested hardlinking: %s%s%s -> %s",
|
||||
src_dir, os.path.sep, src_relpath, dst_dir)
|
||||
if os.path.isabs(src_relpath) or os.path.pardir in src_relpath.split(
|
||||
os.path.sep):
|
||||
raise RuntimeError(
|
||||
"Refusing non-normalized relative path: %s" % src_relpath)
|
||||
|
||||
src_dir_abs = os.path.abspath(src_dir)
|
||||
src_full_path = os.path.join(src_dir_abs, src_relpath)
|
||||
dst_dir_abs = os.path.abspath(dst_dir)
|
||||
dst_full_path = os.path.join(dst_dir_abs, src_relpath)
|
||||
|
||||
# check source entity and destination directory
|
||||
if not os.path.exists(src_full_path):
|
||||
if not os.path.lexists(src_full_path):
|
||||
raise RuntimeError("Error reading source entity: %s" % src_full_path)
|
||||
if os.path.exists(dst_dir_abs):
|
||||
if os.path.lexists(dst_dir_abs):
|
||||
if not os.path.isdir(dst_dir_abs):
|
||||
raise RuntimeError("Destination path is not a directory: %s"
|
||||
% dst_dir_abs)
|
||||
@@ -486,12 +821,13 @@ def nest_hardlink(src_dir: str, src_relpath: str, dst_dir: str):
|
||||
os.mkdir(dst_dir_abs)
|
||||
|
||||
# if destination entity exists, check it points to source entity
|
||||
if os.path.exists(dst_full_path):
|
||||
dst_entry = PseudoDirEntry(dst_full_path)
|
||||
if os.path.lexists(dst_entry.path):
|
||||
src_stat = os.lstat(src_full_path)
|
||||
if os.path.samestat(src_stat, os.lstat(dst_full_path)):
|
||||
if os.path.samestat(src_stat, dst_entry.stat()):
|
||||
return
|
||||
# remove otherwise
|
||||
os.unlink(dst_full_path)
|
||||
rm_direntry(dst_entry)
|
||||
|
||||
src_cur_path = src_dir_abs
|
||||
dst_cur_path = dst_dir_abs
|
||||
@@ -500,4 +836,4 @@ def nest_hardlink(src_dir: str, src_relpath: str, dst_dir: str):
|
||||
dst_cur_path = os.path.join(dst_cur_path, rel_part)
|
||||
if os.path.exists(dst_cur_path):
|
||||
continue
|
||||
copy_entity(src_cur_path, dst_cur_path)
|
||||
copy_direntry(PseudoDirEntry(src_cur_path), dst_cur_path)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
Module for restoring a backed-up snapshot (or a subset of its paths) to a
|
||||
destination directory.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from typing import Iterable, List, Optional, Tuple, Union
|
||||
|
||||
from curateipsum import backup, fs
|
||||
|
||||
_lg = logging.getLogger(__name__)
|
||||
|
||||
OVERWRITE_NEVER = "never"
|
||||
OVERWRITE_ALWAYS = "always"
|
||||
OVERWRITE_POLICIES = (OVERWRITE_NEVER, OVERWRITE_ALWAYS)
|
||||
|
||||
# Snapshot-root entries that are backup bookkeeping, not backed-up data,
|
||||
# and must never be copied out during a restore.
|
||||
_SNAPSHOT_INTERNAL_PREFIXES = (backup.BACKUP_MARKER, backup.DELTA_DIR)
|
||||
|
||||
|
||||
class RestoreError(Exception):
|
||||
"""Raised when a restore could not be completed safely or fully."""
|
||||
|
||||
|
||||
def _is_snapshot_internal(top_name: str) -> bool:
|
||||
return any(top_name.startswith(p) for p in _SNAPSHOT_INTERNAL_PREFIXES)
|
||||
|
||||
|
||||
def _under_any(relpath: str, rel_paths: List[str]) -> bool:
|
||||
return any(relpath == p or relpath.startswith(p + os.sep)
|
||||
for p in rel_paths)
|
||||
|
||||
|
||||
def plan_restore(
|
||||
snapshot_entry: Union[os.DirEntry, fs.PseudoDirEntry],
|
||||
rel_paths: Optional[List[str]] = None,
|
||||
) -> Iterable[Tuple[Union[os.DirEntry, fs.PseudoDirEntry], str]]:
|
||||
"""
|
||||
Yield (entry, relpath) pairs a restore would copy, directories before
|
||||
their contents (fs.scantree's default order, which copy_direntry()
|
||||
depends on so a directory exists before anything is written into it).
|
||||
Skips snapshot-internal bookkeeping entries (backup marker, delta
|
||||
dir). If rel_paths is given, only entries at or under one of those
|
||||
snapshot-relative paths are included.
|
||||
|
||||
A generator rather than a list: fs.scantree() already streams, and a
|
||||
snapshot can hold far more entries than comfortably fit in memory at
|
||||
once.
|
||||
"""
|
||||
for entry in fs.scantree(snapshot_entry.path):
|
||||
relpath = os.path.relpath(entry.path, snapshot_entry.path)
|
||||
top_name = relpath.split(os.sep, 1)[0]
|
||||
if _is_snapshot_internal(top_name):
|
||||
continue
|
||||
if rel_paths is not None and not _under_any(relpath, rel_paths):
|
||||
continue
|
||||
yield entry, relpath
|
||||
|
||||
|
||||
def restore_snapshot(
|
||||
snapshot_entry: Union[os.DirEntry, fs.PseudoDirEntry],
|
||||
dest_dir: str,
|
||||
dry_run: bool = False,
|
||||
overwrite: str = OVERWRITE_NEVER,
|
||||
rel_paths: Optional[List[str]] = None,
|
||||
) -> List[str]:
|
||||
"""
|
||||
Restore a completed snapshot (or a subset of its paths) into dest_dir.
|
||||
|
||||
:param overwrite: "never" (default) leaves any destination path that
|
||||
already exists untouched and reports it as skipped; "always"
|
||||
removes and replaces it.
|
||||
:param rel_paths: restrict the restore to these snapshot-relative
|
||||
paths (and anything nested under them); default restores
|
||||
everything in the snapshot.
|
||||
:return: relative paths that already existed at dest_dir under
|
||||
overwrite="never" - skipped for real, or (on dry_run) reported as
|
||||
what would be skipped.
|
||||
:raises RestoreError: if the snapshot has no manifest, dest_dir is
|
||||
inside the snapshot being restored, a destination path would
|
||||
resolve outside dest_dir (e.g. via a symlinked parent directory),
|
||||
or a copy fails partway through (the destination is left as-is;
|
||||
already-restored paths are not rolled back).
|
||||
"""
|
||||
if overwrite not in OVERWRITE_POLICIES:
|
||||
raise ValueError("Unknown overwrite policy: %r" % overwrite)
|
||||
|
||||
manifest = backup._read_manifest(
|
||||
backup._get_backup_marker(snapshot_entry).path)
|
||||
# A pre-migration (_LEGACY_MANIFEST) marker carries no checksums or
|
||||
# excluded-entries record, but the snapshot data itself is still
|
||||
# restorable - only verify_restored() needs real manifest content.
|
||||
if manifest is None:
|
||||
raise RestoreError(
|
||||
"Cannot restore %s: missing or corrupt manifest"
|
||||
% snapshot_entry.name
|
||||
)
|
||||
|
||||
dest_canon = backup._canonical(dest_dir)
|
||||
snapshot_canon = backup._canonical(snapshot_entry.path)
|
||||
if backup._is_same_or_within(dest_canon, snapshot_canon):
|
||||
raise RestoreError(
|
||||
"Refusing to restore %s into itself (destination %s is inside "
|
||||
"the snapshot)" % (snapshot_entry.name, dest_dir)
|
||||
)
|
||||
|
||||
skipped = []
|
||||
for entry, relpath in plan_restore(snapshot_entry, rel_paths):
|
||||
dst_path = os.path.join(dest_dir, relpath)
|
||||
# A symlink planted under dest_dir (by another process, or left
|
||||
# over from a previous run) could otherwise redirect lexists(),
|
||||
# rm_direntry(), or copy_direntry() below to write, delete, or
|
||||
# read through it, outside dest_dir entirely.
|
||||
dst_canon = backup._canonical(dst_path)
|
||||
if not backup._is_same_or_within(dst_canon, dest_canon):
|
||||
raise RestoreError(
|
||||
"Refusing to restore %s: resolves outside destination "
|
||||
"%s (a parent path component may be a symlink)"
|
||||
% (relpath, dest_dir)
|
||||
)
|
||||
exists = os.path.lexists(dst_path)
|
||||
if exists and overwrite == OVERWRITE_NEVER:
|
||||
_lg.info("Skipping existing %s (overwrite=%s)",
|
||||
relpath, OVERWRITE_NEVER)
|
||||
skipped.append(relpath)
|
||||
continue
|
||||
if dry_run:
|
||||
_lg.info("Would restore %s -> %s", relpath, dst_path)
|
||||
continue
|
||||
if exists:
|
||||
fs.rm_direntry(fs.PseudoDirEntry(dst_path))
|
||||
parent = os.path.dirname(dst_path)
|
||||
if parent and not os.path.isdir(parent):
|
||||
os.makedirs(parent, exist_ok=True)
|
||||
try:
|
||||
fs.copy_direntry(entry, dst_path)
|
||||
except (OSError, fs.BackupCreationError) as err:
|
||||
raise RestoreError(
|
||||
"Failed to restore %s: %s" % (relpath, err)
|
||||
) from err
|
||||
|
||||
return skipped
|
||||
|
||||
|
||||
def verify_restored(
|
||||
snapshot_entry: Union[os.DirEntry, fs.PseudoDirEntry],
|
||||
dest_dir: str,
|
||||
rel_paths: Optional[List[str]] = None,
|
||||
) -> List[str]:
|
||||
"""
|
||||
Verify restored file content at dest_dir against the checksums the
|
||||
snapshot's manifest recorded at backup time. Mirrors
|
||||
backup.verify_snapshot(), but against an arbitrary restore
|
||||
destination rather than the snapshot directory itself.
|
||||
|
||||
:return: relative paths whose restored content doesn't match the
|
||||
recorded checksum, or is missing. Empty means verified OK.
|
||||
:raises RestoreError: if the manifest itself is missing or corrupt.
|
||||
"""
|
||||
manifest = backup._read_manifest(
|
||||
backup._get_backup_marker(snapshot_entry).path)
|
||||
if manifest is None or manifest is backup._LEGACY_MANIFEST:
|
||||
raise RestoreError(
|
||||
"Cannot verify %s: missing, corrupt, or pre-migration manifest"
|
||||
% snapshot_entry.name
|
||||
)
|
||||
|
||||
dest_canon = backup._canonical(dest_dir)
|
||||
mismatches = []
|
||||
for relpath, expected_digest in manifest.get("checksums", {}).items():
|
||||
if rel_paths is not None and not _under_any(relpath, rel_paths):
|
||||
continue
|
||||
full_path = os.path.join(dest_dir, relpath)
|
||||
# Same symlink-escape concern as restore_snapshot(): don't let a
|
||||
# planted symlink under dest_dir make this hash a file outside it.
|
||||
full_canon = backup._canonical(full_path)
|
||||
if not backup._is_same_or_within(full_canon, dest_canon):
|
||||
_lg.error("Refusing to verify %s: resolves outside "
|
||||
"destination %s", relpath, dest_dir)
|
||||
mismatches.append(relpath)
|
||||
continue
|
||||
try:
|
||||
actual_digest = backup._sha256_file(full_path)
|
||||
except OSError:
|
||||
mismatches.append(relpath)
|
||||
continue
|
||||
if actual_digest != expected_digest:
|
||||
mismatches.append(relpath)
|
||||
return mismatches
|
||||
@@ -0,0 +1,41 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64", "setuptools_scm>=8"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "cura-te-ipsum"
|
||||
dynamic = ["version"]
|
||||
description = "Backup utility"
|
||||
authors = [
|
||||
{name = "Maks Snegov", email = "snegov@spqr.link"}
|
||||
]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
classifiers = [
|
||||
"Development Status :: 2 - Pre-Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: System Administrators",
|
||||
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Topic :: System :: Archiving :: Backup",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/snegov/cura-te-ipsum"
|
||||
"Bug Tracker" = "https://github.com/snegov/cura-te-ipsum/issues"
|
||||
GitHub = "https://github.com/snegov/cura-te-ipsum"
|
||||
|
||||
[project.scripts]
|
||||
cura-te-ipsum = "curateipsum.cli:main"
|
||||
|
||||
[tool.setuptools]
|
||||
packages = ["curateipsum"]
|
||||
|
||||
[tool.setuptools_scm]
|
||||
version_file = "curateipsum/_version.py"
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=7.0.1",
|
||||
]
|
||||
@@ -1 +0,0 @@
|
||||
pytest
|
||||
@@ -1,48 +1,5 @@
|
||||
import setuptools
|
||||
import subprocess
|
||||
# Minimal setup.py for backwards compatibility
|
||||
# All configuration is in pyproject.toml
|
||||
from setuptools import setup
|
||||
|
||||
|
||||
def get_version_from_vcs():
|
||||
ret_code, git_ver = subprocess.getstatusoutput("git describe")
|
||||
if ret_code != 0:
|
||||
from curateipsum._version import version
|
||||
return version
|
||||
|
||||
with open("curateipsum/_version.py", "w") as fd:
|
||||
fd.write("version = \"%s\"\n" % git_ver)
|
||||
return git_ver
|
||||
|
||||
|
||||
with open("README.md", "r", encoding="utf-8") as fh:
|
||||
long_description = fh.read()
|
||||
|
||||
setuptools.setup(
|
||||
name="cura-te-ipsum",
|
||||
version=get_version_from_vcs(),
|
||||
author="Maks Snegov",
|
||||
author_email="snegov@spqr.link",
|
||||
url="https://github.com/snegov/cura-te-ipsum",
|
||||
description="Backup utility",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
project_urls={
|
||||
"Bug Tracker": "https://github.com/snegov/cura-te-ipsum/issues",
|
||||
"GitHub": "https://github.com/snegov/cura-te-ipsum",
|
||||
},
|
||||
classifiers=[
|
||||
"Development Status :: 2 - Pre-Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: System Administrators",
|
||||
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Topic :: System :: Archiving :: Backup",
|
||||
],
|
||||
packages=setuptools.find_packages(include=["curateipsum"]),
|
||||
entry_points={
|
||||
"console_scripts": [
|
||||
"cura-te-ipsum = curateipsum.cli:main",
|
||||
],
|
||||
},
|
||||
python_requires=">=3.6",
|
||||
)
|
||||
setup()
|
||||
@@ -0,0 +1,134 @@
|
||||
"""Shared pytest fixtures for cura-te-ipsum tests."""
|
||||
import os
|
||||
import random
|
||||
import string
|
||||
import tempfile
|
||||
import pytest
|
||||
|
||||
from curateipsum import backup as bk, fs
|
||||
|
||||
|
||||
# Shared helper functions for fs tests
|
||||
def create_file(parent_dir: str, prefix: str = None) -> str:
|
||||
"""
|
||||
Create a file with random name in parent_dir.
|
||||
Returns absolute path to the created file.
|
||||
"""
|
||||
fd, path = tempfile.mkstemp(prefix=prefix, dir=parent_dir)
|
||||
with open(fd, "w") as f:
|
||||
f.write(string.printable)
|
||||
return path
|
||||
|
||||
|
||||
def create_dir(parent_dir: str, prefix: str = None) -> str:
|
||||
"""
|
||||
Create a directory with random name in parent_dir.
|
||||
Returns absolute path to created directory.
|
||||
"""
|
||||
return tempfile.mkdtemp(prefix=prefix, dir=parent_dir)
|
||||
|
||||
|
||||
def relpath(full_path: str, src_dir: str, dst_dir: str) -> str:
|
||||
"""Get a relative path for entity in src/dst dirs."""
|
||||
if full_path.startswith(src_dir):
|
||||
p_dir = src_dir
|
||||
elif full_path.startswith(dst_dir):
|
||||
p_dir = dst_dir
|
||||
else:
|
||||
raise RuntimeError(f"Path {full_path} is not src_dir nor dst_dir")
|
||||
|
||||
return full_path[len(p_dir) + 1:]
|
||||
|
||||
|
||||
def check_identical_file(f1_path: str, f2_path: str):
|
||||
"""Check that files are identical. Fails test, if not."""
|
||||
st1 = os.lstat(f1_path)
|
||||
st2 = os.lstat(f2_path)
|
||||
|
||||
assert st1.st_uid == st2.st_uid
|
||||
assert st1.st_gid == st2.st_gid
|
||||
assert st1.st_mode == st2.st_mode
|
||||
assert st1.st_mtime == st2.st_mtime
|
||||
assert st1.st_size == st2.st_size
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def common_fs_dirs(tmp_path):
|
||||
"""Create source and destination directories for tests."""
|
||||
src_dir = tmp_path / "source"
|
||||
dst_dir = tmp_path / "dest"
|
||||
src_dir.mkdir()
|
||||
dst_dir.mkdir()
|
||||
return src_dir, dst_dir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def backup_dir(tmp_path):
|
||||
"""Provide a temporary backup directory."""
|
||||
return tmp_path / "backups"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def source_dir(tmp_path):
|
||||
"""Provide a temporary source directory."""
|
||||
src = tmp_path / "source"
|
||||
src.mkdir()
|
||||
return src
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def add_backup(backup_dir):
|
||||
"""Factory fixture for creating test backups."""
|
||||
backup_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _add_backup(backup_name: str) -> fs.PseudoDirEntry:
|
||||
backup = fs.PseudoDirEntry(os.path.join(str(backup_dir), backup_name))
|
||||
os.mkdir(backup.path)
|
||||
bk.set_backup_marker(backup)
|
||||
|
||||
fd, path = tempfile.mkstemp(prefix="backup_file_", dir=backup.path)
|
||||
with open(fd, "w") as f:
|
||||
f.write(''.join(random.choices(string.printable, k=128)))
|
||||
return backup
|
||||
|
||||
return _add_backup
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def check_backup_not_empty():
|
||||
"""Helper to verify backup is not empty."""
|
||||
def _check(backup: fs.PseudoDirEntry) -> bool:
|
||||
return bool(os.listdir(backup.path))
|
||||
return _check
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def check_backups(backup_dir, check_backup_not_empty):
|
||||
"""Helper to verify expected backups exist."""
|
||||
def _check(expected_backups):
|
||||
backups_list = [
|
||||
name for name in os.listdir(str(backup_dir))
|
||||
if name != bk.REPO_ID_FILE
|
||||
]
|
||||
assert sorted(b.name for b in expected_backups) == sorted(backups_list)
|
||||
for b in expected_backups:
|
||||
assert check_backup_not_empty(b)
|
||||
return _check
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run_cleanup(backup_dir):
|
||||
"""Helper to run cleanup_old_backups with default parameters."""
|
||||
def _run(**kwargs):
|
||||
cleanup_kwargs = {
|
||||
"backups_dir": str(backup_dir),
|
||||
"dry_run": False,
|
||||
"keep_all": None,
|
||||
"keep_daily": None,
|
||||
"keep_weekly": None,
|
||||
"keep_monthly": None,
|
||||
"keep_yearly": None,
|
||||
}
|
||||
cleanup_kwargs.update(**kwargs)
|
||||
bk.cleanup_old_backups(**cleanup_kwargs)
|
||||
return _run
|
||||
+919
-148
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,744 @@
|
||||
"""Tests for CLI module (cli.py)."""
|
||||
|
||||
import sys
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from curateipsum import cli
|
||||
|
||||
|
||||
class TestArgumentParsing:
|
||||
"""Test command-line argument parsing."""
|
||||
|
||||
def test_requires_backups_dir(self):
|
||||
"""Should fail when -b flag is missing."""
|
||||
with pytest.raises(SystemExit):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '/src1']):
|
||||
with mock.patch('argparse.ArgumentParser.parse_args') as m:
|
||||
m.side_effect = SystemExit(2)
|
||||
cli.main()
|
||||
|
||||
def test_requires_at_least_one_source(self):
|
||||
"""Should fail when no sources are provided."""
|
||||
with pytest.raises(SystemExit):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b', '/backups']):
|
||||
with mock.patch('argparse.ArgumentParser.parse_args') as m:
|
||||
m.side_effect = SystemExit(2)
|
||||
cli.main()
|
||||
|
||||
def test_parses_single_source(self, tmp_path):
|
||||
"""Should parse single source directory."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
|
||||
def test_parses_multiple_sources(self, tmp_path):
|
||||
"""Should parse multiple source directories."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
src1 = tmp_path / "src1"
|
||||
src1.mkdir()
|
||||
src2 = tmp_path / "src2"
|
||||
src2.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(src1), str(src2)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup') \
|
||||
as m_init:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
m_init.assert_called_once()
|
||||
call_args = m_init.call_args
|
||||
assert call_args.kwargs['sources'] == [str(src1), str(src2)]
|
||||
|
||||
def test_verbose_flag_sets_debug_logging(self, tmp_path):
|
||||
"""Should enable DEBUG logging when --verbose is set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--verbose']):
|
||||
with mock.patch('logging.basicConfig') as m_logging:
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
import logging
|
||||
m_logging.assert_called_once()
|
||||
assert m_logging.call_args.kwargs['level'] == logging.DEBUG
|
||||
|
||||
def test_dry_run_flag_passed_to_backup(self, tmp_path):
|
||||
"""Should pass dry_run=True when --dry-run is set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--dry-run']):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups') \
|
||||
as m_cleanup:
|
||||
with mock.patch('curateipsum.backup.initiate_backup') \
|
||||
as m_init:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
assert m_cleanup.call_args.kwargs['dry_run'] is True
|
||||
assert m_init.call_args.kwargs['dry_run'] is True
|
||||
|
||||
def test_dry_run_does_not_acquire_lock(self, tmp_path):
|
||||
"""
|
||||
A dry-run must not take the backups lock at all - set_backups_lock()
|
||||
writes PID/timestamp metadata to the lock file, which is itself a
|
||||
mutation a dry-run must never make.
|
||||
"""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--dry-run']):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock') \
|
||||
as m_lock:
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock') \
|
||||
as m_release:
|
||||
cli.main()
|
||||
|
||||
m_lock.assert_not_called()
|
||||
m_release.assert_not_called()
|
||||
|
||||
def test_force_flag_passed_to_lock(self, tmp_path):
|
||||
"""Should pass force=True to set_backups_lock when --force is set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--force']):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True) as m_lock:
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
m_lock.assert_called_once_with(str(backups_dir), True)
|
||||
|
||||
def test_external_rsync_flag_passed_to_backup(self, tmp_path):
|
||||
"""Should pass external_rsync=True when --external-rsync is set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--external-rsync']):
|
||||
with mock.patch('shutil.which', return_value='/usr/bin/rsync'):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup') \
|
||||
as m_init:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
assert m_init.call_args.kwargs['external_rsync'] is True
|
||||
|
||||
def test_external_hardlink_flag_passed_to_backup(self, tmp_path):
|
||||
"""Should pass external_hardlink=True when --external-hardlink is
|
||||
set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--external-hardlink']):
|
||||
with mock.patch('shutil.which', return_value='/usr/bin/cp'):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup') \
|
||||
as m_init:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
assert m_init.call_args.kwargs['external_hardlink'] is True
|
||||
|
||||
|
||||
class TestPlatformValidation:
|
||||
"""Test platform-specific checks."""
|
||||
|
||||
def test_allows_linux_platform(self, tmp_path):
|
||||
"""Should allow execution on Linux."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'linux'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
|
||||
def test_allows_darwin_platform(self, tmp_path):
|
||||
"""Should allow execution on macOS (darwin)."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'darwin'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
|
||||
def test_rejects_windows_platform(self, tmp_path):
|
||||
"""Should reject Windows platform."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'win32'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_rejects_unsupported_platform(self, tmp_path):
|
||||
"""Should reject unsupported platforms."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'freebsd'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
|
||||
class TestExternalToolValidation:
|
||||
"""Test validation of external tool availability."""
|
||||
|
||||
def test_requires_rsync_when_external_rsync_enabled(self, tmp_path):
|
||||
"""Should fail when rsync is missing and --external-rsync is set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--external-rsync']):
|
||||
with mock.patch('shutil.which', return_value=None):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_requires_cp_on_linux_when_external_hardlink_enabled(
|
||||
self, tmp_path):
|
||||
"""Should fail when cp is missing on Linux and --external-hardlink is
|
||||
set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'linux'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--external-hardlink']):
|
||||
with mock.patch('shutil.which', return_value=None):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_requires_gcp_on_darwin_when_external_hardlink_enabled(
|
||||
self, tmp_path):
|
||||
"""Should fail when gcp is missing on macOS and --external-hardlink is
|
||||
set."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'darwin'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--external-hardlink']):
|
||||
with mock.patch('shutil.which', return_value=None):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_checks_correct_tool_on_darwin(self, tmp_path):
|
||||
"""Should check for gcp (not cp) on macOS."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.platform', 'darwin'):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source),
|
||||
'--external-hardlink']):
|
||||
with mock.patch('shutil.which',
|
||||
side_effect=lambda x: '/usr/bin/gcp'
|
||||
if x == 'gcp' else None):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
|
||||
|
||||
class TestDirectoryValidation:
|
||||
"""Test validation of backup and source directories."""
|
||||
|
||||
def test_fails_when_backups_dir_missing(self, tmp_path):
|
||||
"""Should fail when backup directory doesn't exist."""
|
||||
backups_dir = tmp_path / "nonexistent"
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_fails_when_source_dir_missing(self, tmp_path):
|
||||
"""Should fail when source directory doesn't exist."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "nonexistent"
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_fails_when_any_source_dir_missing(self, tmp_path):
|
||||
"""Should fail when any source directory doesn't exist."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
src1 = tmp_path / "src1"
|
||||
src1.mkdir()
|
||||
src2 = tmp_path / "nonexistent"
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(src1), str(src2)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_converts_backups_dir_to_absolute_path(self, tmp_path):
|
||||
"""Should convert relative backup directory path to absolute."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('os.getcwd', return_value=str(tmp_path)):
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b', 'backups',
|
||||
str(source)]):
|
||||
with mock.patch('os.path.isdir', return_value=True):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True) as m_lock:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
m_lock.assert_called_once_with(str(backups_dir), False)
|
||||
|
||||
|
||||
class TestLockHandling:
|
||||
"""Test backup lock acquisition and release."""
|
||||
|
||||
def test_exits_when_lock_acquisition_fails(self, tmp_path):
|
||||
"""Should exit with code 1 when lock cannot be acquired."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=False):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_releases_lock_after_successful_backup(self, tmp_path):
|
||||
"""Should release lock after backup completes."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock') \
|
||||
as m_release:
|
||||
cli.main()
|
||||
|
||||
m_release.assert_called_once_with(str(backups_dir))
|
||||
|
||||
def test_releases_lock_and_exits_nonzero_after_failed_backup(
|
||||
self, tmp_path):
|
||||
"""Should still release lock and return nonzero exit code when
|
||||
initiate_backup raises BackupFailedError."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
from curateipsum import backup
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.initiate_backup',
|
||||
side_effect=backup.BackupFailedError("boom")):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock') \
|
||||
as m_release:
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
m_release.assert_called_once_with(str(backups_dir))
|
||||
|
||||
def test_skips_cleanup_when_backup_fails(self, tmp_path):
|
||||
"""
|
||||
A failed backup must prevent every retention deletion: if
|
||||
initiate_backup raises, cleanup_old_backups must never run.
|
||||
"""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
from curateipsum import backup
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.cleanup_old_backups') \
|
||||
as m_cleanup:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.initiate_backup',
|
||||
side_effect=backup.BackupFailedError("boom")):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
m_cleanup.assert_not_called()
|
||||
|
||||
|
||||
class TestBackupExecution:
|
||||
"""Test backup execution flow."""
|
||||
|
||||
def test_calls_initiate_before_cleanup(self, tmp_path):
|
||||
"""
|
||||
Should call initiate_backup before cleanup_old_backups: retention
|
||||
deletes old snapshots, so it must only run once the new snapshot
|
||||
is durable, never before it.
|
||||
"""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
call_order = []
|
||||
|
||||
def mock_cleanup(**kwargs):
|
||||
call_order.append('cleanup')
|
||||
|
||||
def mock_initiate(**kwargs):
|
||||
call_order.append('initiate')
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups',
|
||||
side_effect=mock_cleanup):
|
||||
with mock.patch('curateipsum.backup.initiate_backup',
|
||||
side_effect=mock_initiate):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
assert call_order == ['initiate', 'cleanup']
|
||||
|
||||
def test_passes_correct_arguments_to_initiate_backup(self, tmp_path):
|
||||
"""Should pass all required arguments to initiate_backup."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
src1 = tmp_path / "src1"
|
||||
src1.mkdir()
|
||||
src2 = tmp_path / "src2"
|
||||
src2.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(src1), str(src2),
|
||||
'--dry-run', '--external-rsync',
|
||||
'--external-hardlink']):
|
||||
with mock.patch('shutil.which', return_value='/usr/bin/tool'):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup') \
|
||||
as m_init:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
m_init.assert_called_once_with(
|
||||
sources=[str(src1), str(src2)],
|
||||
backups_dir=str(backups_dir),
|
||||
dry_run=True,
|
||||
external_rsync=True,
|
||||
external_hardlink=True,
|
||||
)
|
||||
|
||||
def test_logs_completion_time(self, tmp_path, caplog):
|
||||
"""Should log time spent after backup completes."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
import logging
|
||||
caplog.set_level(logging.INFO)
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch('curateipsum.backup.initiate_backup'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
cli.main()
|
||||
|
||||
# check that completion message was logged
|
||||
assert any("Finished" in record.message for record in caplog.records)
|
||||
assert any("time spent" in record.message
|
||||
for record in caplog.records)
|
||||
|
||||
|
||||
class TestRestoreSubcommand:
|
||||
"""End-to-end tests for `cura-te-ipsum restore`, against a real
|
||||
snapshot on disk - restore's file operations are cheap enough that
|
||||
mocking them out would just be testing the mocks."""
|
||||
|
||||
def _make_backup(self, backups_dir, source):
|
||||
from curateipsum import backup as bk
|
||||
(source / "file1.txt").write_text("content1")
|
||||
entry = bk.initiate_backup(sources=[str(source)],
|
||||
backups_dir=str(backups_dir))
|
||||
assert entry is not None
|
||||
return entry
|
||||
|
||||
def test_restore_copies_snapshot_to_dest(self, tmp_path):
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
self._make_backup(backups_dir, source)
|
||||
|
||||
dest = tmp_path / "dest"
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', 'restore', '-b',
|
||||
str(backups_dir), str(dest)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
restored = dest / "src" / "file1.txt"
|
||||
assert restored.read_text() == "content1"
|
||||
|
||||
def test_restore_unknown_backups_dir_fails(self, tmp_path):
|
||||
dest = tmp_path / "dest"
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', 'restore', '-b',
|
||||
str(tmp_path / "nope"), str(dest)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_restore_unknown_snapshot_fails(self, tmp_path):
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
self._make_backup(backups_dir, source)
|
||||
|
||||
dest = tmp_path / "dest"
|
||||
with mock.patch('sys.argv', [
|
||||
'cura-te-ipsum', 'restore', '-b', str(backups_dir),
|
||||
'--snapshot', '20000101_000000', str(dest)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 1
|
||||
|
||||
def test_restore_dry_run_creates_nothing(self, tmp_path):
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
self._make_backup(backups_dir, source)
|
||||
|
||||
dest = tmp_path / "dest"
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', 'restore', '-b',
|
||||
str(backups_dir), '-n', str(dest)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
assert not dest.exists()
|
||||
|
||||
def test_restore_dry_run_does_not_acquire_lock(self, tmp_path):
|
||||
"""
|
||||
Mirrors TestMain.test_dry_run_does_not_acquire_lock for restore:
|
||||
restore --dry-run must not touch the lock either.
|
||||
"""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
self._make_backup(backups_dir, source)
|
||||
|
||||
dest = tmp_path / "dest"
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', 'restore', '-b',
|
||||
str(backups_dir), '-n', str(dest)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock') \
|
||||
as m_lock:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock') \
|
||||
as m_release:
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
m_lock.assert_not_called()
|
||||
m_release.assert_not_called()
|
||||
|
||||
def test_restore_verify_passes_after_clean_restore(self, tmp_path):
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
self._make_backup(backups_dir, source)
|
||||
|
||||
dest = tmp_path / "dest"
|
||||
with mock.patch('sys.argv', [
|
||||
'cura-te-ipsum', 'restore', '-b', str(backups_dir),
|
||||
'--verify', str(dest)]):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
|
||||
def test_backup_subcommand_still_explicit(self, tmp_path):
|
||||
"""`cura-te-ipsum backup -b ... SRC` works the same as the
|
||||
implicit form."""
|
||||
backups_dir = tmp_path / "backups"
|
||||
backups_dir.mkdir()
|
||||
source = tmp_path / "src"
|
||||
source.mkdir()
|
||||
|
||||
with mock.patch('sys.argv', ['cura-te-ipsum', 'backup', '-b',
|
||||
str(backups_dir), str(source)]):
|
||||
with mock.patch('curateipsum.backup.set_backups_lock',
|
||||
return_value=True):
|
||||
with mock.patch('curateipsum.backup.cleanup_old_backups'):
|
||||
with mock.patch(
|
||||
'curateipsum.backup.initiate_backup') as m_init:
|
||||
with mock.patch(
|
||||
'curateipsum.backup.release_backups_lock'):
|
||||
result = cli.main()
|
||||
|
||||
assert result == 0
|
||||
assert m_init.call_args.kwargs['sources'] == [str(source)]
|
||||
+738
-202
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,277 @@
|
||||
"""Tests for PseudoDirEntry class."""
|
||||
import os
|
||||
|
||||
from curateipsum import fs
|
||||
|
||||
|
||||
class TestPseudoDirEntry:
|
||||
"""Test PseudoDirEntry class behavior, especially follow_symlinks handling."""
|
||||
|
||||
def test_regular_file_is_file(self, tmp_path):
|
||||
"""Regular file should report as file, not dir or symlink."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
filepath.write_text("test")
|
||||
|
||||
entry = fs.PseudoDirEntry(str(filepath))
|
||||
|
||||
assert entry.is_file(follow_symlinks=True)
|
||||
assert entry.is_file(follow_symlinks=False)
|
||||
assert not entry.is_dir(follow_symlinks=True)
|
||||
assert not entry.is_dir(follow_symlinks=False)
|
||||
assert not entry.is_symlink()
|
||||
|
||||
def test_regular_dir_is_dir(self, tmp_path):
|
||||
"""Regular directory should report as dir, not file or symlink."""
|
||||
dirpath = tmp_path / "testdir"
|
||||
dirpath.mkdir()
|
||||
|
||||
entry = fs.PseudoDirEntry(str(dirpath))
|
||||
|
||||
assert entry.is_dir(follow_symlinks=True)
|
||||
assert entry.is_dir(follow_symlinks=False)
|
||||
assert not entry.is_file(follow_symlinks=True)
|
||||
assert not entry.is_file(follow_symlinks=False)
|
||||
assert not entry.is_symlink()
|
||||
|
||||
def test_symlink_to_file_follow_true(self, tmp_path):
|
||||
"""Symlink to file with follow_symlinks=True should report as file."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
assert entry.is_file(follow_symlinks=True)
|
||||
assert entry.is_symlink()
|
||||
|
||||
def test_symlink_to_file_follow_false(self, tmp_path):
|
||||
"""Symlink to file with follow_symlinks=False should not report as file."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
assert not entry.is_file(follow_symlinks=False)
|
||||
assert not entry.is_dir(follow_symlinks=False)
|
||||
assert entry.is_symlink()
|
||||
|
||||
def test_symlink_to_dir_follow_true(self, tmp_path):
|
||||
"""Symlink to dir with follow_symlinks=True should report as dir."""
|
||||
dirpath = tmp_path / "testdir"
|
||||
linkpath = tmp_path / "linkdir"
|
||||
dirpath.mkdir()
|
||||
linkpath.symlink_to(dirpath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
assert entry.is_dir(follow_symlinks=True)
|
||||
assert entry.is_symlink()
|
||||
|
||||
def test_symlink_to_dir_follow_false(self, tmp_path):
|
||||
"""Symlink to dir with follow_symlinks=False should not report as dir."""
|
||||
dirpath = tmp_path / "testdir"
|
||||
linkpath = tmp_path / "linkdir"
|
||||
dirpath.mkdir()
|
||||
linkpath.symlink_to(dirpath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
assert not entry.is_dir(follow_symlinks=False)
|
||||
assert not entry.is_file(follow_symlinks=False)
|
||||
assert entry.is_symlink()
|
||||
|
||||
def test_matches_real_direntry_file(self, tmp_path):
|
||||
"""PseudoDirEntry should match real DirEntry for regular file."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
filepath.write_text("test")
|
||||
|
||||
pseudo = fs.PseudoDirEntry(str(filepath))
|
||||
real = next(os.scandir(tmp_path))
|
||||
|
||||
assert pseudo.is_file(follow_symlinks=True) == real.is_file(follow_symlinks=True)
|
||||
assert pseudo.is_file(follow_symlinks=False) == real.is_file(follow_symlinks=False)
|
||||
assert pseudo.is_dir(follow_symlinks=True) == real.is_dir(follow_symlinks=True)
|
||||
assert pseudo.is_dir(follow_symlinks=False) == real.is_dir(follow_symlinks=False)
|
||||
assert pseudo.is_symlink() == real.is_symlink()
|
||||
|
||||
def test_matches_real_direntry_symlink(self, tmp_path):
|
||||
"""PseudoDirEntry should match real DirEntry for symlink."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
pseudo = fs.PseudoDirEntry(str(linkpath))
|
||||
real = [e for e in os.scandir(tmp_path) if e.name == "link.txt"][0]
|
||||
|
||||
assert pseudo.is_file(follow_symlinks=True) == real.is_file(follow_symlinks=True)
|
||||
assert pseudo.is_file(follow_symlinks=False) == real.is_file(follow_symlinks=False)
|
||||
assert pseudo.is_dir(follow_symlinks=True) == real.is_dir(follow_symlinks=True)
|
||||
assert pseudo.is_dir(follow_symlinks=False) == real.is_dir(follow_symlinks=False)
|
||||
assert pseudo.is_symlink() == real.is_symlink()
|
||||
|
||||
def test_stat_follow_symlinks_true(self, tmp_path):
|
||||
"""stat(follow_symlinks=True) should return target's stat."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test content")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
stat_result = entry.stat(follow_symlinks=True)
|
||||
|
||||
# should return file's size, not symlink size
|
||||
assert stat_result.st_size == 12
|
||||
|
||||
def test_stat_follow_symlinks_false(self, tmp_path):
|
||||
"""stat(follow_symlinks=False) should return symlink's stat."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test content")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
stat_result = entry.stat(follow_symlinks=False)
|
||||
|
||||
# should return symlink size, not file size
|
||||
assert stat_result.st_size != 12
|
||||
|
||||
def test_stat_caching_separate(self, tmp_path):
|
||||
"""stat() should cache follow_symlinks=True/False separately."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test content")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
stat_follow = entry.stat(follow_symlinks=True)
|
||||
stat_nofollow = entry.stat(follow_symlinks=False)
|
||||
|
||||
# should return different results
|
||||
assert stat_follow.st_size == 12
|
||||
assert stat_nofollow.st_size != 12
|
||||
|
||||
# call again to verify caching works
|
||||
assert entry.stat(follow_symlinks=True).st_size == 12
|
||||
assert entry.stat(follow_symlinks=False).st_size != 12
|
||||
|
||||
def test_name_and_path_attributes(self, tmp_path):
|
||||
"""Test that name and path attributes are set correctly."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
filepath.write_text("test")
|
||||
|
||||
entry = fs.PseudoDirEntry(str(filepath))
|
||||
|
||||
assert entry.name == "file.txt"
|
||||
assert entry.path == str(filepath)
|
||||
|
||||
def test_str_representation(self, tmp_path):
|
||||
"""__str__ should return name."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
filepath.write_text("test")
|
||||
|
||||
entry = fs.PseudoDirEntry(str(filepath))
|
||||
|
||||
assert str(entry) == "file.txt"
|
||||
|
||||
def test_abspath_not_realpath(self, tmp_path):
|
||||
"""Constructor should use abspath, not realpath (preserves symlinks)."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
# path should point to symlink, not resolved target
|
||||
assert entry.path == str(linkpath)
|
||||
assert entry.name == "link.txt"
|
||||
assert entry.is_symlink()
|
||||
|
||||
def test_caching_is_dir(self, tmp_path):
|
||||
"""is_dir() should cache result for follow_symlinks=True."""
|
||||
dirpath = tmp_path / "testdir"
|
||||
dirpath.mkdir()
|
||||
|
||||
entry = fs.PseudoDirEntry(str(dirpath))
|
||||
|
||||
# first call caches
|
||||
assert entry.is_dir(follow_symlinks=True)
|
||||
assert entry._is_dir is True
|
||||
|
||||
# second call uses cache
|
||||
assert entry.is_dir(follow_symlinks=True)
|
||||
|
||||
def test_caching_is_file(self, tmp_path):
|
||||
"""is_file() should cache result for follow_symlinks=True."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
filepath.write_text("test")
|
||||
|
||||
entry = fs.PseudoDirEntry(str(filepath))
|
||||
|
||||
# first call caches
|
||||
assert entry.is_file(follow_symlinks=True)
|
||||
assert entry._is_file is True
|
||||
|
||||
# second call uses cache
|
||||
assert entry.is_file(follow_symlinks=True)
|
||||
|
||||
def test_caching_is_symlink(self, tmp_path):
|
||||
"""is_symlink() should cache result."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
linkpath = tmp_path / "link.txt"
|
||||
filepath.write_text("test")
|
||||
linkpath.symlink_to(filepath)
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
# first call caches
|
||||
assert entry.is_symlink()
|
||||
assert entry._is_symlink is True
|
||||
|
||||
# second call uses cache
|
||||
assert entry.is_symlink()
|
||||
|
||||
def test_broken_symlink_is_symlink(self, tmp_path):
|
||||
"""Broken symlink should still be detected as symlink."""
|
||||
linkpath = tmp_path / "broken_link"
|
||||
linkpath.symlink_to("/nonexistent/path")
|
||||
|
||||
entry = fs.PseudoDirEntry(str(linkpath))
|
||||
|
||||
assert entry.is_symlink()
|
||||
assert not entry.is_file(follow_symlinks=False)
|
||||
assert not entry.is_dir(follow_symlinks=False)
|
||||
|
||||
def test_relative_path_converted_to_absolute(self, tmp_path):
|
||||
"""Relative paths should be converted to absolute."""
|
||||
filepath = tmp_path / "file.txt"
|
||||
filepath.write_text("test")
|
||||
|
||||
# change to tmp_path and use relative path
|
||||
original_cwd = os.getcwd()
|
||||
try:
|
||||
os.chdir(tmp_path)
|
||||
entry = fs.PseudoDirEntry("file.txt")
|
||||
|
||||
assert os.path.isabs(entry.path)
|
||||
assert entry.name == "file.txt"
|
||||
finally:
|
||||
os.chdir(original_cwd)
|
||||
|
||||
def test_nonexistent_path_attributes(self, tmp_path):
|
||||
"""PseudoDirEntry should work for paths that don't exist yet."""
|
||||
filepath = tmp_path / "future_file.txt"
|
||||
|
||||
# path doesn't exist yet
|
||||
assert not filepath.exists()
|
||||
|
||||
entry = fs.PseudoDirEntry(str(filepath))
|
||||
|
||||
# should still have name and path attributes
|
||||
assert entry.name == "future_file.txt"
|
||||
assert entry.path == str(filepath)
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Tests for the restore module (restore.py)."""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from curateipsum import backup as bk
|
||||
from curateipsum import restore
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def restore_dirs(tmp_path):
|
||||
backups_dir = tmp_path / "backups"
|
||||
source_dir = tmp_path / "source"
|
||||
dest_dir = tmp_path / "dest"
|
||||
backups_dir.mkdir()
|
||||
source_dir.mkdir()
|
||||
return backups_dir, source_dir, dest_dir
|
||||
|
||||
|
||||
def _make_snapshot(backups_dir, source_dir):
|
||||
entry = bk.initiate_backup(
|
||||
sources=[str(source_dir)], backups_dir=str(backups_dir))
|
||||
assert entry is not None
|
||||
return bk.find_backup(str(backups_dir))
|
||||
|
||||
|
||||
class TestRestoreSnapshot:
|
||||
def test_restores_files_and_dirs(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "subdir").mkdir()
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
(source_dir / "subdir" / "file2.txt").write_text("content2")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
skipped = restore.restore_snapshot(snapshot, str(dest_dir))
|
||||
|
||||
assert skipped == []
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
restored_root = dest_dir / src_name
|
||||
assert (restored_root / "file1.txt").read_text() == "content1"
|
||||
assert (restored_root / "subdir" / "file2.txt").read_text() == (
|
||||
"content2")
|
||||
|
||||
def test_preserves_symlinks(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "real.txt").write_text("data")
|
||||
os.symlink("real.txt", str(source_dir / "link.txt"))
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
restore.restore_snapshot(snapshot, str(dest_dir))
|
||||
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
link_path = dest_dir / src_name / "link.txt"
|
||||
assert os.path.islink(str(link_path))
|
||||
assert os.readlink(str(link_path)) == "real.txt"
|
||||
|
||||
def test_excludes_snapshot_bookkeeping(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
restore.restore_snapshot(snapshot, str(dest_dir))
|
||||
|
||||
restored_names = os.listdir(str(dest_dir))
|
||||
assert bk.DELTA_DIR not in restored_names
|
||||
assert not any(n.startswith(bk.BACKUP_MARKER)
|
||||
for n in restored_names)
|
||||
|
||||
def test_overwrite_never_skips_existing(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("new-content")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
existing = dest_dir / src_name / "file1.txt"
|
||||
existing.parent.mkdir(parents=True)
|
||||
existing.write_text("old-content")
|
||||
|
||||
skipped = restore.restore_snapshot(
|
||||
snapshot, str(dest_dir), overwrite=restore.OVERWRITE_NEVER)
|
||||
|
||||
assert os.path.join(src_name, "file1.txt") in skipped
|
||||
assert existing.read_text() == "old-content"
|
||||
|
||||
def test_overwrite_always_replaces_existing(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("new-content")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
existing = dest_dir / src_name / "file1.txt"
|
||||
existing.parent.mkdir(parents=True)
|
||||
existing.write_text("old-content")
|
||||
|
||||
skipped = restore.restore_snapshot(
|
||||
snapshot, str(dest_dir), overwrite=restore.OVERWRITE_ALWAYS)
|
||||
|
||||
assert skipped == []
|
||||
assert existing.read_text() == "new-content"
|
||||
|
||||
def test_dry_run_writes_nothing(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
dest_dir.mkdir()
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
skipped = restore.restore_snapshot(
|
||||
snapshot, str(dest_dir), dry_run=True)
|
||||
|
||||
assert skipped == []
|
||||
assert os.listdir(str(dest_dir)) == []
|
||||
|
||||
def test_rel_paths_restricts_restore(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "keep.txt").write_text("keep")
|
||||
(source_dir / "skip.txt").write_text("skip")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
restore.restore_snapshot(
|
||||
snapshot, str(dest_dir),
|
||||
rel_paths=[os.path.join(src_name, "keep.txt")])
|
||||
|
||||
restored_root = dest_dir / src_name
|
||||
assert (restored_root / "keep.txt").read_text() == "keep"
|
||||
assert not (restored_root / "skip.txt").exists()
|
||||
|
||||
def test_refuses_to_restore_into_snapshot_itself(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
with pytest.raises(restore.RestoreError):
|
||||
restore.restore_snapshot(snapshot, snapshot.path)
|
||||
|
||||
def test_refuses_symlinked_dest_subdir_escape(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "subdir").mkdir()
|
||||
(source_dir / "subdir" / "file.txt").write_text("content")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
|
||||
outside = restore_dirs[2].parent / "outside"
|
||||
outside.mkdir()
|
||||
dest_dir.mkdir()
|
||||
(dest_dir / src_name).symlink_to(outside, target_is_directory=True)
|
||||
|
||||
with pytest.raises(restore.RestoreError):
|
||||
restore.restore_snapshot(snapshot, str(dest_dir))
|
||||
|
||||
assert os.listdir(str(outside)) == []
|
||||
|
||||
def test_unknown_overwrite_policy_rejected(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
with pytest.raises(ValueError):
|
||||
restore.restore_snapshot(
|
||||
snapshot, str(dest_dir), overwrite="sometimes")
|
||||
|
||||
|
||||
class TestVerifyRestored:
|
||||
def test_verify_matches_after_clean_restore(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
restore.restore_snapshot(snapshot, str(dest_dir))
|
||||
|
||||
mismatches = restore.verify_restored(snapshot, str(dest_dir))
|
||||
assert mismatches == []
|
||||
|
||||
def test_verify_detects_corrupted_restore(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
restore.restore_snapshot(snapshot, str(dest_dir))
|
||||
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
(dest_dir / src_name / "file1.txt").write_text("corrupted")
|
||||
|
||||
mismatches = restore.verify_restored(snapshot, str(dest_dir))
|
||||
assert mismatches == [os.path.join(src_name, "file1.txt")]
|
||||
|
||||
def test_verify_refuses_symlinked_dest_escape(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
src_name = os.path.basename(str(source_dir))
|
||||
|
||||
outside = restore_dirs[2].parent / "outside"
|
||||
outside.mkdir()
|
||||
(outside / "file1.txt").write_text("content1")
|
||||
dest_dir.mkdir()
|
||||
(dest_dir / src_name).symlink_to(outside, target_is_directory=True)
|
||||
|
||||
mismatches = restore.verify_restored(snapshot, str(dest_dir))
|
||||
assert mismatches == [os.path.join(src_name, "file1.txt")]
|
||||
|
||||
def test_verify_detects_missing_restore(self, restore_dirs):
|
||||
backups_dir, source_dir, dest_dir = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("content1")
|
||||
|
||||
snapshot = _make_snapshot(backups_dir, source_dir)
|
||||
dest_dir.mkdir()
|
||||
|
||||
mismatches = restore.verify_restored(snapshot, str(dest_dir))
|
||||
assert mismatches == [
|
||||
os.path.join(os.path.basename(str(source_dir)), "file1.txt")
|
||||
]
|
||||
|
||||
|
||||
class TestFindBackup:
|
||||
def test_finds_latest_by_default(self, restore_dirs):
|
||||
backups_dir, source_dir, _ = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("v1")
|
||||
first = _make_snapshot(backups_dir, source_dir)
|
||||
|
||||
(source_dir / "file1.txt").write_text("v2")
|
||||
bk.initiate_backup(sources=[str(source_dir)],
|
||||
backups_dir=str(backups_dir))
|
||||
|
||||
latest = bk.find_backup(str(backups_dir))
|
||||
assert latest.name != first.name
|
||||
|
||||
def test_finds_by_explicit_name(self, restore_dirs):
|
||||
backups_dir, source_dir, _ = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("v1")
|
||||
first = _make_snapshot(backups_dir, source_dir)
|
||||
|
||||
found = bk.find_backup(str(backups_dir), first.name)
|
||||
assert found.name == first.name
|
||||
|
||||
def test_raises_on_unknown_name(self, restore_dirs):
|
||||
backups_dir, source_dir, _ = restore_dirs
|
||||
(source_dir / "file1.txt").write_text("v1")
|
||||
_make_snapshot(backups_dir, source_dir)
|
||||
|
||||
with pytest.raises(bk.BackupFailedError):
|
||||
bk.find_backup(str(backups_dir), "20000101_000000")
|
||||
|
||||
def test_raises_when_no_backups_exist(self, restore_dirs):
|
||||
backups_dir, _, _ = restore_dirs
|
||||
with pytest.raises(bk.BackupFailedError):
|
||||
bk.find_backup(str(backups_dir))
|
||||
@@ -0,0 +1,902 @@
|
||||
import os
|
||||
import os.path
|
||||
import socket
|
||||
import string
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from curateipsum import fs
|
||||
from conftest import create_file, create_dir, relpath, check_identical_file
|
||||
|
||||
|
||||
class MockStdout:
|
||||
"""Mock stdout that supports context manager and readline iteration."""
|
||||
|
||||
def __init__(self, lines):
|
||||
self.lines = iter(lines)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
def readline(self):
|
||||
try:
|
||||
return next(self.lines)
|
||||
except StopIteration:
|
||||
return b""
|
||||
|
||||
|
||||
class TestRsync:
|
||||
def test_dst_has_excess_file(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_fpath = create_file(str(dst_dir))
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert not os.path.lexists(dst_fpath)
|
||||
|
||||
def test_dst_has_excess_symlink(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_lpath = os.path.join(str(dst_dir), 'nonexisting_file')
|
||||
os.symlink('broken_symlink', dst_lpath)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert not os.path.lexists(dst_lpath)
|
||||
|
||||
def test_dst_has_excess_empty_dir(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_dpath = create_dir(str(dst_dir))
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert not os.path.lexists(dst_dpath)
|
||||
|
||||
def test_dst_has_excess_nonempty_dir(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_dpath = create_dir(str(dst_dir))
|
||||
create_file(dst_dpath)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert not os.path.lexists(dst_dpath)
|
||||
|
||||
def test_dst_has_excess_nonempty_recursive_dir(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_dpath = create_dir(str(dst_dir))
|
||||
nested_dpath = create_dir(dst_dpath)
|
||||
create_file(nested_dpath)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert not os.path.lexists(dst_dpath)
|
||||
|
||||
def test_different_types_src_file_dst_dir(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_fpath = create_file(str(src_dir))
|
||||
dst_path = os.path.join(str(dst_dir),
|
||||
relpath(src_fpath, str(src_dir), str(dst_dir)))
|
||||
os.mkdir(dst_path)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_path)
|
||||
assert os.path.isfile(dst_path)
|
||||
|
||||
def test_different_types_src_file_dst_symlink(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_fpath = create_file(str(src_dir))
|
||||
dst_path = os.path.join(str(dst_dir),
|
||||
relpath(src_fpath, str(src_dir), str(dst_dir)))
|
||||
os.symlink('broken_link', dst_path)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_path)
|
||||
assert os.path.isfile(dst_path)
|
||||
|
||||
def test_different_types_src_symlink_dst_file(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_path = create_file(str(dst_dir))
|
||||
src_lpath = os.path.join(str(src_dir),
|
||||
relpath(dst_path, str(src_dir), str(dst_dir)))
|
||||
os.symlink('broken_link', src_lpath)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_path)
|
||||
assert os.path.islink(dst_path)
|
||||
|
||||
def test_different_types_src_symlink_dst_dir(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
dst_path = create_dir(str(dst_dir))
|
||||
src_lpath = os.path.join(str(src_dir),
|
||||
relpath(dst_path, str(src_dir), str(dst_dir)))
|
||||
os.symlink('broken_link', src_lpath)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_path)
|
||||
assert os.path.islink(dst_path)
|
||||
|
||||
def test_different_types_src_dir_dst_file(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_dpath = create_dir(str(src_dir))
|
||||
dst_path = os.path.join(str(dst_dir),
|
||||
relpath(src_dpath, str(src_dir), str(dst_dir)))
|
||||
with open(dst_path, "w") as f:
|
||||
f.write(string.printable)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_path)
|
||||
assert os.path.isdir(dst_path)
|
||||
|
||||
def test_different_types_src_dir_dst_symlink(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_dpath = create_dir(str(src_dir))
|
||||
dst_path = os.path.join(str(dst_dir),
|
||||
relpath(src_dpath, str(src_dir), str(dst_dir)))
|
||||
os.symlink('broken_link', dst_path)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_path)
|
||||
assert os.path.isdir(dst_path)
|
||||
|
||||
@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"),
|
||||
reason="AF_UNIX not available on this platform")
|
||||
def test_src_is_socket(self):
|
||||
import tempfile
|
||||
# AF_UNIX paths are capped at ~104-108 bytes; pytest's tmp_path
|
||||
# nests too deep on macOS, so use a short-path tempdir directly.
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src_dir = os.path.join(d, "src")
|
||||
dst_dir = os.path.join(d, "dst")
|
||||
os.mkdir(src_dir)
|
||||
os.mkdir(dst_dir)
|
||||
src_spath = os.path.join(src_dir, "a_socket")
|
||||
dst_spath = os.path.join(dst_dir, "a_socket")
|
||||
with socket.socket(socket.AF_UNIX) as sock:
|
||||
sock.bind(src_spath)
|
||||
all(fs.rsync(src_dir, dst_dir))
|
||||
|
||||
assert not os.path.lexists(dst_spath)
|
||||
|
||||
def test_src_dst_same_inode(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_fpath = create_file(str(src_dir))
|
||||
dst_fpath = os.path.join(str(dst_dir),
|
||||
relpath(src_fpath, str(src_dir), str(dst_dir)))
|
||||
os.link(src_fpath, dst_fpath)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_fpath)
|
||||
src_stat = os.lstat(src_fpath)
|
||||
dst_stat = os.lstat(dst_fpath)
|
||||
assert src_stat.st_nlink == 1
|
||||
assert dst_stat.st_nlink == 1
|
||||
assert src_stat.st_ino != dst_stat.st_ino
|
||||
|
||||
def test_src_dst_diff_size(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_fpath = create_file(str(src_dir))
|
||||
dst_fpath = os.path.join(str(dst_dir),
|
||||
relpath(src_fpath, str(src_dir), str(dst_dir)))
|
||||
with open(dst_fpath, "w") as df:
|
||||
df.write(string.printable * 2)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
assert os.path.lexists(dst_fpath)
|
||||
check_identical_file(src_fpath, dst_fpath)
|
||||
|
||||
def test_broken_symlink_in_source(self, common_fs_dirs):
|
||||
"""Test that rsync copies broken symlinks correctly."""
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_lpath = os.path.join(str(src_dir), 'broken_link')
|
||||
# create symlink pointing to non-existent target
|
||||
os.symlink('/nonexistent/target/file.txt', src_lpath)
|
||||
dst_lpath = os.path.join(str(dst_dir), 'broken_link')
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
# verify symlink was copied and remains broken
|
||||
assert os.path.islink(dst_lpath)
|
||||
assert os.readlink(dst_lpath) == '/nonexistent/target/file.txt'
|
||||
assert not os.path.exists(dst_lpath) # link target doesn't exist
|
||||
|
||||
def test_unicode_filename(self, common_fs_dirs):
|
||||
"""Test that rsync handles unicode characters in filenames."""
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
# use various unicode characters: emoji, cyrillic, chinese, accents
|
||||
unicode_name = 'test_文件_файл_café_🎉.txt'
|
||||
src_fpath = os.path.join(str(src_dir), unicode_name)
|
||||
with open(src_fpath, "w", encoding='utf-8') as f:
|
||||
f.write("unicode content: 你好世界")
|
||||
dst_fpath = os.path.join(str(dst_dir), unicode_name)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert os.path.exists(dst_fpath)
|
||||
with open(dst_fpath, "r", encoding='utf-8') as f:
|
||||
assert f.read() == "unicode content: 你好世界"
|
||||
|
||||
def test_filename_with_spaces(self, common_fs_dirs):
|
||||
"""Test that rsync handles filenames with spaces."""
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
spaced_name = 'file with many spaces.txt'
|
||||
src_fpath = os.path.join(str(src_dir), spaced_name)
|
||||
with open(src_fpath, "w") as f:
|
||||
f.write("spaced content")
|
||||
dst_fpath = os.path.join(str(dst_dir), spaced_name)
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert os.path.exists(dst_fpath)
|
||||
check_identical_file(src_fpath, dst_fpath)
|
||||
|
||||
def test_empty_file(self, common_fs_dirs):
|
||||
"""Test that rsync handles empty (0 byte) files correctly."""
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
src_fpath = os.path.join(str(src_dir), 'empty.txt')
|
||||
# create empty file
|
||||
open(src_fpath, "w").close()
|
||||
dst_fpath = os.path.join(str(dst_dir), 'empty.txt')
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert os.path.exists(dst_fpath)
|
||||
assert os.path.getsize(dst_fpath) == 0
|
||||
|
||||
def test_very_long_relative_path(self, common_fs_dirs):
|
||||
"""Test that rsync handles deeply nested directory structures."""
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
# create a deeply nested path (10 levels deep)
|
||||
nested_path = os.path.join(*[f"level{i}" for i in range(10)])
|
||||
src_nested = os.path.join(str(src_dir), nested_path)
|
||||
os.makedirs(src_nested, exist_ok=True)
|
||||
|
||||
# create a file in the deepest directory
|
||||
src_fpath = os.path.join(src_nested, 'deep_file.txt')
|
||||
with open(src_fpath, "w") as f:
|
||||
f.write("deeply nested content")
|
||||
|
||||
dst_nested = os.path.join(str(dst_dir), nested_path)
|
||||
dst_fpath = os.path.join(dst_nested, 'deep_file.txt')
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert os.path.exists(dst_fpath)
|
||||
check_identical_file(src_fpath, dst_fpath)
|
||||
|
||||
|
||||
class TestRsyncBasic:
|
||||
"""Test suite for basic rsync functionality."""
|
||||
|
||||
@pytest.fixture
|
||||
def rsync_dirs(self, tmp_path):
|
||||
"""Create source and destination directories for rsync tests."""
|
||||
src_dir = os.path.join(str(tmp_path), "source")
|
||||
dst_dir = os.path.join(str(tmp_path), "dest")
|
||||
os.mkdir(src_dir)
|
||||
return src_dir, dst_dir
|
||||
|
||||
def test_rsync_creates_destination(self, rsync_dirs):
|
||||
"""Test that rsync creates destination directory if missing"""
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
assert not os.path.exists(dst_dir)
|
||||
list(fs.rsync(src_dir, dst_dir))
|
||||
assert os.path.isdir(dst_dir)
|
||||
|
||||
def test_rsync_copies_new_files(self, rsync_dirs):
|
||||
"""Test that rsync copies new files"""
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
|
||||
with open(os.path.join(src_dir, "file1.txt"), "w") as f:
|
||||
f.write("content1")
|
||||
with open(os.path.join(src_dir, "file2.txt"), "w") as f:
|
||||
f.write("content2")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir))
|
||||
|
||||
assert os.path.exists(os.path.join(dst_dir, "file1.txt"))
|
||||
assert os.path.exists(os.path.join(dst_dir, "file2.txt"))
|
||||
|
||||
create_actions = [a for a in actions if a[1] == fs.Actions.CREATE]
|
||||
assert len(create_actions) == 2
|
||||
|
||||
def test_rsync_deletes_missing_files(self, rsync_dirs):
|
||||
"""Test that rsync deletes files not in source"""
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
|
||||
dst_file = os.path.join(dst_dir, "old_file.txt")
|
||||
with open(dst_file, "w") as f:
|
||||
f.write("old content")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir))
|
||||
|
||||
assert not os.path.exists(dst_file)
|
||||
|
||||
delete_actions = [a for a in actions if a[1] == fs.Actions.DELETE]
|
||||
assert len(delete_actions) == 1
|
||||
|
||||
def test_rsync_updates_modified_files(self, rsync_dirs):
|
||||
"""Test that rsync updates modified files"""
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
|
||||
src_file = os.path.join(src_dir, "file.txt")
|
||||
dst_file = os.path.join(dst_dir, "file.txt")
|
||||
|
||||
with open(src_file, "w") as f:
|
||||
f.write("original")
|
||||
with open(dst_file, "w") as f:
|
||||
f.write("modified")
|
||||
|
||||
import time
|
||||
time.sleep(0.1)
|
||||
with open(src_file, "w") as f:
|
||||
f.write("updated content")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir))
|
||||
|
||||
with open(dst_file, "r") as f:
|
||||
assert f.read() == "updated content"
|
||||
|
||||
rewrite_actions = [a for a in actions if a[1] == fs.Actions.REWRITE]
|
||||
assert len(rewrite_actions) > 0
|
||||
|
||||
def test_rsync_preserves_permissions(self, rsync_dirs):
|
||||
"""Test that rsync preserves file permissions"""
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
|
||||
src_file = os.path.join(src_dir, "script.sh")
|
||||
with open(src_file, "w") as f:
|
||||
f.write("#!/bin/bash\n")
|
||||
os.chmod(src_file, 0o755)
|
||||
|
||||
list(fs.rsync(src_dir, dst_dir))
|
||||
|
||||
dst_file = os.path.join(dst_dir, "script.sh")
|
||||
dst_stat = os.stat(dst_file)
|
||||
src_stat = os.stat(src_file)
|
||||
assert dst_stat.st_mode == src_stat.st_mode
|
||||
|
||||
|
||||
class TestRsyncDryRun:
|
||||
"""
|
||||
fs.rsync(dry_run=True) must yield the same actions a real run would,
|
||||
while never creating, deleting, or modifying anything - including
|
||||
dst_dir itself when it doesn't already exist.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def rsync_dirs(self, tmp_path):
|
||||
src_dir = os.path.join(str(tmp_path), "source")
|
||||
dst_dir = os.path.join(str(tmp_path), "dest")
|
||||
os.mkdir(src_dir)
|
||||
return src_dir, dst_dir
|
||||
|
||||
def test_dry_run_does_not_create_missing_destination(self, rsync_dirs):
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
with open(os.path.join(src_dir, "file.txt"), "w") as f:
|
||||
f.write("content")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir, dry_run=True))
|
||||
|
||||
assert not os.path.exists(dst_dir)
|
||||
assert [a[1] for a in actions] == [fs.Actions.CREATE]
|
||||
|
||||
def test_dry_run_does_not_copy_new_files(self, rsync_dirs):
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
with open(os.path.join(src_dir, "file.txt"), "w") as f:
|
||||
f.write("content")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir, dry_run=True))
|
||||
|
||||
assert not os.path.exists(os.path.join(dst_dir, "file.txt"))
|
||||
assert [a[1] for a in actions] == [fs.Actions.CREATE]
|
||||
|
||||
def test_dry_run_does_not_delete_stale_files(self, rsync_dirs):
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
stale = os.path.join(dst_dir, "stale.txt")
|
||||
with open(stale, "w") as f:
|
||||
f.write("stale")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir, dry_run=True))
|
||||
|
||||
assert os.path.exists(stale)
|
||||
assert [a[1] for a in actions] == [fs.Actions.DELETE]
|
||||
|
||||
def test_dry_run_does_not_rewrite_changed_files(self, rsync_dirs):
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
src_file = os.path.join(src_dir, "file.txt")
|
||||
dst_file = os.path.join(dst_dir, "file.txt")
|
||||
with open(src_file, "w") as f:
|
||||
f.write("updated content")
|
||||
with open(dst_file, "w") as f:
|
||||
f.write("modified")
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir, dry_run=True))
|
||||
|
||||
with open(dst_file, "r") as f:
|
||||
assert f.read() == "modified"
|
||||
assert [a[1] for a in actions] == [fs.Actions.REWRITE]
|
||||
|
||||
def test_dry_run_does_not_change_permissions(self, rsync_dirs):
|
||||
src_dir, dst_dir = rsync_dirs
|
||||
os.mkdir(dst_dir)
|
||||
src_file = os.path.join(src_dir, "script.sh")
|
||||
dst_file = os.path.join(dst_dir, "script.sh")
|
||||
with open(src_file, "w") as f:
|
||||
f.write("content")
|
||||
with open(dst_file, "w") as f:
|
||||
f.write("content")
|
||||
os.utime(dst_file, ns=(os.stat(src_file).st_atime_ns,
|
||||
os.stat(src_file).st_mtime_ns))
|
||||
os.chmod(src_file, 0o755)
|
||||
os.chmod(dst_file, 0o644)
|
||||
|
||||
actions = list(fs.rsync(src_dir, dst_dir, dry_run=True))
|
||||
|
||||
assert os.stat(dst_file).st_mode & 0o777 == 0o644
|
||||
assert [a[1] for a in actions] == [fs.Actions.UPDATE_PERM]
|
||||
|
||||
|
||||
class TestParseRsyncOutput:
|
||||
"""Test _parse_rsync_output() parsing of rsync --itemize-changes."""
|
||||
|
||||
def test_delete_file(self):
|
||||
"""Parse deletion output."""
|
||||
result = fs._parse_rsync_output("*deleting path/to/file.txt")
|
||||
assert result == ("path/to/file.txt", fs.Actions.DELETE, "")
|
||||
|
||||
def test_delete_nested_path(self):
|
||||
"""Parse deletion with nested directory structure."""
|
||||
result = fs._parse_rsync_output("*deleting deeply/nested/dir/file.md")
|
||||
assert result == ("deeply/nested/dir/file.md", fs.Actions.DELETE, "")
|
||||
|
||||
def test_create_file(self):
|
||||
"""Parse file creation."""
|
||||
result = fs._parse_rsync_output(">f+++++++++ new_file.txt")
|
||||
assert result == ("new_file.txt", fs.Actions.CREATE, "")
|
||||
|
||||
def test_create_file_nested(self):
|
||||
"""Parse file creation in subdirectory."""
|
||||
result = fs._parse_rsync_output(">f+++++++++ subdir/another.log")
|
||||
assert result == ("subdir/another.log", fs.Actions.CREATE, "")
|
||||
|
||||
def test_create_directory(self):
|
||||
"""Parse directory creation."""
|
||||
result = fs._parse_rsync_output("cd+++++++++ new_directory/")
|
||||
assert result == ("new_directory/", fs.Actions.CREATE, "")
|
||||
|
||||
def test_create_symlink(self):
|
||||
"""Parse symlink creation."""
|
||||
result = fs._parse_rsync_output("cL+++++++++ link_to_file")
|
||||
assert result == ("link_to_file", fs.Actions.CREATE, "")
|
||||
|
||||
def test_rewrite_file_size_change(self):
|
||||
"""Parse file rewrite due to size change."""
|
||||
result = fs._parse_rsync_output(">f.s...... modified_file.txt")
|
||||
assert result == ("modified_file.txt", fs.Actions.REWRITE, "")
|
||||
|
||||
def test_rewrite_file_time_change(self):
|
||||
"""Parse file rewrite due to time change."""
|
||||
result = fs._parse_rsync_output(">f..t...... touched_file.dat")
|
||||
assert result == ("touched_file.dat", fs.Actions.REWRITE, "")
|
||||
|
||||
def test_rewrite_file_size_and_time(self):
|
||||
"""Parse file rewrite due to both size and time change."""
|
||||
result = fs._parse_rsync_output(">f.st...... changed.bin")
|
||||
assert result == ("changed.bin", fs.Actions.REWRITE, "")
|
||||
|
||||
def test_update_directory_time(self):
|
||||
"""Parse directory time update."""
|
||||
result = fs._parse_rsync_output(">d..t...... some_dir/")
|
||||
assert result == ("some_dir/", fs.Actions.UPDATE_TIME, "")
|
||||
|
||||
def test_update_permissions(self):
|
||||
"""Parse permission change."""
|
||||
result = fs._parse_rsync_output(">f....p.... executable.sh")
|
||||
assert result == ("executable.sh", fs.Actions.UPDATE_PERM, "")
|
||||
|
||||
def test_update_permissions_with_time_change(self):
|
||||
"""Time change takes precedence over permission change."""
|
||||
result = fs._parse_rsync_output(">f...tp.... script.py")
|
||||
assert result == ("script.py", fs.Actions.REWRITE, "")
|
||||
|
||||
def test_update_owner(self):
|
||||
"""Parse owner change."""
|
||||
result = fs._parse_rsync_output(">f.....o... owned_file.txt")
|
||||
assert result == ("owned_file.txt", fs.Actions.UPDATE_OWNER, "")
|
||||
|
||||
def test_update_group(self):
|
||||
"""Parse group change."""
|
||||
result = fs._parse_rsync_output(">f......g.. grouped_file.txt")
|
||||
assert result == ("grouped_file.txt", fs.Actions.UPDATE_OWNER, "")
|
||||
|
||||
def test_update_owner_and_group(self):
|
||||
"""Parse both owner and group change."""
|
||||
result = fs._parse_rsync_output(">f.....og.. shared_file.txt")
|
||||
assert result == ("shared_file.txt", fs.Actions.UPDATE_OWNER, "")
|
||||
|
||||
def test_invalid_format_raises_error(self):
|
||||
"""Unparseable line should raise RuntimeError."""
|
||||
with pytest.raises(RuntimeError, match="Not parsed string"):
|
||||
fs._parse_rsync_output(">f......... unknown.txt")
|
||||
|
||||
def test_empty_change_string_raises_error(self):
|
||||
"""Empty change indicators should raise RuntimeError."""
|
||||
with pytest.raises(RuntimeError, match="Not parsed string"):
|
||||
fs._parse_rsync_output(">f......... no_action.txt")
|
||||
|
||||
|
||||
class TestRsyncExt:
|
||||
"""Test external rsync command wrapper."""
|
||||
|
||||
def test_command_construction(self, tmp_path):
|
||||
"""Verify rsync command is built with correct arguments."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
# minimal valid rsync output
|
||||
mock_process.stdout = MockStdout([b">f+++++++++ test.txt\n"])
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
# verify command was called with correct arguments
|
||||
args = mock_popen.call_args[0][0]
|
||||
assert args[0] == "rsync"
|
||||
assert "--archive" in args
|
||||
assert "--whole-file" in args
|
||||
assert "--human-readable" in args
|
||||
assert "--delete-during" in args
|
||||
assert "--itemize-changes" in args
|
||||
assert "--one-file-system" in args
|
||||
assert args[-2] == f"{src}/"
|
||||
assert args[-1] == str(dst)
|
||||
|
||||
def test_dry_run_flag(self, tmp_path):
|
||||
"""Verify --dry-run flag is added when dry_run=True."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout([b">f+++++++++ test.txt\n"])
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
list(fs.rsync_ext(str(src), str(dst), dry_run=True))
|
||||
|
||||
args = mock_popen.call_args[0][0]
|
||||
assert "--dry-run" in args
|
||||
|
||||
def test_processes_rsync_output_lines(self, tmp_path):
|
||||
"""Parse valid rsync itemize output lines."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
rsync_output = [
|
||||
b"cd+++++++++ subdir/\n",
|
||||
b">f+++++++++ subdir/newfile.txt\n",
|
||||
]
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout(rsync_output)
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
results = list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
# both lines should be processed
|
||||
assert len(results) == 2
|
||||
assert results[0][0] == "subdir/"
|
||||
assert results[0][1] == fs.Actions.CREATE
|
||||
assert results[1][0] == "subdir/newfile.txt"
|
||||
assert results[1][1] == fs.Actions.CREATE
|
||||
|
||||
def test_handles_unicode_decode_error(self, tmp_path, caplog):
|
||||
"""Log error when encountering non-UTF8 bytes."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
# invalid UTF-8 byte sequence
|
||||
invalid_utf8 = b"\xff\xfe invalid bytes\n"
|
||||
rsync_output = [
|
||||
invalid_utf8,
|
||||
b">f+++++++++ validfile.txt\n",
|
||||
]
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout(rsync_output)
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
results = list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
# current behavior: invalid line causes prev_line to get stuck,
|
||||
# so subsequent lines are also skipped (potential bug)
|
||||
assert len(results) == 0
|
||||
assert "Can't process rsync line" in caplog.text
|
||||
|
||||
def test_yields_parsed_actions(self, tmp_path):
|
||||
"""Verify integration with _parse_rsync_output()."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
rsync_output = [
|
||||
b"cd+++++++++ dir1/\n",
|
||||
b">f+++++++++ file1.txt\n",
|
||||
b"*deleting oldfile.txt\n",
|
||||
b">f..t...... file2.txt\n",
|
||||
]
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout(rsync_output)
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
results = list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
assert len(results) == 4
|
||||
assert results[0] == ("dir1/", fs.Actions.CREATE, "")
|
||||
assert results[1] == ("file1.txt", fs.Actions.CREATE, "")
|
||||
assert results[2] == ("oldfile.txt", fs.Actions.DELETE, "")
|
||||
assert results[3] == ("file2.txt", fs.Actions.REWRITE, "")
|
||||
|
||||
def test_calls_process_wait(self, tmp_path):
|
||||
"""Ensure subprocess.wait() is called to clean up process."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout([b">f+++++++++ test.txt\n"])
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
mock_process.wait.assert_called_once()
|
||||
|
||||
def test_single_line_output(self, tmp_path):
|
||||
"""Handle case where rsync produces single file output."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout([b">f+++++++++ newfile.txt\n"])
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
results = list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0][0] == "newfile.txt"
|
||||
assert results[0][1] == fs.Actions.CREATE
|
||||
|
||||
def test_multiple_files_in_output(self, tmp_path):
|
||||
"""Process multiple file operations in single rsync run."""
|
||||
src = tmp_path / "source"
|
||||
dst = tmp_path / "dest"
|
||||
src.mkdir()
|
||||
dst.mkdir()
|
||||
|
||||
# realistic rsync output with multiple operations
|
||||
rsync_output = [
|
||||
b"cd+++++++++ docs/\n",
|
||||
b">f+++++++++ docs/readme.md\n",
|
||||
b">f+++++++++ config.json\n",
|
||||
b".f..t...... existing.txt\n",
|
||||
b"*deleting old/\n",
|
||||
]
|
||||
|
||||
with patch("subprocess.Popen") as mock_popen:
|
||||
mock_process = Mock()
|
||||
mock_process.stdout = MockStdout(rsync_output)
|
||||
mock_process.wait.return_value = 0
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
results = list(fs.rsync_ext(str(src), str(dst)))
|
||||
|
||||
assert len(results) == 5
|
||||
assert results[0][0] == "docs/"
|
||||
assert results[1][0] == "docs/readme.md"
|
||||
assert results[2][0] == "config.json"
|
||||
assert results[3][0] == "existing.txt"
|
||||
assert results[4][0] == "old/"
|
||||
|
||||
|
||||
class TestRsyncHardlinkImmutability:
|
||||
"""
|
||||
Regression tests: rsync() is run against a staging directory that
|
||||
was populated by hardlinking in the previous, completed snapshot
|
||||
(curateipsum.backup.hardlink_dir). Any in-place metadata change made
|
||||
while updating staging must never mutate that previous snapshot's
|
||||
files via the shared inode.
|
||||
"""
|
||||
|
||||
def test_permission_change_does_not_mutate_shared_hardlink(
|
||||
self, common_fs_dirs, tmp_path
|
||||
):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
# Independent source file with new content/mtime but the SAME
|
||||
# eventual permissions the old snapshot file already has - only
|
||||
# the fallback "update permissions and ownership" branch should
|
||||
# fire, not a full rewrite (which would already be safe via
|
||||
# rm+recreate).
|
||||
src_fpath = create_file(str(src_dir))
|
||||
os.chmod(src_fpath, 0o600)
|
||||
|
||||
# Simulate staging (dst_dir) having been hardlinked in from the
|
||||
# previous, completed snapshot: a separate directory tree outside
|
||||
# dst_dir, sharing an inode with the staging file, with content
|
||||
# and mtime matching src (so only permissions differ) but the old
|
||||
# mode.
|
||||
dst_fpath = os.path.join(str(dst_dir),
|
||||
relpath(src_fpath, str(src_dir), str(dst_dir)))
|
||||
prior_snapshot_fpath = str(tmp_path / "prior_snapshot")
|
||||
with open(src_fpath) as src_f:
|
||||
src_content = src_f.read()
|
||||
with open(prior_snapshot_fpath, "w") as f:
|
||||
f.write(src_content)
|
||||
os.chmod(prior_snapshot_fpath, 0o644)
|
||||
src_stat = os.lstat(src_fpath)
|
||||
os.utime(prior_snapshot_fpath, (src_stat.st_atime, src_stat.st_mtime))
|
||||
os.link(prior_snapshot_fpath, dst_fpath)
|
||||
prior_mode_before = os.lstat(prior_snapshot_fpath).st_mode
|
||||
dst_mtime_before = os.lstat(dst_fpath).st_mtime
|
||||
assert os.lstat(dst_fpath).st_ino == os.lstat(
|
||||
prior_snapshot_fpath).st_ino # sanity: genuinely shared
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert os.lstat(dst_fpath).st_mode == os.lstat(src_fpath).st_mode
|
||||
assert os.lstat(prior_snapshot_fpath).st_mode == prior_mode_before
|
||||
# dst must now have its own inode, no longer shared
|
||||
assert os.lstat(dst_fpath).st_ino != os.lstat(
|
||||
prior_snapshot_fpath).st_ino
|
||||
# breaking the hardlink must not, as a side effect, reset mtime:
|
||||
# rsync only intended to change permissions here (content/mtime
|
||||
# already matched), and uid/gid are identical for this test user
|
||||
# so the chown branch never fires to "accidentally" fix ownership
|
||||
assert os.lstat(dst_fpath).st_mtime == dst_mtime_before
|
||||
|
||||
def test_symlink_metadata_never_touches_external_target(
|
||||
self, common_fs_dirs, tmp_path
|
||||
):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
external_target = tmp_path / "external_target"
|
||||
external_target.mkdir()
|
||||
(external_target / "canary").write_text("do-not-touch")
|
||||
external_mode_before = os.lstat(str(external_target)).st_mode
|
||||
|
||||
link_name = "a_symlink"
|
||||
os.symlink(str(external_target), os.path.join(str(src_dir), link_name))
|
||||
os.symlink(str(external_target), os.path.join(str(dst_dir), link_name))
|
||||
|
||||
all(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert os.lstat(str(external_target)).st_mode == external_mode_before
|
||||
assert (external_target / "canary").read_text() == "do-not-touch"
|
||||
|
||||
|
||||
class TestEntryKind:
|
||||
"""Tests for fs.entry_kind() classification."""
|
||||
|
||||
def test_regular_file(self, tmp_path):
|
||||
path = os.path.join(str(tmp_path), "f")
|
||||
with open(path, "w") as f:
|
||||
f.write("x")
|
||||
with os.scandir(str(tmp_path)) as it:
|
||||
entry = next(iter(it))
|
||||
assert fs.entry_kind(entry) == "file"
|
||||
|
||||
def test_directory(self, tmp_path):
|
||||
path = os.path.join(str(tmp_path), "d")
|
||||
os.mkdir(path)
|
||||
with os.scandir(str(tmp_path)) as it:
|
||||
entry = next(iter(it))
|
||||
assert fs.entry_kind(entry) == "dir"
|
||||
|
||||
def test_symlink(self, tmp_path):
|
||||
target = os.path.join(str(tmp_path), "target")
|
||||
link = os.path.join(str(tmp_path), "link")
|
||||
with open(target, "w") as f:
|
||||
f.write("x")
|
||||
os.symlink(target, link)
|
||||
with os.scandir(str(tmp_path)) as it:
|
||||
entries = {e.name: e for e in it}
|
||||
assert fs.entry_kind(entries["link"]) == "symlink"
|
||||
|
||||
@pytest.mark.skipif(not hasattr(os, "mkfifo"),
|
||||
reason="os.mkfifo not available on this platform")
|
||||
def test_fifo(self, tmp_path):
|
||||
path = os.path.join(str(tmp_path), "fifo")
|
||||
os.mkfifo(path)
|
||||
with os.scandir(str(tmp_path)) as it:
|
||||
entry = next(iter(it))
|
||||
assert fs.entry_kind(entry) == "fifo"
|
||||
|
||||
@pytest.mark.skipif(not os.path.exists("/dev/null"),
|
||||
reason="no /dev/null on this platform")
|
||||
def test_char_device(self):
|
||||
entry = fs.PseudoDirEntry("/dev/null")
|
||||
assert fs.entry_kind(entry) == "char_device"
|
||||
|
||||
@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"),
|
||||
reason="AF_UNIX not available on this platform")
|
||||
def test_socket(self):
|
||||
import tempfile
|
||||
# AF_UNIX paths are capped at ~104-108 bytes; pytest's tmp_path
|
||||
# nests too deep on macOS, so use a short-path tempdir directly.
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
sock_path = os.path.join(d, "s")
|
||||
with socket.socket(socket.AF_UNIX) as sock:
|
||||
sock.bind(sock_path)
|
||||
with os.scandir(d) as it:
|
||||
entry = next(iter(it))
|
||||
assert fs.entry_kind(entry) == "socket"
|
||||
|
||||
|
||||
class TestRsyncExcludesUnsupportedEntries:
|
||||
"""
|
||||
Regression tests: rsync() must classify FIFOs/sockets/devices via
|
||||
lstat() alone (never opening them) and exclude them with a visible
|
||||
EXCLUDE action, instead of either blocking forever (a FIFO with no
|
||||
writer) or treating them as a fatal Actions.ERROR that aborts the
|
||||
whole backup.
|
||||
"""
|
||||
|
||||
@pytest.mark.skipif(not hasattr(os, "mkfifo"),
|
||||
reason="os.mkfifo not available on this platform")
|
||||
def test_fifo_without_writer_does_not_block(self, common_fs_dirs):
|
||||
src_dir, dst_dir = common_fs_dirs
|
||||
fifo_path = os.path.join(str(src_dir), "a_fifo")
|
||||
os.mkfifo(fifo_path)
|
||||
|
||||
# No writer is ever opened on the other end. If rsync() opened
|
||||
# this for reading, this test would hang instead of failing.
|
||||
results = list(fs.rsync(str(src_dir), str(dst_dir)))
|
||||
|
||||
assert ("a_fifo", fs.Actions.EXCLUDE, "fifo") in results
|
||||
assert not os.path.lexists(os.path.join(str(dst_dir), "a_fifo"))
|
||||
|
||||
@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"),
|
||||
reason="AF_UNIX not available on this platform")
|
||||
def test_socket_is_excluded_not_fatal(self):
|
||||
import tempfile
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src_dir = os.path.join(d, "src")
|
||||
dst_dir = os.path.join(d, "dst")
|
||||
os.mkdir(src_dir)
|
||||
os.mkdir(dst_dir)
|
||||
sock_path = os.path.join(src_dir, "a_socket")
|
||||
with socket.socket(socket.AF_UNIX) as sock:
|
||||
sock.bind(sock_path)
|
||||
results = list(fs.rsync(src_dir, dst_dir))
|
||||
|
||||
assert ("a_socket", fs.Actions.EXCLUDE, "socket") in results
|
||||
assert fs.Actions.ERROR not in [r[1] for r in results]
|
||||
assert not os.path.lexists(os.path.join(dst_dir, "a_socket"))
|
||||
Reference in new issue
Block a user