41 Commits
Author SHA1 Message Date
snegov bfcb81e90b Add CLAUDE.md 2026-10-11 13:26:08 -07:00
22757ece58 Make dry-run genuinely non-mutating (#23)
* Make dry-run genuinely non-mutating

fs.rsync() now takes a real dry_run code path: every mutating call
(copy, delete, chmod, chown, utime) is skipped, and a missing dst_dir
is never created - the same comparison logic still runs so the yielded
actions match what a real run would do.

backup.initiate_backup() diffs each source directly against the latest
completed snapshot on dry-run, instead of building and discarding a
throwaway staging directory with real hardlinks. cleanup_old_backups()
no longer creates the repo-id file as a side effect of a dry-run.

cli.py skips lock acquisition entirely on dry-run (set_backups_lock()
writes PID/timestamp metadata, itself a mutation) and exposes the
retention policy via --keep-all/--keep-daily/--keep-weekly/
--keep-monthly/--keep-yearly.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review: guard restore lock release, reject negative retention values

- Guard restore --dry-run's finally block the same way backup's is
  guarded, for symmetry (release_backups_lock() was already a safe
  no-op when unheld, but this makes the dry-run contract explicit
  rather than relying on that implementation detail).
- Reject negative --keep-* values via a dedicated argparse type: a
  negative threshold shifts retention comparisons into the future and
  can make cleanup treat every existing backup as deletable.
- Add a restore --dry-run lock-skip regression test, mirroring the
  existing backup one.
- Fix _snapshot_all_stats() in the new dry-run non-mutation test to
  also record the backups_dir root's own stat, not just its children.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-09 01:39:53 +00:00
699c569cc2 Test nanosecond mtime precision on file and symlink copies (#22)
* Test nanosecond mtime precision on file and symlink copies

Existing preserves-times tests only set whole-second timestamps via
os.utime(path, (sec, sec)), so a backend that silently truncated to
second resolution would still pass them. The Python backend's
nanosecond-precision guarantee (documented in README's Limitations
section) was otherwise untested at sub-second granularity.

Combined with CI already running the full suite on both ubuntu-latest
and macos-latest, this closes the "Test supported behavior on Linux
and macOS" item in IMPROVEMENTS.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Rename nanosecond timestamp tests to cover atime too

Copilot review feedback on PR #22: both tests assert st_atime_ns and
st_mtime_ns, but the names/docstrings said "mtime" only.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Assert symlink entry is found before use in nanosecond test

Copilot review feedback on PR #22: if the scandir() loop didn't find
the symlink, entry stayed None and copy_direntry() would fail with a
less-informative error than an explicit assertion.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-09 01:12:50 +00:00
4a4797e959 Document Python/external-rsync backend differences (#20)
* Document Python/external-rsync backend differences

- Note that mixing --external-rsync (which can recreate device/socket
  entries via --archive's -D) with the default Python hardlink-forward
  step is unsafe: _recursive_hardlink() only understands files,
  symlinks, and directories and errors on anything else.
- Note that --dry-run is I/O-free with --external-rsync but still
  fully copies into a throwaway staging directory with the Python
  backend, though neither leaves a lasting change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Clarify external-rsync dry-run description

Copilot review feedback on PR #20: rsync's --dry-run still reads and
stats source files to compute what would change, it just avoids
writing to the destination - "performs no I/O" overstated that.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 17:20:47 +00:00
87cdb5cadb Reduce CI cost: dedupe triggers, thin macOS matrix (#21)
- Drop push-triggered runs for non-master branches; pull_request
  already covers every PR commit, so push+pull_request was running
  the full 14-job matrix twice per push (28 jobs).
- Only run the full Python 3.8-3.14 matrix on ubuntu-latest. macOS
  runners bill at 10x Linux minutes; test just the oldest and newest
  supported Python there to catch platform-specific issues.
- Net effect: 28 jobs per PR push -> 9 (7 Linux + 2 macOS).

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 16:37:57 +00:00
934482086f Document ACL, xattr, sparse-file, and hardlink backup behavior (#19)
* Document ACL, xattr, sparse-file, and hardlink backup behavior

Extend the README Limitations section with the filesystem-feature
behaviors that weren't documented: ACLs/xattrs/flags are never
preserved by either backend, sparse files are materialized as full
allocated copies, source-side hardlinks are not preserved as
hardlinks in the backup, and ownership is only preserved when
running as root.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Soften README timestamp/ownership claims for external-rsync backend

Nanosecond mtime precision and 'silently logged chown failures' are
Python-backend specifics that don't hold for --external-rsync: rsync's
own timestamp precision depends on the build/filesystem, and it skips
disallowed ownership changes itself rather than going through our
logging path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 16:00:09 +00:00
91b7bb133c Add an explicit one-filesystem policy to backups (#18)
* Add an explicit one-filesystem policy to backups

scantree() gains an opt-in one_filesystem flag: when a subdirectory's
device differs from the walk root's (a mount point), its contents are
excluded from the walk. The mount-point directory itself is still
yielded, so it appears as an empty directory in the backup rather than
vanishing silently - matching rsync's --one-file-system behavior.

Wired into rsync()'s two source-tree walks so backups never silently
pull in content from a bind mount or other filesystem mounted under
the source tree.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Fix one-filesystem policy: symlinked root and external rsync parity

- scantree() computed the walk root's device with os.lstat(), but
  scandir() follows the root path if it's a symlink. A symlinked root
  would compute the symlink's own device instead of the target
  directory's, making every real subdirectory look cross-device and
  get its contents wrongly excluded. Use os.stat() for the root only.
- rsync_ext() (the external-rsync backend) didn't pass
  --one-file-system, so backups using external_rsync=True still
  crossed mount points despite the pure-Python path now refusing to.

Addresses GitHub Copilot review feedback on PR #18.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-06 03:38:16 +00:00
e3c8acf954 Fix test that leaks a chdir'd cwd across the test run (#17)
test_relative_symlink_to_common_file changed the process working
directory via os.chdir() but never restored it, leaving subsequent
tests running from a tmp_path fixture directory that gets deleted
after the test. Restore cwd in a finally block, matching the pattern
already used in test_pseudo_direntry.py.

Also checks off the now-satisfied xfail-marker item: no xfail markers
remain in the repo.

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 02:17:40 +00:00
7618ef7ffb Add macOS to CI test matrix (#16)
Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-05 02:07:43 +00:00
d696f2aebb Run CI on pull requests as well as pushes (#15)
Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 23:02:44 +00:00
4461fe2359 Fix Unix-socket test failing on macOS due to AF_UNIX path length (#14)
tmp_path nests too deeply for AF_UNIX socket paths (~104-108 byte
limit on macOS). Use a flat tempfile.TemporaryDirectory(), matching
the pattern already used by TestEntryKind::test_socket.

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 22:52:42 +00:00
snegovandMaxim Shulga 33dcbe6c58 Implement a restore command (#13)
* Implement restore command

Add a restore subcommand alongside the existing backup command:
- curateipsum/restore.py: restore_snapshot() and verify_restored(),
  reusing fs.scantree/copy_direntry/rm_direntry so metadata handling
  (mode, ownership, timestamps, symlinks) matches backup exactly.
- backup.find_backup(): resolve a snapshot by name or latest.
- cli.py: argparse subcommands (backup/restore), with backup implied
  when no subcommand is given so existing invocations keep working.

Restore supports dry-run (creates nothing), partial restore by
snapshot-relative path, an overwrite policy (never/always), a
destination-inside-snapshot boundary check, and manifest-checksum
verification of restored content. It takes the same backups_lock a
backup does, since retention could otherwise delete the snapshot
being restored out from under it.

Closes P1 'Provide a safe restoration workflow' in IMPROVEMENTS.md.

* Address Copilot review: symlink-escape boundary check, docstring fix

- restore_snapshot() and verify_restored() now canonicalize each
  destination path and refuse to operate on it if it resolves outside
  dest_dir - a symlink planted under dest_dir (by another process, or
  left over from a prior run) could otherwise redirect a write, delete,
  or read outside the intended destination.
- Fixed restore_snapshot()'s docstring: the skipped-paths list reports
  what would be skipped on dry-run too, it isn't always empty.

* Address Copilot suppressed findings: stream plan_restore, restore-specific lock message

- plan_restore() is now a generator instead of building a full list in
  memory, matching fs.scantree()'s streaming style everywhere else in
  the codebase.
- restore CLI logs a restore-specific message on lock-acquire failure,
  since set_backups_lock()'s own log line talks about a 'previous
  backup', which read wrong for a restore.

* Fix PATH docs: snapshot-relative means source-basename-prefixed

README and CLI help examples for restore's PATH argument omitted the
source directory's basename, which backup.initiate_backup() always
prefixes onto snapshot-relative paths - the given examples would have
matched nothing in an actual snapshot.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-04 15:58:34 +00:00
snegovandMaxim Shulga 248204fe41 Add immediate safety warning to README (#12)
* Add immediate safety warning to README

- Remove the production-use claim from Project Status.
- Mark the project experimental until the P0 data-safety checklist
  passes, with a prominent warning banner up top.
- Add a Limitations section: warn against modifying hardlinked
  snapshots in place, document the lack of a restore command, and
  note special-entry exclusion and symlink-preservation behavior.
- Check off the corresponding IMPROVEMENTS.md acceptance criteria.

* Qualify special-entry exclusion limitation to the Python implementation

--external-rsync uses rsync's --archive flag, which copies/recreates
FIFOs, sockets, and device nodes instead of excluding them - the
exclusion behavior only applies to the default Python implementation.

* Qualify device-node recreation reliability under --external-rsync

rsync -a implies -D (devices/specials), but creating device nodes
typically requires root on the destination - without it rsync may
skip or fail on them rather than reliably recreating them.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-04 04:49:00 +00:00
a29517e2fc Handle special filesystem entries explicitly (#11)
* Handle special filesystem entries explicitly

- Added fs.entry_kind(): classifies via lstat() mode bits alone
  ("file", "dir", "symlink", "fifo", "socket", "block_device",
  "char_device", "unknown") - never opens the entry, so classifying a
  FIFO can't block even without a writer.
- rsync() now classifies every source entry before touching it and
  yields a new Actions.EXCLUDE for anything outside file/dir/symlink,
  instead of falling through to copy_direntry()'s file branch, which
  would either block forever opening a writerless FIFO for read, or
  raise an OSError that initiate_backup() treats as fatal (aborting the
  whole backup for one socket).
- initiate_backup() records exclusions in the completion manifest
  (keyed by snapshot-relative path, valued with the excluded kind), and
  no longer nest_hardlinks or counts a recurring exclusion as a change
  worth keeping a new snapshot for.
- Chose the "recorded exclusion" policy the plan allows, rather than
  fail-fast: a FIFO or socket living in a backed-up tree is not itself
  a backup failure, and previously turned into one.

Note: rsync_ext() (external rsync) is unaffected by this change and
keeps whatever its own --archive flags do with special files; the P1
item on Python/external implementation parity covers reconciling that.
The pre-existing test_src_is_socket failure (AF_UNIX path length on
macOS tmp_path) is untouched here - it's separately tracked under P1
test fixes - but this PR adds working socket/FIFO/char-device coverage
via a short-path tempdir.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review: fix stale exclude, exclusion-only diffs, test portability

- fs.rsync(): remove the existing dst_entry before yielding EXCLUDE for
  a src entry with an unsupported kind, so an entry inherited via
  hardlink from a prior snapshot doesn't linger in the new one.
- backup.initiate_backup(): compare this run's excluded set against
  the previous snapshot's manifest; a change in exclusions alone now
  counts as backup_changed, so the updated manifest gets written.
- tests: skip mkfifo/AF_UNIX-dependent tests on platforms without
  support, and use TemporaryDirectory/context managers instead of
  manual mkdtemp/unlink for more robust cleanup.

* Remove unused shutil import from test_rsync.py

Left over after switching the socket/fifo tests to
tempfile.TemporaryDirectory(), per Copilot's suppressed comment.

* Fix rm_direntry() no-op on special dst entries

rm_direntry() only handled file/symlink/dir - a FIFO, socket, or
device node at dst (e.g. inherited from an external-rsync snapshot)
silently survived removal, since is_file/is_dir/is_symlink all
return False for it. Any non-directory entry is unlinkable the same
way, so invert the branching: recurse for directories, unlink
everything else.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 03:25:37 +00:00
b4db7c806b Prevent stale, truncated, or changing-file copies (#10)
* Prevent stale, truncated, or changing-file copies

- copy_file() now loops until every byte is actually written (os.write
  may write fewer bytes than given) and compares fstat() on the
  source's own open descriptor before/after the read loop - this
  reflects the underlying inode directly, catching a source file
  truncated, grown, or overwritten in place while being read, and isn't
  fooled by the source path being renamed away mid-copy. Raises
  BackupCreationError (already a fatal, staging-discarding condition in
  initiate_backup) on a mismatch.
- copy_file() returns a sha256 hex digest of the copied content;
  copy_direntry()/update_direntry() propagate it; rsync() carries it
  through the previously-unused msg field for CREATE/REWRITE actions.
- initiate_backup() collects those digests into a checksums dict keyed
  by path relative to the snapshot root, recorded in the completion
  manifest (already JSON since the topology-validation work).
- Added verify_snapshot(): re-hashes every file with a recorded
  checksum and reports any mismatch, satisfying the release gate's
  "completed snapshot passes manifest verification" requirement.
- Switched every mtime comparison and os.utime() restore (rsync's
  file/directory sync, hardlink_dir's directory metadata, the
  hardlink-breaking copy-on-write step) from float seconds to
  nanoseconds, so a same-second modification can't be missed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review: hash checksums for external rsync too, fix log/error text

- initiate_backup() now hashes CREATE/REWRITE files itself when msg is
  empty (fs.rsync_ext(), the external-rsync path, never yields a
  digest). Without this, verify_snapshot() silently became a no-op for
  every snapshot created with external_rsync=True.
- Fixed a pre-existing log message that said "different inodes" for
  the branch whose actual condition is src/dst sharing an inode.
- verify_snapshot()'s error message now also mentions a corrupt
  manifest, not just missing/pre-migration, matching what
  _read_manifest() actually distinguishes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-04 00:10:25 +00:00
cc61aed10c Preserve symlinks and old-snapshot immutability (#9)
* Preserve symlinks and old-snapshot immutability

Two real bugs found while implementing this item, both in fs.py:

- copy_direntry() checked entry.is_dir() (default follow_symlinks=True)
  before entry.is_symlink(). A symlink pointing at a directory was
  misclassified as a directory and an empty real directory was created
  in its place, silently destroying the symlink and losing its target
  entirely. Fixed by checking is_symlink() first, and is_dir() with
  follow_symlinks=False.
- rsync()'s permission/ownership-sync branch called os.chmod/os.chown
  on dst_entry.path unconditionally. Two problems: (1) for a symlink
  whose target already matched, this had no follow_symlinks=False
  guard and could rewrite an external symlink target's permissions;
  (2) for a regular file, that path may still be hardlinked to the
  same file in the previous, completed snapshot (hardlink_dir() links
  unchanged files in at the start of every backup) - mutating it in
  place silently corrupted every older snapshot sharing the inode.
  Fixed by skipping symlinks entirely (nothing to sync once their
  target matches) and adding _break_shared_hardlink(), a copy-on-write
  step that gives a file its own inode before any in-place metadata
  change.

Also fixed the dir-mtime-restore loop's is_dir() call (same
default-follow_symlinks issue, lower severity since its own operations
were already lstat-based/no-follow).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review: preserve ownership/timestamps when breaking hardlinks, fix test fd leak

- _break_shared_hardlink() now explicitly restores the original file's
  uid/gid and atime/mtime on the new private copy before it replaces
  the shared one. copy_file() only carries over mode at create time, so
  without this a caller that only meant to update permissions would
  silently also reset ownership/mtime as a side effect of the
  copy-on-write break itself. Also cleans up the temp file on failure
  and uses a less collision-prone temp name.
- Fixed a file descriptor leak in the new hardlink-immutability test
  (bare open(...).read() without a context manager)
- Strengthened the same test to assert mtime survives the break

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 23:08:24 +00:00
fd613edad0 Correct retention before enabling automatic deletion (#8)
* Correct retention before enabling automatic deletion

- Compute each retention tier's kept set independently from its own
  name range and union them, instead of carrying a single 'previous
  backup' comparison across tier boundaries - that carry-over was the
  actual cause of bug #32 (a coarser tier could evict a backup a finer
  tier, or the always-keep-latest rule, had already decided to retain)
- Group weekly retention by (ISO year, ISO week) instead of ISO week
  number alone, fixing bug #33 (same week number in different years,
  or late-December dates that belong to next year's ISO week 1, were
  treated as duplicates/collisions)
- Validate the computed retention plan (latest snapshot present, no
  phantom entries) before deleting anything
- Fix cli.py to run initiate_backup before cleanup_old_backups, and
  skip cleanup entirely if the backup raised - retention must only run
  once a new snapshot is durable and complete, and a failed backup must
  never trigger deletion of history
- Quarantine (rename) a deletion candidate before recursively removing
  it, reusing the already-hardened stale-staging-dir cleanup to finish
  the job if the process crashes mid-delete
- Remove both retention xfail markers (bugs #32, #33) now that the
  tests they guarded pass; update pre-existing tests whose expectations
  encoded the old bug (deleting the latest snapshot when it collided
  with the next-newest one in a coarser bucket)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review: replace asserts with runtime checks, don't swallow quarantine-delete failures

- Retention-plan validation now raises BackupFailedError instead of
  using assert, which python -O would silently strip ahead of a
  destructive operation
- _quarantine_and_delete no longer passes ignore_errors=True to
  rmtree; a removal failure is now logged with the quarantine path so
  operators can find and retry it, instead of silently leaving a
  hidden directory consuming space

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 22:47:43 +00:00
72a8fe2b59 Validate topology and destructive path boundaries (#7)
* Validate topology and destructive path boundaries

- Canonicalize sources/backups_dir and reject overlap in either direction
- Reject duplicate sources and destination basename collisions
- Reject non-normalized relative paths in nest_hardlink
- Give each backup repository a persistent identity, recorded in every
  snapshot's completion manifest
- Verify repo identity, directory type (no symlinks), containment, and
  device before any recursive snapshot/staging-dir deletion, refusing to
  cross mount points

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review: root-path check, symlink/TOCTOU-safe writes, legacy marker adoption

- _is_same_or_within: drop the redundant, root-mishandling startswith
  check; commonpath() alone is already component-aware
- _ensure_repo_id/_write_manifest: write via temp-file + atomic rename
  (O_NOFOLLOW, O_EXCL on the temp file) instead of open+write in place,
  so writes can never go through a pre-existing symlink and are never
  left half-written
- _verify_safe_to_delete: distinguish a legacy empty marker (pre-dates
  the manifest format, can only be a pre-migration artifact) from a
  non-empty-but-invalid one (corrupt or forged); adopt the former into
  the repository instead of refusing to delete it forever

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 22:26:51 +00:00
a987180653 Replace PID-file process killing with a real fcntl.flock() lock (#6)
* Replace PID-file process killing with a real fcntl.flock() lock

set_backups_lock()/release_backups_lock() now use an exclusive
fcntl.flock() on the lock file's inode instead of trusting the PID
written inside it. The kernel releases the lock automatically on
normal exit, on any signal, and on a crash - no PID liveness check or
staleness heuristic is needed, and there is nothing left in this code
path that sends a signal to another process.

- The open file descriptor is held for the full operation in a
  module-level _held_locks map keyed by the backups directory, and
  release_backups_lock() only ever releases a descriptor this process
  itself acquired, never one it infers from the lock file's content.
- PID and start time are still written into the lock file, but purely
  as diagnostics for whoever reads it (e.g. in a warning log line);
  they play no role in acquisition or release decisions anymore.
- --force no longer sends SIGTERM/SIGKILL to the previous holder. It
  now blocks on the same flock() until that process releases the lock
  on its own (exit, signal, or crash all count).
- release_backups_lock() intentionally stops unlinking the lock file:
  since flock() locks an inode rather than a path, unlinking while
  another process is blocked opening the same path would let that
  process (or a third one) acquire an independent lock on a fresh
  inode at the same path, defeating mutual exclusion.

Rewrites TestBackupLock to match: a real second file descriptor with
its own flock() stands in for "another process" in the fast unit
tests, and a new subprocess-based test proves end-to-end that only one
process can hold the lock and that killing the holder with SIGKILL
frees it for the next acquirer without our code ever calling os.kill.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review feedback on flock-based lock

- Make the fcntl import optional (try/except ImportError -> None), so
  importing curateipsum.backup no longer crashes on Windows before
  cli.py's own "Not supported platform" check gets a chance to run.
- Guard set_backups_lock() against being called twice for a directory
  this process already holds: it now fails fast instead of silently
  overwriting the tracked fd in _held_locks, which would leak the
  original descriptor and leave the lock held even after
  release_backups_lock() closes only the newest one.
- Wrap the post-acquire metadata write (ftruncate/write/fsync) in a
  try/except: a failure there now releases the flock and closes the fd
  before returning False, instead of leaving the lock held with
  no caller aware of it.
- Cap _read_lock_metadata()'s read and strip newlines before logging,
  so a stale or forged lock file can't inject bogus log lines or force
  an unbounded read.

Adds a regression test for the double-acquire guard.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 22:00:21 +00:00
a48eaf8117 Make snapshot creation transactional (#5)
* Make snapshot creation transactional

Build each snapshot in a private .incomplete-<name> staging directory
instead of mutating the final backup path directly. Any failure while
building the snapshot (hardlink failure, rsync error, or a single
Actions.ERROR entry) is now fatal: the staging directory is discarded
and BackupFailedError is raised, so a failed or interrupted backup can
never silently look like a success.

On success, the completion marker is written and the directory fsync'd
before an atomic os.rename() into the final snapshot name, so a crash
can never leave a partially-populated directory under a real snapshot
name.

Also:
- cleanup_stale_staging_dirs() removes abandoned staging directories
  left by a crashed run before a new backup starts.
- _reserve_snapshot_name() avoids same-second snapshot name collisions.
- cli.py releases the backup lock in finally and returns a nonzero
  exit code when BackupFailedError is raised.

Updates the error-recovery tests that previously asserted failures
were swallowed silently to assert BackupFailedError is raised instead,
matching the new fail-loud contract.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* Address Copilot review feedback on transactional snapshots

- Remove unused uuid import.
- _reserve_snapshot_name() also checks for a collision with an existing
  .incomplete-<name> staging directory, not just the final snapshot
  name.
- _fsync_dir() opens with O_DIRECTORY where available.
- Fsync the completion marker file itself, and fsync the parent
  backups_dir after the rename, so the marker and the rename survive a
  crash/power loss.
- Re-raise an already-BackupFailedError unchanged (preserving its
  traceback) instead of wrapping it in a new instance; only
  fs.BackupCreationError gets wrapped.
- Wrap the initial os.mkdir(staging.path) failure in BackupFailedError
  so every failure path uses the documented exception.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-03 21:30:39 +00:00
snegov 48ebb7f9ae Remove requirements-dev.txt in favor of uv dependency management
Dependencies are now managed via pyproject.toml and installed with
'uv sync --all-extras --dev'. This aligns with the workflow update.
2026-02-05 22:37:33 -08:00
snegov 96f063d877 Update Python version requirement to 3.8 or higher 2026-02-06 04:51:30 +00:00
snegov 79b56d770f Update github workflow to use uv 2026-02-05 20:44:03 -08:00
snegov 7c54bf3823 Fix PseudoDirEntry follow_symlinks handling and add documentation
- Fix follow_symlinks parameter being ignored in is_dir(), is_file()
- Change from realpath() to abspath() to preserve symlinks
- Add separate caches for stat() and lstat() results
- Remove incorrect follow_symlinks param from is_symlink()
- Add comprehensive docstring explaining purpose and design

When follow_symlinks=False, methods now correctly return False for
symlinks instead of following them. Previously all symlinks were
resolved, breaking symlink-aware backup operations.

Fixes #8
2026-02-04 23:00:06 -08:00
snegov 52b4fef814 Add error recovery tests for backup failures
Adds 7 new tests in TestErrorRecovery class covering:
- Hardlink failure cleanup (incomplete backup removal)
- Rsync failure cleanup
- Detection of incomplete backups without marker files
- Lock handling after backup failures
- Permission error handling during cleanup

Tests verify that failed backups are properly cleaned up and don't interfere
with subsequent backup operations or lock management.
2026-02-04 22:21:02 -08:00
snegov 84c8425422 Add tests for external rsync and hardlink tools
Tests --external-rsync and --external-hardlink flags with conditional
execution based on tool availability. Verifies external tools correctly
sync files and preserve hardlinks for unchanged files.
2026-02-04 22:14:04 -08:00
snegov e9a65a9b88 Add tests for rsync edge cases
Covers real-world scenarios: broken symlinks, unicode/spaces in filenames,
empty files, and deeply nested paths. All edge cases handled correctly.
2026-02-04 22:00:55 -08:00
snegov 95614b6eec Add metadata preservation tests for copy_direntry
Verify that timestamps, permissions, and ownership are correctly
preserved when copying files, directories, and symlinks. Tests account
for filesystem behavior where reading a file updates its atime by
capturing source timestamps before the copy operation.
2026-02-04 21:56:25 -08:00
snegov 3214b48ae8 Add tests for ISO week calendar boundary edge cases
Tests cover week 53 year transitions, same week numbers across years,
and late December dates in week 1 of next year. Discovered bug #33
where weekly retention compares only week number without ISO year,
causing backups 1 year apart to be incorrectly deduplicated.
2026-02-04 21:49:23 -08:00
snegov f0894584d4 Add tests for force lock behavior with signal handling
Tests verify --force flag properly handles running processes:
- SIGTERM success (process terminates gracefully)
- SIGKILL escalation (process survives SIGTERM)
- Kill failure handling (permission errors)
2026-02-04 21:03:46 -08:00
snegov 06583f7e1a Add test for combined retention policy interaction
Add test_combined_retention_policies to verify all 5 retention policies
(keep_all, keep_daily, keep_weekly, keep_monthly, keep_yearly) work
correctly together. Test validates precedence rules where later retention
tiers can override earlier ones (e.g., monthly overrides weekly, yearly
overrides monthly) and documents threshold inclusive behavior.

Test uses 36 backups spanning 2017-2021 with expected 21 backups kept
based on policy interaction.
2026-02-04 20:58:06 -08:00
snegov fb9dcbd392 Refactor: split rsync tests into separate module
Move all rsync-related tests (44 tests) from test_fs.py to new
test_rsync.py module for better organization:
- TestRsync (14 tests)
- TestRsyncBasic (5 tests)
- TestParseRsyncOutput (17 tests)
- TestRsyncExt (8 tests)

Extract shared helper functions to conftest.py to eliminate duplication:
- create_file(), create_dir(), relpath()
- check_identical_file()
- common_fs_dirs fixture

This improves test organization and maintainability by grouping related
tests and removing code duplication between test modules.
2026-02-04 20:23:51 -08:00
snegov dc9bc2e5e4 Add comprehensive CLI tests
Implements 26 tests across 6 test classes covering all CLI functionality:
- Argument parsing and flag handling
- Platform validation (Linux/macOS only)
- External tool availability checks (rsync, cp, gcp)
- Directory validation
- Lock acquisition and release
- Backup execution flow

Brings CLI module from zero coverage to complete test coverage.
Total test count: 99 → 127 tests (all passing).
2026-02-04 19:40:59 -08:00
snegov fe48010fc9 Add comprehensive tests for rsync output parsing
Implements TestParseRsyncOutput class with 17 tests covering all code
paths in _parse_rsync_output() function. Tests cover deletions, file/
directory/symlink creation, rewrites, metadata updates (permissions,
ownership, timestamps), and error handling for invalid input.
2026-02-04 19:36:24 -08:00
snegov ee1df4cb21 Update tests 2026-02-04 19:31:29 -08:00
snegov 5dc9235992 Fix potential NameError in copy_file exception handler
Initialize file descriptors to None before opening to prevent
UnboundLocalError in the finally block if file opening fails.

Changes:
- Initialize fin = None and fout = None at function start
- Check if descriptors are not None before closing
- Remove UnboundLocalError from exception handling (no longer needed)

This improves code quality by eliminating the need to catch an error
that indicates a logic bug. The existing tests verify correct behavior.

Fixes #6
2026-02-03 22:20:52 -08:00
Claude 7c59bbc90b Fix high-priority bugs and add comprehensive test coverage
This commit addresses 8 high-priority issues identified in code analysis.

Fixes #3
Fixes #4
Fixes #5
Fixes #7
Fixes #10
Fixes #19
Fixes #20
Fixes #21

## Critical Bug Fixes

1. **Race condition in lock file creation (#3)**
   - Changed to atomic file creation using os.O_CREAT | os.O_EXCL
   - Prevents two processes from both acquiring the lock
   - Location: curateipsum/backup.py:110-115

2. **Invalid lock file error handling (#4)**
   - Added try/except for corrupted/empty lock files
   - Gracefully removes corrupted locks and retries
   - Location: curateipsum/backup.py:121-133

3. **SIGKILL vs SIGTERM issue (#5)**
   - Now sends SIGTERM first for graceful shutdown
   - Waits 5 seconds before escalating to SIGKILL
   - Allows previous process to clean up resources
   - Location: curateipsum/backup.py:146-156

4. **Wrong stat object for permissions (#7)**
   - Fixed bug where dst_stat was used instead of src_stat
   - Permissions are now correctly updated during rsync
   - Location: curateipsum/fs.py:371

5. **os.chown() fails for non-root users (#10)**
   - Wrapped all os.chown() calls in try/except blocks
   - Logs debug message instead of crashing
   - Allows backups to succeed for non-root users
   - Locations: curateipsum/fs.py:217-221, 228-231, 383-387, 469-472

## Comprehensive Test Coverage

6. **Lock file tests (#19)**
   - Added TestBackupLock class with 7 test cases
   - Tests: creation, concurrent prevention, stale locks, corruption
   - Location: tests/test_backups.py:228-330

7. **Filesystem operation tests (#20)**
   - Added tests/test_fs_extended.py with 6 test classes
   - Tests: copy_file, copy_direntry, rsync, hardlink_dir, scantree, rm_direntry
   - 20+ test cases covering normal and edge cases
   - Location: tests/test_fs_extended.py

8. **Integration tests (#21)**
   - Added tests/test_integration.py with 2 test classes
   - Tests full backup workflow end-to-end
   - Tests: incremental backups, hardlinks, delta dirs, cleanup, recovery
   - 14 test cases covering complete backup lifecycle
   - Location: tests/test_integration.py

## Test Results
All 68 tests pass successfully:
- 11 original backup cleanup tests
- 7 new lock file tests
- 16 original fs tests
- 20 new fs extended tests
- 14 new integration tests

## Impact
These fixes address critical bugs that could cause:
- Data corruption from concurrent backups
- Incomplete cleanup from forced process termination
- Permission sync failures
- Tool unusability for non-root users

The comprehensive test coverage ensures these bugs are caught early
and provides confidence for future refactoring.
2026-02-03 22:09:28 -08:00
snegov 32ce113608 Migrate to pyproject.toml with setuptools_scm
Replace custom version management with setuptools_scm to eliminate
source file modifications during installation. Version is now derived
from git tags at build time without writing to tracked files.

Changes:
- Add pyproject.toml with full project metadata
- Simplify setup.py to minimal backwards-compatible shim
- Remove curateipsum/_version.py from version control
- Add _version.py to .gitignore (auto-generated at build time)
- Use PEP 440 compliant version strings

Fixes #18
2026-02-03 21:27:49 -08:00
snegov 6fd6051642 Merge pull request #4 from snegov/claude/fix-github-actions-python-versions-011CUyaqGCtZoDZVxANHBu2n
Fix GitHub Actions Python version testing
2025-11-09 20:55:42 -08:00
Claude 22933d7520 Fix GitHub Actions workflow to support Python 3.6-3.14
Use Docker containers with official Python images to run tests across
all Python versions from 3.6 to 3.14. This approach:

- Eliminates "workers not found" errors from deprecated Ubuntu runners
- Provides reliable support for older Python versions (3.6, 3.7)
- Simplifies workflow configuration significantly
- Uses official python:X.Y Docker images maintained by Python team
- Sets fail-fast: false to test all versions independently
2025-11-10 04:50:39 +00:00
Claude 6839d21a77 Add comprehensive README documentation
- Project overview and features
- Installation and usage instructions
- Detailed explanation of how hardlink-based backups work
- Command-line options and examples
- Backup structure and retention policy details
- Development and testing information
2025-11-09 20:23:56 -08:00
22 changed files with 7468 additions and 671 deletions

No files matched your search

+27 -13
View File
@@ -1,23 +1,37 @@
name: Run tests name: Run tests
on: [push] on:
pull_request:
push:
branches: [master]
jobs: jobs:
build: test:
runs-on: ubuntu-20.04 runs-on: ${{ matrix.os }}
strategy: strategy:
fail-fast: false
matrix: matrix:
python-version: ["3.6", "3.7", "3.8", "3.9", "3.10", "3.11"] 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: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v6
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2 - name: Install uv and set the Python version
uses: astral-sh/setup-uv@v7
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: | - name: Install the project
python -m pip install --upgrade pip run: uv sync --all-extras --dev
pip install -r requirements-dev.txt
- name: Run tests - name: Run tests
run: | run: uv run pytest tests
python -m pytest -v
+5 -1
View File
@@ -25,6 +25,9 @@ wheels/
*.egg *.egg
MANIFEST MANIFEST
# Version file generated by setuptools_scm
curateipsum/_version.py
# PyInstaller # PyInstaller
# Usually these files are written by a python script from a template # 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. # before PyInstaller builds the exe, so as to inject date/other infos into it.
@@ -72,8 +75,9 @@ target/
# Jupyter Notebook # Jupyter Notebook
.ipynb_checkpoints .ipynb_checkpoints
# pyenv # uv
.python-version .python-version
uv.lock
# celery beat schedule file # celery beat schedule file
celerybeat-schedule celerybeat-schedule
+134
View File
@@ -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
```
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+242
View File
@@ -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.
+278
View File
@@ -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
View File
@@ -1 +0,0 @@
version = "master"
+753 -147
View File
File diff suppressed because it is too large. Load diff
+251 -30
View File
@@ -8,18 +8,42 @@ import sys
import time import time
from datetime import timedelta from datetime import timedelta
from curateipsum import backup from curateipsum import backup, restore
from curateipsum._version import version from curateipsum._version import version
_lg = logging.getLogger("curateipsum") _lg = logging.getLogger("curateipsum")
SUPPORTED_PLATFORMS = ("linux", "darwin") SUPPORTED_PLATFORMS = ("linux", "darwin")
_SUBCOMMANDS = ("backup", "restore")
_TOP_LEVEL_FLAGS = ("-h", "--help", "-V", "--version")
def main(): def _normalize_argv(argv):
formatter = logging.Formatter("{asctime}|{levelname}|{message}", style="{") """
console_handler = logging.StreamHandler() Insert the implicit "backup" subcommand when argv doesn't already
console_handler.setFormatter(formatter) 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( parser = argparse.ArgumentParser(
prog="cura-te-ipsum", prog="cura-te-ipsum",
description="cura-te-ipsum, my personal backup software.", description="cura-te-ipsum, my personal backup software.",
@@ -27,49 +51,117 @@ def main():
parser.add_argument("-V", "--version", parser.add_argument("-V", "--version",
action="version", action="version",
version=f"%(prog)s v{version}") version=f"%(prog)s v{version}")
parser.add_argument("-v", "--verbose",
common = argparse.ArgumentParser(add_help=False)
common.add_argument("-v", "--verbose",
action="store_true", action="store_true",
default=False, default=False,
help="print verbose information") help="print verbose information")
parser.add_argument("-b", common.add_argument("-b",
dest="backups_dir", dest="backups_dir",
metavar="BACKUPS_DIR", metavar="BACKUPS_DIR",
type=str, type=str,
required=True, required=True,
help="directory, where all backups will be stored") help="directory, where all backups will be stored")
parser.add_argument("-n", "--dry-run", common.add_argument("-f", "--force",
action="store_true", action="store_true",
default=False, default=False,
help="Do not do create backup") help="Wait for a running backup/restore to finish "
parser.add_argument("-f", "--force", "instead of exiting immediately")
common.add_argument("-n", "--dry-run",
action="store_true", action="store_true",
default=False, default=False,
help="Force run when previous backup is still in process") help="show what would be done, without doing it")
parser.add_argument("--external-rsync",
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", action="store_true",
default=False, default=False,
help="Use external rsync for copying") help="Use external rsync for copying")
parser.add_argument("--external-hardlink", backup_parser.add_argument("--external-hardlink",
action="store_true", action="store_true",
default=False, default=False,
help="Use cp command for creating hardlink copies") help="Use cp command for creating hardlink "
parser.add_argument("sources", "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="+", nargs="+",
metavar="SOURCE", metavar="SOURCE",
type=str, type=str,
help="backup source (file/dir/smth else)") help="backup source (file/dir/smth else)")
args = parser.parse_args()
loglevel = logging.DEBUG if args.verbose else logging.INFO restore_parser = subparsers.add_parser(
logging.basicConfig(level=loglevel, handlers=[console_handler]) "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)")
_lg.info("Starting %s: %s", parser.prog, args) return parser
if sys.platform not in SUPPORTED_PLATFORMS:
_lg.error("Not supported platform: %s. Supported platforms: %s",
sys.platform, SUPPORTED_PLATFORMS)
return 1
def _run_backup(args) -> int:
if args.external_rsync and not shutil.which("rsync"): if args.external_rsync and not shutil.which("rsync"):
_lg.error("rsync should be installed to use --external-rsync option.") _lg.error("rsync should be installed to use --external-rsync option.")
return 1 return 1
@@ -91,14 +183,28 @@ def main():
_lg.error("Source directory %s does not exist", src_dir) _lg.error("Source directory %s does not exist", src_dir)
return 1 return 1
start_time = time.time() try:
backup.validate_topology(args.sources, backups_dir_abs)
if not backup.set_backups_lock(backups_dir_abs, args.force): except backup.BackupFailedError as err:
_lg.error("Unsafe source/backups layout: %s", err)
return 1 return 1
# TODO add cleaning up from non-finished backups start_time = time.time()
backup.cleanup_old_backups(backups_dir=backups_dir_abs,
dry_run=args.dry_run) # 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( backup.initiate_backup(
sources=args.sources, sources=args.sources,
backups_dir=backups_dir_abs, backups_dir=backups_dir_abs,
@@ -106,13 +212,128 @@ def main():
external_rsync=args.external_rsync, external_rsync=args.external_rsync,
external_hardlink=args.external_hardlink, 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) backup.release_backups_lock(backups_dir_abs)
end_time = time.time() end_time = time.time()
spent_time = end_time - start_time spent_time = end_time - start_time
_lg.info("Finished, time spent: %s", str(timedelta(seconds=spent_time))) _lg.info("Finished, time spent: %s", str(timedelta(seconds=spent_time)))
return 0 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():
formatter = logging.Formatter("{asctime}|{levelname}|{message}", style="{")
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
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])
_lg.info("Starting %s: %s", parser.prog, args)
if sys.platform not in SUPPORTED_PLATFORMS:
_lg.error("Not supported platform: %s. Supported platforms: %s",
sys.platform, SUPPORTED_PLATFORMS)
return 1
if args.command == "restore":
return _run_restore(args)
return _run_backup(args)
if __name__ == "__main__": if __name__ == "__main__":
+367 -66
View File
@@ -4,11 +4,14 @@ Module with filesystem-related functions.
import enum import enum
import glob import glob
import hashlib
import logging import logging
import os import os
import stat
import subprocess import subprocess
import sys import sys
from typing import Iterable, Tuple, Union import uuid
from typing import Iterable, Optional, Tuple, Union
_lg = logging.getLogger(__name__) _lg = logging.getLogger(__name__)
@@ -26,40 +29,115 @@ class Actions(enum.Enum):
UPDATE_OWNER = enum.auto() UPDATE_OWNER = enum.auto()
CREATE = enum.auto() CREATE = enum.auto()
ERROR = 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: 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): 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.name = os.path.basename(self.path)
self._is_dir = None self._is_dir = None
self._is_file = None self._is_file = None
self._is_symlink = None self._is_symlink = None
self._stat = None # Cache both stat and lstat separately
self._stat_follow = None
self._stat_nofollow = None
def __str__(self): def __str__(self):
return self.name return self.name
def is_dir(self, follow_symlinks: bool = True) -> bool: def is_dir(self, follow_symlinks: bool = True) -> bool:
if follow_symlinks:
if self._is_dir is None: if self._is_dir is None:
self._is_dir = os.path.isdir(self.path) self._is_dir = os.path.isdir(self.path)
return self._is_dir 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 is_file(self, follow_symlinks: bool = True) -> bool: def is_file(self, follow_symlinks: bool = True) -> bool:
if follow_symlinks:
if self._is_file is None: if self._is_file is None:
self._is_file = os.path.isfile(self.path) self._is_file = os.path.isfile(self.path)
return self._is_file 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, follow_symlinks: bool = True) -> bool: def is_symlink(self) -> bool:
if self._is_symlink is None: if self._is_symlink is None:
self._is_symlink = os.path.islink(self.path) self._is_symlink = os.path.islink(self.path)
return self._is_symlink return self._is_symlink
def stat(self, follow_symlinks: bool = True): def stat(self, follow_symlinks: bool = True):
if self._stat is None: if follow_symlinks:
func = os.stat if follow_symlinks else os.lstat if self._stat_follow is None:
self._stat = func(self.path) self._stat_follow = os.stat(self.path)
return self._stat 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, str]: def _parse_rsync_output(line: str) -> Tuple[str, Actions, str]:
@@ -103,6 +181,7 @@ def rsync_ext(src, dst, dry_run=False) -> Iterable[Tuple[str, Actions, str]]:
# rsync_args.append("--inplace") # rsync_args.append("--inplace")
rsync_args.append("--whole-file") rsync_args.append("--whole-file")
rsync_args.append("--human-readable") rsync_args.append("--human-readable")
rsync_args.append("--one-file-system")
rsync_args.append("--delete-during") rsync_args.append("--delete-during")
rsync_args.append("--itemize-changes") rsync_args.append("--itemize-changes")
rsync_args.append(f"{src}/") rsync_args.append(f"{src}/")
@@ -141,17 +220,38 @@ def rsync_ext(src, dst, dry_run=False) -> Iterable[Tuple[str, Actions, str]]:
process.wait() process.wait()
def scantree(path, dir_first=True) -> Iterable[os.DirEntry]: 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. 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 entry: os.DirEntry
with os.scandir(path) as scan_it: with os.scandir(path) as scan_it:
for entry in scan_it: for entry in scan_it:
if entry.is_dir(follow_symlinks=False): 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: if dir_first:
yield entry yield entry
yield from scantree(entry.path, dir_first) yield from scantree(entry.path, dir_first,
one_filesystem, _root_dev)
if not dir_first: if not dir_first:
yield entry yield entry
else: else:
@@ -159,15 +259,19 @@ def scantree(path, dir_first=True) -> Iterable[os.DirEntry]:
def rm_direntry(entry: Union[os.DirEntry, PseudoDirEntry]): def rm_direntry(entry: Union[os.DirEntry, PseudoDirEntry]):
""" Recursively delete DirEntry (dir/file/symlink). """ """
if entry.is_file(follow_symlinks=False) or entry.is_symlink(): Recursively delete DirEntry. Directories are removed recursively;
os.unlink(entry.path) anything else (file, symlink, or a special entry like a FIFO,
elif entry.is_dir(follow_symlinks=False): socket, or device node) is unlinked directly.
"""
if entry.is_dir(follow_symlinks=False):
with os.scandir(entry.path) as it: with os.scandir(entry.path) as it:
child_entry: os.DirEntry child_entry: os.DirEntry
for child_entry in it: for child_entry in it:
rm_direntry(child_entry) rm_direntry(child_entry)
os.rmdir(entry.path) os.rmdir(entry.path)
else:
os.unlink(entry.path)
try: try:
@@ -179,62 +283,172 @@ WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | O_BINARY
BUFFER_SIZE = 128 * 1024 BUFFER_SIZE = 128 * 1024
def copy_file(src, dst): def _write_all(fd: int, data: bytes):
""" Copy file from src to dst. Faster than shutil.copy. """ """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: try:
fin = os.open(src, READ_FLAGS) fin = os.open(src, READ_FLAGS)
fstat = os.fstat(fin) stat_before = os.fstat(fin)
fout = os.open(dst, WRITE_FLAGS, fstat.st_mode) fout = os.open(dst, WRITE_FLAGS, stat_before.st_mode)
for x in iter(lambda: os.read(fin, BUFFER_SIZE), b""): digest = hashlib.sha256()
os.write(fout, x) 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: finally:
if fout is not None:
try: try:
os.close(fout) os.close(fout)
except (OSError, UnboundLocalError): except OSError:
pass pass
if fin is not None:
try: try:
os.close(fin) os.close(fin)
except (OSError, UnboundLocalError): except OSError:
pass pass
def copy_direntry(entry: Union[os.DirEntry, PseudoDirEntry], dst_path): def _break_shared_hardlink(path: str):
""" Non-recursive DirEntry (file/dir/symlink) copy. """ """
src_stat = entry.stat(follow_symlinks=False) Give `path` a private inode if it currently shares one with another
if entry.is_dir(): file (nlink > 1), so a subsequent in-place metadata change (chmod,
os.mkdir(dst_path) 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.
elif entry.is_symlink(): 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: 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) link_target = os.readlink(entry.path)
os.symlink(link_target, dst_path) os.symlink(link_target, dst_path)
else: elif entry.is_dir(follow_symlinks=False):
copy_file(entry.path, dst_path) os.mkdir(dst_path)
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(): if entry.is_symlink():
# change symlink attributes only if supported by OS # change symlink attributes only if supported by OS
if os.chown in os.supports_follow_symlinks: if os.chown in os.supports_follow_symlinks:
try:
os.chown(dst_path, src_stat.st_uid, src_stat.st_gid, os.chown(dst_path, src_stat.st_uid, src_stat.st_gid,
follow_symlinks=False) follow_symlinks=False)
except PermissionError:
_lg.debug("Cannot change ownership (not root): %s", dst_path)
if os.chmod in os.supports_follow_symlinks: if os.chmod in os.supports_follow_symlinks:
os.chmod(dst_path, src_stat.st_mode, follow_symlinks=False) os.chmod(dst_path, src_stat.st_mode, follow_symlinks=False)
if os.utime in os.supports_follow_symlinks: 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) follow_symlinks=False)
else: else:
try:
os.chown(dst_path, src_stat.st_uid, src_stat.st_gid) 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.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. Make dst DirEntry (file/dir/symlink) same as src.
If dst is directory, its content will be removed. If dst is directory, its content will be removed.
Src dir content will not be copied into dst dir. Src dir content will not be copied into dst dir.
:return: see copy_direntry().
""" """
rm_direntry(dst_entry) rm_direntry(dst_entry)
copy_direntry(src_entry, dst_entry.path) return copy_direntry(src_entry, dst_entry.path)
def _maybe_update(src_entry: os.DirEntry, dst_entry: os.DirEntry,
dry_run: bool) -> Optional[str]:
"""
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, def rsync(src_dir,
@@ -245,6 +459,14 @@ def rsync(src_dir,
Yield (path, action, error message) tuples. Yield (path, action, error message) tuples.
Entries in dst_dir will be removed if not present in src_dir. Entries in dst_dir will be removed if not present in src_dir.
Analog of 'rsync --delete -irltpog'. 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) _lg.debug("Rsync: %s -> %s", src_dir, dst_dir)
@@ -255,21 +477,28 @@ def rsync(src_dir,
raise BackupCreationError( raise BackupCreationError(
"Error during reading source directory: %s" % src_root_abs "Error during reading source directory: %s" % src_root_abs
) )
if os.path.exists(dst_root_abs): dst_exists = os.path.exists(dst_root_abs)
if not os.path.isdir(dst_root_abs): if dst_exists and not os.path.isdir(dst_root_abs):
raise BackupCreationError( raise BackupCreationError(
"Destination path is not a directory: %s" % dst_root_abs "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: else:
os.mkdir(dst_root_abs) os.mkdir(dst_root_abs)
# Create source map {rel_path: dir_entry} # Create source map {rel_path: dir_entry}
src_files_map = { 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 # 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:] rel_path = dst_entry.path[len(dst_root_abs) + 1:]
src_entry = src_files_map.get(rel_path) src_entry = src_files_map.get(rel_path)
@@ -277,6 +506,9 @@ def rsync(src_dir,
# remove dst entries not existing in source # remove dst entries not existing in source
if src_entry is None: if src_entry is None:
_lg.debug("Rsync, deleting: %s", rel_path) _lg.debug("Rsync, deleting: %s", rel_path)
if dry_run:
yield rel_path, Actions.DELETE, ""
continue
try: try:
rm_direntry(dst_entry) rm_direntry(dst_entry)
yield rel_path, Actions.DELETE, "" yield rel_path, Actions.DELETE, ""
@@ -288,6 +520,21 @@ def rsync(src_dir,
del src_files_map[rel_path] del src_files_map[rel_path]
src_entry: os.DirEntry src_entry: os.DirEntry
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 # rewrite dst if it has different type from src
if src_entry.is_file(follow_symlinks=False): if src_entry.is_file(follow_symlinks=False):
if not dst_entry.is_file(follow_symlinks=False): if not dst_entry.is_file(follow_symlinks=False):
@@ -295,9 +542,9 @@ def rsync(src_dir,
" (src is a file, dst is not a file): %s", " (src is a file, dst is not a file): %s",
rel_path) rel_path)
try: try:
update_direntry(src_entry, dst_entry) digest = _maybe_update(src_entry, dst_entry, dry_run)
yield rel_path, Actions.REWRITE, "" yield rel_path, Actions.REWRITE, digest or ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(exc) yield rel_path, Actions.ERROR, str(exc)
continue continue
@@ -307,9 +554,9 @@ def rsync(src_dir,
" (src is a dir, dst is not a dir): %s", " (src is a dir, dst is not a dir): %s",
rel_path) rel_path)
try: try:
update_direntry(src_entry, dst_entry) _maybe_update(src_entry, dst_entry, dry_run)
yield rel_path, Actions.REWRITE, "" yield rel_path, Actions.REWRITE, ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(exc) yield rel_path, Actions.ERROR, str(exc)
continue continue
@@ -319,19 +566,19 @@ def rsync(src_dir,
" (src is a symlink, dst is not a symlink): %s", " (src is a symlink, dst is not a symlink): %s",
rel_path) rel_path)
try: try:
update_direntry(src_entry, dst_entry) _maybe_update(src_entry, dst_entry, dry_run)
yield rel_path, Actions.REWRITE, "" yield rel_path, Actions.REWRITE, ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(exc) yield rel_path, Actions.ERROR, str(exc)
continue continue
# rewrite dst if it is hard link to src (bad for backups) # rewrite dst if it is hard link to src (bad for backups)
if src_entry.inode() == dst_entry.inode(): if src_entry.inode() == dst_entry.inode():
_lg.debug("Rsync, rewriting (different inodes): %s", rel_path) _lg.debug("Rsync, rewriting (shared inode with src): %s", rel_path)
try: try:
update_direntry(src_entry, dst_entry) digest = _maybe_update(src_entry, dst_entry, dry_run)
yield rel_path, Actions.REWRITE, "" yield rel_path, Actions.REWRITE, digest or ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(exc) yield rel_path, Actions.ERROR, str(exc)
continue continue
@@ -341,15 +588,15 @@ def rsync(src_dir,
# rewrite dst file/symlink which have different size or mtime than src # rewrite dst file/symlink which have different size or mtime than src
if src_entry.is_file(follow_symlinks=False): if src_entry.is_file(follow_symlinks=False):
same_size = src_stat.st_size == dst_stat.st_size 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): if not (same_size and same_mtime):
reason = "size" if not same_size else "time" reason = "size" if not same_size else "time"
_lg.debug("Rsync, rewriting (different %s): %s", _lg.debug("Rsync, rewriting (different %s): %s",
reason, rel_path) reason, rel_path)
try: try:
update_direntry(src_entry, dst_entry) digest = _maybe_update(src_entry, dst_entry, dry_run)
yield rel_path, Actions.REWRITE, "" yield rel_path, Actions.REWRITE, digest or ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(exc) yield rel_path, Actions.ERROR, str(exc)
continue continue
@@ -359,55 +606,100 @@ def rsync(src_dir,
_lg.debug("Rsync, rewriting (different symlink target): %s", _lg.debug("Rsync, rewriting (different symlink target): %s",
rel_path) rel_path)
try: try:
update_direntry(src_entry, dst_entry) _maybe_update(src_entry, dst_entry, dry_run)
yield rel_path, Actions.REWRITE, "" yield rel_path, Actions.REWRITE, ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(exc) yield rel_path, Actions.ERROR, str(exc)
continue 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 # update permissions and ownership
if src_stat.st_mode != dst_stat.st_mode: if src_stat.st_mode != dst_stat.st_mode:
_lg.debug("Rsync, updating permissions: %s", rel_path) _lg.debug("Rsync, updating permissions: %s", rel_path)
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, "" yield rel_path, Actions.UPDATE_PERM, ""
if (src_stat.st_uid != dst_stat.st_uid if (src_stat.st_uid != dst_stat.st_uid
or src_stat.st_gid != dst_stat.st_gid): or src_stat.st_gid != dst_stat.st_gid):
_lg.debug("Rsync, updating owners: %s", rel_path) _lg.debug("Rsync, updating owners: %s", rel_path)
if dry_run:
yield rel_path, Actions.UPDATE_OWNER, ""
else:
try:
os.chown(dst_entry.path, src_stat.st_uid, src_stat.st_gid) os.chown(dst_entry.path, src_stat.st_uid, src_stat.st_gid)
yield rel_path, Actions.UPDATE_OWNER, "" yield rel_path, Actions.UPDATE_OWNER, ""
except PermissionError:
_lg.debug("Cannot change ownership (not root): %s",
rel_path)
# process remained source entries (new files/dirs/symlinks) # process remained source entries (new files/dirs/symlinks)
for rel_path, src_entry in src_files_map.items(): 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) dst_path = os.path.join(dst_root_abs, rel_path)
_lg.debug("Rsync, creating: %s", rel_path) _lg.debug("Rsync, creating: %s", rel_path)
try: try:
copy_direntry(src_entry, dst_path) digest = copy_direntry(src_entry, dst_path)
yield rel_path, Actions.CREATE, "" yield rel_path, Actions.CREATE, digest or ""
except OSError as exc: except (OSError, BackupCreationError) as exc:
yield rel_path, Actions.ERROR, str(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 # restore dir mtimes in dst, updated by updating files
for src_entry in scantree(src_root_abs, dir_first=True): for src_entry in scantree(src_root_abs, dir_first=True,
if not src_entry.is_dir(): one_filesystem=True):
if not src_entry.is_dir(follow_symlinks=False):
continue continue
rel_path = src_entry.path[len(src_root_abs) + 1:] rel_path = src_entry.path[len(src_root_abs) + 1:]
dst_path = os.path.join(dst_root_abs, rel_path) dst_path = os.path.join(dst_root_abs, rel_path)
src_stat = src_entry.stat(follow_symlinks=False) src_stat = src_entry.stat(follow_symlinks=False)
dst_stat = os.lstat(dst_path) 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) _lg.debug("Rsync, restoring directory mtime: %s", dst_path)
os.utime(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) follow_symlinks=False)
# restore dst_root dir mtime # restore dst_root dir mtime
src_root_stat = os.lstat(src_root_abs) src_root_stat = os.lstat(src_root_abs)
dst_root_stat = os.lstat(dst_root_abs) dst_root_stat = os.lstat(dst_root_abs)
if src_root_stat.st_mtime != dst_root_stat.st_mtime: if src_root_stat.st_mtime_ns != dst_root_stat.st_mtime_ns:
_lg.debug("Rsync, restoring root directory mtime: %s", dst_root_abs) _lg.debug("Rsync, restoring root directory mtime: %s", dst_root_abs)
os.utime(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) follow_symlinks=False)
@@ -457,9 +749,13 @@ def _recursive_hardlink(src: str, dst: str) -> bool:
# save directory's metainfo # save directory's metainfo
ent_stat = ent.stat(follow_symlinks=False) ent_stat = ent.stat(follow_symlinks=False)
try:
os.chown(ent_dst_path, ent_stat.st_uid, ent_stat.st_gid) 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.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 continue
if ent.is_file(follow_symlinks=False) or ent.is_symlink(): if ent.is_file(follow_symlinks=False) or ent.is_symlink():
@@ -504,6 +800,11 @@ def nest_hardlink(src_dir: str, src_relpath: str, dst_dir: str):
""" """
_lg.debug("Nested hardlinking: %s%s%s -> %s", _lg.debug("Nested hardlinking: %s%s%s -> %s",
src_dir, os.path.sep, src_relpath, dst_dir) 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_dir_abs = os.path.abspath(src_dir)
src_full_path = os.path.join(src_dir_abs, src_relpath) src_full_path = os.path.join(src_dir_abs, src_relpath)
dst_dir_abs = os.path.abspath(dst_dir) dst_dir_abs = os.path.abspath(dst_dir)
+190
View File
@@ -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
+41
View File
@@ -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
View File
@@ -1 +0,0 @@
pytest
+4 -47
View File
@@ -1,48 +1,5 @@
import setuptools # Minimal setup.py for backwards compatibility
import subprocess # All configuration is in pyproject.toml
from setuptools import setup
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",
)
+134
View File
@@ -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
+899 -155
View File
File diff suppressed because it is too large. Load diff
+744
View File
@@ -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)]
+734 -210
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+277
View File
@@ -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)
+249
View File
@@ -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))
+902
View File
@@ -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"))