Skip to content

FileCleaner v1.1.0 — Simple 5-Minute HOWTO

Language Editions: English · Français (docs/fr/HOWTO.md)
Related Docs: README · User Guide · Cookbook Examples · Formal Specifications

Get productive with FileCleaner in five minutes: preview safely with plan, enforce deterministic retention with zero-config CLI flags or a 10-line filecleaner.toml, protect live writers and healthy backups, and automate recurring sweeps.


1. The 3-Step Safety Habit: Plan -> Run -> Daemon

Never run a destructive retention rule blind. FileCleaner is built around a three-step workflow:

  1. Preview (plan): Simulates every scan, in-use check, backup guardrail, and eviction decision without modifying, moving, compressing, or deleting a single file.
  2. Enforce (run): Executes the exact same deterministic plan once you have verified which files stay and which files move, compress, trash, or delete.
  3. Automate (daemon or cron): Runs recurring or filesystem-event-driven sweeps unattended with structured JSONL audit logging.

Tip

filecleaner plan --config filecleaner.toml and filecleaner run --config filecleaner.toml --dry-run compute the same eviction set, without invoking pre_delete_hook unless run_in_dry_run = true.


2. Six Zero-Config CLI One-Liners (No Config File Needed)

Pass --dir directly to plan or run (clean is an alias for run) when you want quick cleanup without writing a configuration file. Replace plan with run once the preview looks right.

2.1 Keep Only the N Newest Files (--max-files)

# Preview keeping only the 10 newest archives
filecleaner plan --dir /var/backups/app --include "*.tar.gz" --max-files 10

# Execute once verified
filecleaner run --dir /var/backups/app --include "*.tar.gz" --max-files 10

2.2 Remove Files Older Than a Duration (--max-age)

filecleaner plan --dir /var/log/app --include "*.log" --recursive --max-age 14d

2.3 Cap Total Directory Disk Usage (--max-size)

filecleaner plan --dir /var/cache/builds --max-size 2GiB

2.4 Soft-Delete to Quarantine Trash (--trash-dir)

filecleaner run --dir /var/tmp/exports --max-age 7d --trash-dir /var/tmp/filecleaner-trash

2.5 Rename by Date, Compress, and Archive (--rename-by-date --compress --move-to)

filecleaner run \
  --dir /var/log/nginx \
  --include "*.log" \
  --exclude "current/**" \
  --recursive \
  --max-age 1d \
  --rename-by-date \
  --compress gzip \
  --move-to /mnt/cold-logs

Note: Passing --rename-template "%Y%m%d_%H%M%S" automatically enables rename_by_date even if --rename-by-date is omitted.

2.6 Check If a File Is Still Being Written (check-in-use)

# Exit 0 if safe to touch; exit 10 if any writer/lock/cooldown triggers
filecleaner check-in-use /var/spool/incoming/upload.parquet --idle-age 30s --stability 2s

3. Your First 10-Line Config File (filecleaner.toml)

When you manage multiple directories or want repeatable schedules, create a config file.

3.1 Generate a Starter Config Safely (init)

# Generate a TOML or YAML starter config (`backups`, `logs`, `spool`, or `dba-postgres` profile)
filecleaner init --profile backups --format toml --output filecleaner.toml
filecleaner init --profile dba-postgres --format toml --output pg-wal-s3.toml

Info

Templates generated by filecleaner init intentionally start with dry_run = true so running filecleaner run by mistake will not mutate files until you review plan and flip dry_run = false.

3.2 Minimal 10-Line TOML Config

Save this minimal configuration as filecleaner.toml:

dry_run = true

[[rules]]
name = "downloads-cleanup"
path = "/var/tmp/downloads"
max_age = "30d"
max_files = 50
trash_dir = "/var/tmp/filecleaner-trash"
actions = ["trash"]

Validate syntax and invariants, preview the sweep, then edit dry_run = false to execute:

filecleaner validate --config filecleaner.toml
filecleaner plan --config filecleaner.toml
# Once satisfied, change dry_run = false in filecleaner.toml:
filecleaner run --config filecleaner.toml

4. Protecting Backups with backup_guard

Standard age/count cleanup becomes dangerous if upstream cron backups silently fail or produce 0-byte dumps: ordinary cleanup would eventually delete your remaining good backups. Adding [rules.backup_guard] freezes eviction automatically whenever the backup vault degrades.

4.1 The Five Essential backup_guard Controls

Key Purpose Recommended Starting Value
enabled Turns backup guardrails on (true) or off (false) true
min_keep_files Unconditionally protects the \(N\) newest valid backups 3
min_valid_backup_bytes Ignores corrupt/empty stubs below this size when counting valid backups "1MiB"
require_newer_within Dead-man's-switch: freezes the rule if no valid backup arrived recently "36h"
freeze_on_empty_valid Freezes eviction when zero files meet min_valid_backup_bytes true

4.2 Safe PostgreSQL Vault Example

dry_run = false

[[rules]]
name = "postgres-backups"
path = "/var/backups/postgres"
include_globs = ["pg_*.sql"]
max_files = 14
actions = ["compress", "move"]
compression = "gzip"
move_to = "/mnt/nas/postgres-archive"

[rules.backup_guard]
enabled = true
min_keep_files = 3
min_valid_backup_bytes = "1MiB"
require_newer_within = "36h"
freeze_on_empty_valid = true

Run with --fail-on-freeze in cron or monitoring scripts so your alerting system sees exit code 3 whenever backups stop arriving:

filecleaner run --config filecleaner.toml --fail-on-freeze

5. Vetoing Deletion with pre_delete_hook (Bash & PowerShell)

Attach [rules.pre_delete_hook] when an external check (downstream ingest receipt, replication ACK, database check) must approve a candidate before FileCleaner moves, compresses, or deletes it.

5.1 Environment Variables and Exit Code Contract

FileCleaner executes hooks directly without shell interpolation (zero shell injection) and injects metadata via environment variables such as $FILECLEANER_PATH, $FILECLEANER_NAME, $FILECLEANER_SIZE, and $FILECLEANER_RULE:

  • Exit 0: Approved — proceed with the rule's actions.
  • Exit 42 (configurable via skip_exit_code): Benign per-file veto — skip this file cleanly and keep overall sweep exit code 0.
  • Any other non-zero exit (or timeout): Handled by on_failure ("abort_file" default, "abort_rule" to halt with exit 1, or "warn_and_continue").
dry_run = false
global_trash_dir = "/var/tmp/filecleaner-trash"

[[rules]]
name = "spool-verified-cleanup"
path = "/var/spool/incoming"
max_age = "1h"
actions = ["trash"]

[rules.pre_delete_hook]
command = "/usr/local/bin/verify_receipt.sh"
args = ["{path}", "{rule}"]
timeout = "10s"
skip_exit_code = 42
on_failure = "abort_file"

5.2 Linux / macOS Bash Hook (verify_receipt.sh)

#!/usr/bin/env sh
# Allow quarantine only after downstream ingest wrote <file>.ok
if [ -f "$FILECLEANER_PATH.ok" ]; then
  exit 0
fi
exit 42

5.3 Windows PowerShell Hook (Verify-Receipt.ps1)

Point TOML command = "powershell.exe" with args = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", "C:\\Scripts\\Verify-Receipt.ps1"]:

# Allow quarantine only after downstream ingest wrote <file>.ok
if (Test-Path "$env:FILECLEANER_PATH.ok") {
    exit 0
}
exit 42

6. Automating with Cron or Built-In Daemon

Choose between simple OS cron scheduling and FileCleaner's built-in reactive daemon.

6.1 Option A: Simple Cron / Task Scheduler

# Run every 15 minutes and append structured audit events
*/15 * * * * /usr/local/bin/filecleaner run --config /etc/filecleaner/filecleaner.toml --audit-log /var/log/filecleaner/audit.jsonl

6.2 Option B: Built-In Reactive Daemon (daemon)

# Run in foreground (`hybrid`, `notify`, or `interval` mode configured in `[daemon]`)
filecleaner daemon run --config /etc/filecleaner/filecleaner.toml

# Check live PID & health (`exit 0` if running, `exit 4` if stopped)
filecleaner daemon status --config /etc/filecleaner/filecleaner.toml

# Request graceful stop without cutting an active action mid-flight
filecleaner daemon stop --config /etc/filecleaner/filecleaner.toml

# Generate native OS service unit files (`systemd`, `launchd`, or `windows-task`)
filecleaner daemon service-template --init-system systemd --config /etc/filecleaner/filecleaner.toml

7. Quick Cheat Sheet: Units, Exit Codes & Troubleshooting (-v)

7.1 Durations & Byte Size Formats

  • Durations: Integer seconds (60) or compound segments with ms, s, m, h, d, w (for example "30s", "12h", "1d 12h", "2w").
  • Byte Sizes: Integer bytes (1048576), SI powers of \(10^3\) (KB, MB, GB, TB, PB), or IEC powers of \(2^{10}\) (KiB, MiB, GiB, TiB, PiB), including decimals such as "1.5 GiB".

7.2 Deterministic Exit Codes

Exit Code Meaning When You See It
0 Success Sweep completed cleanly (including benign skip_exit_code = 42 vetoes and soft constraints).
1 Operational error Unreadable root directory, I/O error, destination collision, S3 upload/SHA-256 verification failure, or hook abort_rule.
2 Config or usage error Invalid TOML/YAML syntax, bad regex/glob/strftime template, missing CLI flags, validate failure.
3 Strict policy halt Backup freeze hit with --fail-on-freeze, or floor/lock blocked target with --strict-constraints.
4 Daemon conflict/stopped Duplicate daemon PID lock or daemon status while daemon is not running.
10 File busy (check-in-use) At least one target path matched an active sidecar, OS lock, /proc fd, or idle cooldown.

7.3 Troubleshooting with -v and --json

When a file was unexpectedly kept or skipped, re-run a dry-run preview with verbose output or JSON inspection:

# Human-readable trace of kept, in-use, and candidate files
filecleaner -v plan --config filecleaner.toml

# Machine-readable decision report for scripts or CI diagnostics
filecleaner --json plan --config filecleaner.toml

Look for keep_floor (min_keep_files), skip_in_use (active sidecar lock, open handle, or min_idle_age), skip_hook (hook returned exit 42), or freeze (backup_guard detected missing/stale backups) in the output.