Skip to content

About

macOS folder watcher: waits for files to finish writing, then copies, unzips or converts them

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

118 Commits

Folders and files

Repository files navigation

folder-watch

Watch a folder until files finish writing, then run a pluggable action.

Location: ~/Desktop/folder-watch (local git repo)
Global CLIs: ~/.local/bin/{folder-watch,watch-copy,watch-unzip,watch-convx} → bin/

Install

cd ~/Desktop/folder-watch
.venv/bin/pip install -e .

Puts folder-watch, watch-copy, watch-unzip and watch-convx in .venv/bin/, each pointing at the interpreter that owns watchdog — so they run from any directory with no PYTHONPATH set. python -m folder_watch works the same way.

The bin/ wrappers still work without installing at all: they set PYTHONPATH themselves and run the package out of the checkout. That's why the LaunchAgent uses them — it works either way.

How watching works

Default: --backend event (FSEvents via watchdog) — copy / unzip

  1. FS event → debounce → settle (write-handles closed + size stable)
  2. Skip files already finished at startup (new-only; use --catch-up to process old)
  3. Run action; persist done-state (scheme B) so restarts don’t redo work

Some actions don't run that loop at all: they hand the folder to another tool that does its own watching. See Wrapping another tool.

Actions

Built in

Action Behavior Defaults
copy Atomic copy → --to DIR (retry on OSError); never deletes source; macOS notif. Mirrors subdirectories under --recursive --ext mp4 --min-bytes 1000000
unzip Extract .zip; delete zip only after every member is verified present. --no-clobber refuses an archive that would overwrite; macOS notif --ext zip --min-bytes 1
exec Run any command per finished file; exit code decides done/retry/fail --ext * --min-bytes 1
route A different action per kind of file in one folder, from a preset's rules the rules' extensions

copy and unzip notify on success and failure with a Show in folder button, off with --no-notify. A failed extract says the archive was kept — a folder where nothing happened and one where something went wrong look identical otherwise.

One folder, several actions (route)

A route preset gives each kind of file its own action. Rules are tried in order and the first whose ext matches decides; "ext": [] matches every file, so it goes last. A file no rule takes is not watched at all, so it is never marked done; once you add a rule for it, a file already in the folder is like any file present at startup, and --catch-up picks it up.

"inbox": {"action": "route", "src": "~/Inbox", "rules": [
  {"ext": ["zip"], "action": "unzip", "mode": "named"},
  {"ext": ["mov", "mp4"], "action": "copy", "to": "~/Drive/Video"},
  {"ext": [], "action": "copy", "to": "~/Archive"}
]}

A rule may set to, mode, cmd, exec_timeout, no_clobber, create_dest and verify for its own files; everything else (stable, recursive, sound, …) comes from the preset. Each rule is checked as the preset it amounts to, so a copy rule without to, or one whose destination sits inside a recursive source, is refused when saved. Set them with folder-watch presets edit inbox rules='[...]'.

Notification sound

On by default, and deliberately quiet — Tink, which is a click rather than an announcement. This fires once per finished file on a folder that can take a batch of them, so anything with a tail or a melody stops being information and starts being noise.

folder-watch copy ./Out --to ./Drive --no-sound          # silent
folder-watch copy ./Out --to ./Drive --sound-name Purr   # something else
folder-watch --list-sounds                               # what this Mac has

Sounds come from ~/Library/Sounds and /System/Library/Sounds, yours first — so a .wav you drop in the former is selectable by name. The quiet end is Tink, Pop, Purr, Morse; Basso, Sosumi, Funk and Submarine announce themselves and will wear out their welcome.

The sound rides along with the notification rather than being played separately, so turning notifications off silences it too, and it can never drift out of sync with the popup.

A name that matches no sound is reported once rather than passed through: every notifier accepts an unknown name and simply plays nothing, which makes a typo indistinguishable from having the feature switched off.

Unlike --notify, this is preset-settable — the watchers that run unattended are exactly the ones you want to hear, and they start from a preset with no other flags:

{ "nightly-render": { "action": "copy", "sound": true, "sound_name": "Tink" } }

exec — run any command per finished file

folder-watch exec ~/Inbox --ext wav \
  --cmd 'ffmpeg -i {path} -c:a libmp3lame {dir}/{stem}.mp3'

Settle detection, the done-store, the retry queue, pidfiles, status and the LaunchAgent are the expensive part of this tool and none of it is specific to copying. exec is what opens all of it to anything with a command line, instead of requiring Python in this repo.

placeholder for ~/Inbox/shots/take-3.mov
{path} /Users/you/Inbox/shots/take-3.mov
{dir} /Users/you/Inbox/shots
{name} take-3.mov
{stem} take-3
{ext} mov
{rel} shots/take-3.mov (from the watched root)

The command runs with its working directory set to the file's own folder, so a relative output lands beside the input.

There is no shell. --cmd is split into argv once, and placeholders are substituted into the resulting tokens afterwards — so a file called note; rm -rf ~.mp4 arrives as a single argument, not as a second command. Substituting first and splitting after is the entire bug class, and it needs no attacker: an unlucky export name is enough. It does mean --cmd is quoted the way xargs or find -exec would want, with inner quotes surviving the split.

The exit code is the contract:

exit meaning
0 done — recorded, never repeated
75 retry later — straight into the same backoff and 72h give-up budget a failed copy uses (EX_TEMPFAIL, the BSD sysexits.h convention)
anything else permanent failure; the command's own stderr is quoted in the fail line, because a bare exit code explains nothing

A command that never returns would stop the watcher silently and forever, so there is a default --exec-timeout of one hour (0 disables it). A timed-out command is reported, not retried — it was killed mid-flight, so what it did or half-did is unknown, and repeating that is worse than saying so.

--cmd is part of the done-key, so editing it re-processes files the previous command already handled. Notifications are off unless you pass --notify: unlike a copy, a command can fire on every file in a busy folder.

exec recipes

Each of these runs for real in tests/e2e/test_recipes.py. Paths in --cmd must be absolute: there is no shell to expand ~.

# move each finished file somewhere else
folder-watch exec ~/Inbox --cmd '/bin/mv -n {path} /Users/you/Sorted/'

# rename with today's date, into another folder
folder-watch exec ~/Scans --cmd \
  '/bin/sh -c '"'"'mv -n "$1" "$2/$(date +%F)-$(basename "$1")"'"'"' sh {path} /Users/you/Archive'

# upload with rclone; a failed upload is retried later rather than given up on
folder-watch exec ~/Outbox --cmd \
  '/bin/sh -c '"'"'/opt/homebrew/bin/rclone copy "$1" drive:Inbox || exit 75'"'"' sh {path}'

# a 540p video proxy beside the original's name
folder-watch exec ~/Footage --ext mp4,mov --cmd \
  '/opt/homebrew/bin/ffmpeg -nostdin -v error -y -i {path} -vf scale=-2:540 -c:v libx264 -preset veryfast -crf 28 /Users/you/Proxies/{stem}_proxy.mp4'
  • When a recipe needs the shell ($(date), ||), pass the file as an argument (sh -c '… "$1" …' sh {path}), never inside the script text. As an argument it is data; inside the script, a file called x;touch pwned;.txt runs touch pwned. The tests check both forms.
  • Do not rename a file inside the folder being watched: the renamed file is a new file, and the watcher would rename it again, forever. Rename into another folder, as above.
  • exit 75 turns a failure into "retry later" (see the table above), which is the right answer for a network upload that may work in a minute.
  • -nostdin keeps ffmpeg from waiting on input it will never get under launchd.

service (LaunchAgent install / uninstall / status), status, prune and presets are subcommands rather than actions.

Wrapping another tool

Not every job is worth reimplementing. Plenty of tools already watch a folder competently — converters, encoders, sync clients, uploaders — and the useful thing folder-watch can add is not a second settle loop on top of theirs, but the operational shell around it: one config format, one way to start it at login, one place to see whether it is running, and a guarantee that it dies when you stop it.

So there is a second kind of action: a wrapper. It converts nothing and watches nothing. It translates folder-watch flags into the other tool's command line, launches it, prints exactly what it ran, and then supervises the process.

folder-watch → /path/to/tool watch ~/Inbox -t webp --filter *.png --debounce 500

What you get, and what you give up

A wrapper hands ownership of the watching to the wrapped tool, so most of this README stops applying to it — the settle loop, the done-store and the retry queue all belong to a pipeline folder-watch is no longer running:

built-in actions wrapper actions
settle loop, lsof, --stable / --settle yes no — the wrapped tool decides when a file is ready
done-store, --catch-up, baseline_pending yes no
retry queue, --retry-hours yes no
--pending yes no
--once yes no — rejected when the wrapped command is continuous

What you keep is the part that made you reach for a watcher in the first place:

  • Presets — the same --save-preset / --list-presets / presets forget lifecycle, so a wrapped tool is configured the way everything else is.
  • folder-watch status — a wrapper writes a pidfile like any other watch, so it shows up in the same table with the same log tail.
  • LaunchAgent — service install --preset NAME works unchanged.
  • Lifecycle. This is the one that actually earns its keep. A wrapped watch command runs forever, so anything that ends the wrapper without taking the child with it leaves an orphan watching the same folder — and those stack up silently over restarts. The wrapper turns SIGTERM into a clean unwind, terminates the child, escalates to SIGKILL if it will not go, and only then exits.

The contract

A wrapper action is a small amount of code — an argv builder and a supervised exec — and it commits to three things:

  1. Never bundle the tool. A wrapped binary keeps its own repository, release cycle and issue tracker. pip install folder-watch must never drag it along, and for compiled tools it could not anyway.
  2. Fail loudly when it is missing. Exit 127 with the binary name in the message, and accept an explicit path so a non-standard install still works, rather than silently doing nothing.
  3. Print the translated command line. The flag mapping is the whole surface area of a wrapper; showing it means a mismatch is one glance away instead of a debugging session.

Currently wrapped

convx → ConvX, a third-party "local-first universal file converter for CLI, Desktop, and AI agents". It is a compiled binary, not a Python package, and it is not bundled, vendored or installed by folder-watch. Install it separately, or point at it with --convx-bin /path/to/convx; if it is absent the action exits 127 with error: convx not found.

folder-watch convx ~/Inbox --format webp --ext png,jpg

--ext becomes ConvX's --filter, --format becomes -t, and --quality / --width / --fps / --max-size / --convx-preset pass through. ConvX converts in place, so --to is rejected rather than quietly ignored, and convx watch is continuous, so --once is rejected too — use convx convert directly for a one-shot run.

Anything not in that mapping goes through --passthru, appended verbatim and last, so a flag ConvX grows tomorrow is usable the day it ships rather than the day a release here catches up:

folder-watch convx ~/Inbox --format webp --passthru "--some-new-flag 3"

It is split with shlex and appended to the argv list. There is no shell in the chain, so this adds arguments to convx — never a second command.

Verifying a copy

folder-watch copy ./Out --to ./Drive --verify

A copy is normally checked by size, which catches a truncated write and nothing else. --verify re-reads both files and compares sha256, which is the only check that catches the right number of wrong bytes — rare on local disk, less rare across a network mount or a syncing client, and silent when it happens. A copy that fails verification is deleted rather than left looking finished — a file that is confidently wrong is worse than one that is obviously missing. In watch mode it then goes back on the retry queue. Under --once there is no loop left to service a queue, so it is reported in the log and in a non-zero exit status instead, which is what a cron wrapper needs.

It costs a full read of both files, which is why it is off by default. sha256 rather than something faster so you can reproduce it with shasum -a 256.

Opening Finder on each result

folder-watch copy ./Out --to ./Drive --reveal

--reveal opens Finder with each result selected as it lands, without clicking a notification: the copy for copy, the extracted folder for unzip, the file the command ran on for exec. It works with notifications off too, and does nothing on a dry run. It can be saved in a preset ("reveal": true), so a LaunchAgent can use it. Each result brings Finder to the front, so it suits folders that receive a file now and then rather than a busy one. convx hands files to another tool, so it has no result to reveal.

Failure notifications are grouped

The first failure in an hour notifies straight away. Later ones in the same hour (a copy that failed, a missing destination, a corrupt copy, an extract or command that failed) are counted, and one notification sums them up when the hour ends: "12 more after the first; latest: …". One notification per failed file used to bury the screen when a drive went away, and again on every retry pass. Successes still notify one by one, and the log keeps every line. A watcher that stops before the hour ends (a --once run, say) sends the summary as it exits.

Telling something else

folder-watch copy ./Out --to ./Drive --webhook https://example.com/hook

POSTs outcome events — copied, extracted, ran, fail, give_up, src_lost, src_restored — as JSON. Progress chatter is not forwarded; it fires continuously and would make the webhook a firehose that says nothing.

It is hooked onto the log rather than onto each action, so a new action is covered without being asked to remember. Three guarantees: it never blocks the watch loop (bounded queue, one daemon thread, events dropped and counted if an endpoint cannot keep up), it never crashes the watcher (an unreachable endpoint is a lost notification, not a lost file), and the URL is never logged — Slack and Discord put the secret in the path, and this log gets pasted into bug reports.

Reliability / logging

# dry-run (no writes)
folder-watch copy ./Out --to ./Drive --once --dry-run

# log file + JSON lines (rotates at 10 MB, keeps 3 old copies; without a
# terminal, events go only to the file, so a LaunchAgent's .out log is not a
# second copy of them)
folder-watch --preset nightly-render --log ~/.local/state/folder-watch/nightly-render.log --json

# verbose settle/progress
folder-watch --preset nightly-render -v

# disable persistent done-state
folder-watch copy ./Out --to ./Drive --no-done-store

# copy retries (default 5)
folder-watch copy ./Out --to ./Drive --retries 8

# status of running watchers
folder-watch status

# every preset in one table: health, service (running / paused / not loaded),
# last exit code, last result from its log, and log size
folder-watch status --all
folder-watch status --preset nightly-render

# drop done-state whose source is gone, stale pidfiles, presets whose folder
# has been deleted or renamed for 30+ days, logs no preset owns that are 30+
# days old, and trim launchd .out logs over 10 MB (dry by default)
folder-watch prune
folder-watch prune --yes

# weekly (Sundays 10:00): one notification listing what prune would do, with
# a "Clean up" button; nothing is removed without the click
folder-watch prune --schedule
folder-watch prune --unschedule

# one preset in full: values, which file each came from, is it running
folder-watch presets show nightly-render

# change some keys and keep the rest; an installed service is reinstalled
folder-watch presets edit nightly-render src=~/Renders/v2 ext=mp4,mov
folder-watch presets edit nightly-render follow_moves=true --unset verify

presets edit types each value the way the matching flag does (true/false, numbers, ext as a comma list) and stores src and to as absolute paths. An unknown key or a bad value changes nothing. If the preset has a LaunchAgent, it is reinstalled, because the plist copies src at install time and would otherwise keep watching the old path. A watcher you started yourself keeps the old settings until restarted, and edit says so. The dashboard's Edit button changes the watched folder and the copy destination the same way.

Files already in the folder at startup

A new watcher skips whatever is already sitting there (that's the point of new-only), and records it as baseline — assumed handled. Nothing used to verify that assumption, so a file that had never been processed looked exactly like one that had, and was skipped forever without a word.

Startup now says so:

baseline ignored=2 encoding=0 pending=1 probed=2
baseline_pending count=1 names=['never-touched.zip'] hint=skipped but no output found

To ask the same question without starting anything — read-only, no state written, no lsof, safe against a folder a watcher is running on right now:

folder-watch unzip ~/Inbox --mode named --pending
folder-watch --preset nightly-render --pending

Exits 1 if anything is pending. --catch-up then processes them, and clears any stale baseline assumptions first — without that it would skip precisely the files it was asked to pick up.

When the folder goes away

Watched folder deleted, renamed, or its volume unmounted — FSEvents just goes quiet, so the watcher polls for the directory every 5s rather than trusting the silence. On loss it logs src_lost, tears down the observer and waits; when the folder returns it logs src_restored and re-arms. While it waits, src_waiting is logged after 1 minute, then 2, 4, 8… capped at once a day, so a folder that never returns does not grow the log forever.

Watched folder moved or renamed — on macOS the watcher holds the folder open, so it can tell where the folder went, the Trash included. It logs error reason=src_moved now=<new path>, exits 2 and sends a notification instead of waiting for a name that will not come back. It never follows a move by itself: the new place can be the Trash or a backup copy. For a stored preset the notification has a Watch new path button (needs alerter). Clicking it saves the new path as the preset's src and restarts the watcher on it. A LaunchAgent is reinstalled so its plist follows. Ignoring it, or letting it time out after an hour, changes nothing.

Following without asking. A preset with "follow_moves": true (or saved with --follow-moves) skips the button and follows the move by itself, then tells you with a notification. It never does that for a move into a Trash, which is a deletion; that is logged as follow_refused and falls back to the button. A move onto another volume is a copy and a delete, so the watcher sees its folder deleted rather than moved and has nothing to follow; should a path on another volume ever be reported, it is refused the same way. With --no-notify nothing is shown, but a safe automatic follow still happens.

A restore always does a catch-up scan, even without --catch-up: anything that landed while the directory was gone is work that hasn't been done. The done-store makes that safe — files already handled are skipped, not redone.

The same goes for a follow, either way it happens: the restarted watcher takes over the done-store kept under the old path (logged as follow_resumed) and scans instead of taking a fresh baseline, so a file dropped in the seconds between the move and the restart, or one waiting for its destination, is still processed, while what was handled or already there before is not.

Destination missing — --to is not created recursively. On an unmounted drive mkdir -p happily rebuilds the whole path as ordinary local folders, so files land on the boot disk, get reported copied, and get recorded as done — silently never reaching the drive. Instead the copy fails with dest_unavailable and is not marked done. --create-dest opts back into building the full path.

Retry queue

A failure the action judges transient — dest_unavailable, a copy_error that outlived atomic_copy's own backoff, an OSError mid-extract — is queued rather than dropped. Nothing else would pick it up: the only thing that re-queues a file is a new FSEvent on the source, and a destination coming back produces none.

fail name=take.mp4 reason=dest_unavailable
retry_scheduled name=take.mp4 attempt=1 in_s=30
retry_waiting queued=1 reason=dest_away      # one probe, not one per file
retry name=take.mp4 attempt=1
copied name=take.mp4

Backoff runs 30 s → 60 s → 2 m → 5 m → 10 m → 30 m (capped), so a long outage costs a handful of attempts an hour. Retries skip the settle loop entirely — the file already settled once, and re-settling would pay another lsof per attempt — so the recorded (size, mtime) is checked instead; if it moved, the file was rewritten and goes back through the normal path.

The queue is persisted beside the done-store and survives a restart; baseline seeding will not claim a file the queue owns. Terminal failures are never queued: a corrupt archive does not become valid by waiting.

--retry-hours (default 72) is when it stops and logs give_up reason=retry_exhausted. 72 covers a weekend with the machine asleep — timestamps are wall-clock, because monotonic clocks do not survive a restart, so sleep counts against the budget. Giving up is not data loss: the source is untouched, nothing was marked done, and --pending and --catch-up still see the file.

Ignores partial/scratch names: *.part, *.tmp, *.crdownload, .aria2, etc. Also skips anything beginning with . or ~ — that covers ._*, ~$… and dotfiles, but note it excludes ordinary names like ~final cut.mp4 too. Note copy only looks at .mp4 of at least 1 MB unless you pass --ext / --min-bytes; a file below the threshold is logged as ignored.

Exit codes: --once returns 1 if any file ended in fail or error, 0 otherwise (an empty run is not a failure), 2 for usage errors — including a source directory that doesn't exist. So a cron or CI wrapper can actually tell.

Log format: plain-text fields escape control characters and are quoted when they contain spaces, = or ", so name="my clip.mp4" rather than an ambiguous bare value. Without that a crafted filename could emit a second, well-formed line. --json was never affected.

A stalled file is not abandoned. If nothing changes for STALL_TIMEOUT (300 s) the watcher asks lsof directly. If the writer has let go, the file is complete and gets processed — logged settled_late, because releasing a handle does not reliably emit an FSEvent and dropping it there lost finished work. If the writer still holds it, it logs stalled once and keeps re-checking slowly rather than forgetting it; only after 24 h of no progress does it give_up.

Two watchers on one folder log a duplicate_watcher warning and both act. --exclusive refuses to start instead; it is off by default because under launchd a refusing service flaps rather than running.

Done-state files: ~/.local/state/folder-watch/done-*.json
Pidfiles: ~/.local/state/folder-watch/pids/*.json
Key = action + src + dest/mode + size + mtime (scheme B).

Audit trail

folder-watch audit                          # the last 7 days
folder-watch audit --since 30d --preset photos
folder-watch audit --kind preset_saved --kind service_paused
folder-watch audit --since 2026-11-01 --json

Every action, in ~/.local/state/folder-watch/audit.jsonl, one JSON line each, with who or what triggered it: cli, service, weekly, dashboard, notification (a button) or automatic (a followed move). The file is readable only by you, and a webhook URL in it is reduced to its host, since the token is part of the URL. Recorded:

kind when
copied, extracted, ran, fail, give_up a file's outcome, with its preset
src_moved, src_followed, src_not_followed, follow_refused a watched folder moved
preset_saved (with what changed), preset_removed presets
service_installed, service_uninstalled, service_paused, service_resumed, job_installed services and the tool's own jobs
log_removed, log_trimmed, state_pruned what a cleanup removed

Logs rotate away and the done-store forgets on purpose; this file does neither. It is append-only, rotation never touches it, and prune keeps one year (entries it cannot date are kept). Writing it never stops a copy: a failed write is skipped. The dashboard's Audit button lists the last 7 days.

Digest

folder-watch digest            # what each preset did in the last 7 days
folder-watch digest --days 30

Counted from each preset's log and its rotated copies: results (copied, extracted, ran) and failures (fail, give_up). Every log line now carries its date (2026-11-04 09:05:00 INFO …, and a ts field with --json), so a week is counted by date. Lines written before dates were added are skipped. The weekly prune --schedule job sends the same summary as a notification, for example "copied 34, 2 failed (photos, inbox)", when anything happened that week.

Dashboard

folder-watch dashboard              # opens http://127.0.0.1:8765/ in your browser
folder-watch dashboard --no-open --port 9000
folder-watch dashboard --install    # at every login, always on 127.0.0.1:8765
folder-watch dashboard --link       # the address with its key, to open once
folder-watch dashboard --uninstall

Above the table, Run doctor shows doctor's findings inline (without its launchd folder probe, which takes seconds), and Clean up… shows what the weekly prune would remove as a dry run, with an Apply button that is the only thing that removes anything. Each row with a log has a Log toggle for its last 20 lines, and a Test button: a --once --dry-run run of that preset against its folder as it is now, listing what it would copy, extract or run, with nothing written. History charts each preset's files done and failed per day over the last 30 days, from the audit trail (open it directly by adding #history to the dashboard's address). --install runs the dashboard at login on a fixed port with --strict-port: if something else holds the port it fails instead of moving to a random one, and launchd retries every five minutes rather than in a loop.

A live local web page of every preset, refreshed every 5 seconds: health, service (running, paused, not loaded), last exit code, last result from its log, and log size, with Pause / Resume, Open folder and Open log buttons. It runs until you press Ctrl-C. The terminal version is folder-watch status --all.

It listens on 127.0.0.1 only, which every account on the Mac and every page in your browser can still reach. So nothing is shown without a key, kept in ~/.local/state/folder-watch/dashboard.key where only you can read it. folder-watch dashboard opens the address with the key; the page swaps it for a cookie (HttpOnly, SameSite=Strict, a year) and takes you to the dashboard's own address, http://127.0.0.1:8765/ followed by 16 characters derived from the key: bookmark that one. The cookie is sent only to that address, because a browser sends a cookie to every port of 127.0.0.1, so one for the whole host would reach any program listening on any port. For the one started at login, --install prints that link once, and --link prints it again whenever you need it; the dashboard's own log only ever gets the plain address. A button press must also come from the dashboard's own page, which stops another page on localhost from acting through your cookie; the page refuses to be framed; and a request addressed to any other host name is refused, which stops a domain rebound to 127.0.0.1 from reading or acting.

Doctor

folder-watch doctor                 # exit 0 all good, 1 warnings, 2 problems
folder-watch doctor --test-notify   # also send a test notification
folder-watch doctor --no-probe      # skip the launchd folder probe

It checks what a watcher needs and cannot check for itself:

  • Notifiers: whether alerter (buttons) and terminal-notifier are where a service looks for them. Whether macOS actually shows notifications cannot be read back, so --test-notify sends one for you to see.
  • Services: every folder-watch LaunchAgent, whether it is loaded, and its last exit code. A watcher that crashes before folder_watch even loads (a wrong interpreter, a missing module) writes no log, and launchd restarts it forever; its exit code is the only trace. It also flags a service whose preset no longer exists, and one whose plist no longer matches its preset.
  • Destinations: whether each exists, is writable, and has 2 GB or more free.
  • Protected folders: macOS keeps background jobs out of ~/Desktop, ~/Documents and ~/Downloads unless the job's binary is allowed. For each of those a preset uses, a one-shot launchd job running the interpreter your services run tries to list it, so the answer is the one a service would get.

The weekly prune --schedule job runs the service and destination checks too, and notifies you when one fails.

LaunchAgent

folder-watch service install --preset nightly-render
folder-watch service status --preset nightly-render
folder-watch service pause --preset nightly-render    # stop, and stay stopped across logins
folder-watch service resume --preset nightly-render
folder-watch service uninstall --preset nightly-render

pause disables the job in launchd and stops it, leaving the plist and the preset as they are; resume re-enables and loads it. service status, status --all and doctor show it as paused rather than as a service that failed to load. install and uninstall clear a pause, since launchd's record of one outlives the plist and would otherwise keep a reinstalled service from ever running.

Do not run services out of a checkout

service install points the plist at whichever interpreter is running it, so installing from a clone leaves the LaunchAgent executing your working tree. Every edit is then one restart away from production, including the broken intermediate ones — a half-finished change that nobody meant to ship goes live the moment launchd restarts the job.

Install a released copy into its own venv and run service install from there:

python3 -m venv ~/.local/share/folder-watch/venv
~/.local/share/folder-watch/venv/bin/pip install folder_watch-X.Y.Z-py3-none-any.whl
~/.local/share/folder-watch/venv/bin/folder-watch service install --preset NAME

The plist then names that venv's interpreter and carries no PYTHONPATH, which matters more than it looks: a PYTHONPATH naming a checkout puts the checkout ahead of site-packages, and the service quietly goes back to running the working tree. --version on a running service is the check — if it does not match the tag you installed, it is reading a checkout from somewhere.

Upgrading is pip install the new wheel and launchctl kickstart -k the service. Rolling back is the same with an older wheel, which is the practical reason to tag releases at all.

Keeps the preset running at login (KeepAlive), but only while the preset's src folder exists (PathState). A missing source logs one error reason=src_missing and then stays quiet. launchd starts the watcher again when the folder reappears, and on any volume mount (StartOnMount, since launchd does not re-check PathState then), so a source on a drive comes back with the drive; a source that is gone for good costs one log line per mount. One case launchd gets wrong: a volume ejected while the service is loaded still counts as present to PathState, so a watcher that then exits (after a kickstart -k, say) was restarted every 10 seconds. A service whose source's volume is ejected (the mount it was last seen on is not mounted) waits for it in-process instead, logging src_lost and then src_waiting at a doubling interval, and carries on when it is back. After changing a preset's src, run service install again. Logs default to ~/.local/state/folder-watch/<preset>.log.

Usage

folder-watch copy ./Output --to ./Drive/V2 --ext mp4
folder-watch unzip ~/Downloads/inbox
folder-watch convx ~/Inbox --format webp --ext png,jpg
folder-watch --preset nightly-render

watch-copy ./Output ./Drive/V2
watch-unzip ~/Downloads/inbox
watch-convx ~/Inbox --format webp --ext png,jpg

Presets: ~/.config/folder-watch/presets.json

folder-watch presets forget NAME          # dry — shows what it would remove
folder-watch presets forget NAME --yes

There are no built-in presets — they come only from these files. A preset can be defined in more than one of them (a pre-rename ~/.config/watch-copy/ path is still read), so forget names every file it found and removes the preset from all of them; taking it out of one would leave the other still being merged in and the command would look broken.

Removal is explicit and never a side effect of listing or running. It refuses while a watcher is using that preset rather than pulling config out from under it, and warns if a LaunchAgent is still installed for it. Exit 1 if the name is unknown, 2 if it is in use.

--save-preset NAME merges into an existing preset rather than replacing it, and says which it is doing:

note: preset 'job' already exists — modifying it, not creating it
  stable: 7 -> 9
updated preset 'job'

Only what you actually typed changes (plus anything you loaded with --preset). Rebuilding the whole config from resolved values meant that re-saving to change one field silently reset every other one to its default — ext back to mp4, min_bytes back to 1000000, no_clobber gone — while reporting success. Creating a new preset still captures the full config, which is what makes one useful.

--list-presets reports the health of each one rather than rendering a dead preset identically to a live one:

nightly-render:  [source missing — nearest existing folder is ~/Desktop]
client-assets:
  ...
1 of 3 preset(s) need attention. Nothing was changed.

It reports and stops there. The tool cannot tell "this project is finished" from "the drive is unplugged" — and its own runtime already assumes a missing folder is temporary, which is what src_lost / src_restored are for. So it never removes a preset on one look.

Retention. prune does remove a preset once three things hold:

  • its source was deleted or renamed in place. A missing folder under /Volumes or ~/Library/CloudStorage whose volume is not mounted never counts, and neither does one last seen on a volume that is no longer mounted, wherever it was mounted: the watcher and each prune note the mount a source sits on (preset-volumes.json in the state folder) while it is there to see. A source never seen by either still looks deleted once its volume is ejected, which is one reason removing needs --yes or a click;
  • it has stayed that way for 30 days, counted from the first check that saw it, recorded in ~/.local/state/folder-watch/dead-presets.json;
  • no watcher is running it.

It removes the LaunchAgent first, then the preset and its default logs. The LaunchAgent goes first because one left naming a removed preset fails on every login. prune is a dry run until --yes. The weekly job (prune --schedule) asks with a notification instead, and does nothing without the click. If the folder comes back, its clock starts over.

It does distinguish the two cases where it honestly can, because they call for opposite responses: a path whose nearest existing folder is an ordinary directory was deleted or renamed and needs your attention, while one under /Volumes or ~/Library/CloudStorage is an unmounted volume and needs nothing, unless that volume is mounted and only the folder on it is gone, which is a deletion. A volume mounted elsewhere is told apart only by the mount noted while its source could be seen. Using a broken preset already fails loudly (error reason=src_missing, exit 2); this only fixes the inventory view.

A preset can carry the safety flags too — no_clobber, create_dest, exclusive, no_done_store, retry_hours. That matters because unattended runs use --preset, so without it the options that most need to be on for an unwatched watcher were the ones it could not reach. An explicit flag on the command line still wins over the preset.

Nothing derives the preset schema from the argument parser, so a key the loader doesn't read does nothing — and --list-presets used to echo it back as though it were configuration. A misspelled no_clober looked exactly like a working safety flag. Unrecognised keys now warn:

warn reason=unknown_preset_keys preset=demo keys=dry_run,no_clober note="ignored — not settable from a preset"

PRESET_KEYS and NOT_PERSISTED in folder_watch/presets.py are the two lists, and a test fails if a flag is added to the parser without landing in one of them.

Tests

.venv/bin/python -m unittest discover -s tests -v
./bin/test-addons
make check    # lint + types + unit tests (~3 min) — what the commit hook runs
make all      # adds the smoke suite, end-to-end tests and coverage
make e2e      # real watchers and real launchd jobs (tests/e2e, ~2 min)
make feature  # before committing a feature: see below (BASE=origin/main)
make dev      # install the dev dependencies
make install-hooks

make check runs on every commit via hooks/pre-commit (symlinked into .git/hooks by make install-hooks, since that directory isn't versioned). The smoke suite is deliberately outside the commit gate: it spawns real watchers and does FSEvents timing, and a gate that is slow or flaky gets bypassed with --no-verify, at which point it protects nothing.

End-to-end tests (tests/e2e) run real watchers on FSEvents and real launchd jobs, in throwaway trees, through the fixtures in tests/e2e/fixtures.py: WatcherCase starts a watcher writing JSON events and waits for an event with given fields under a deadline; LaunchdCase loads a job under a unique label with the scratch config in its environment, and always unloads it. They cover what was only ever checked by hand: a dropped file copied, an archive extracted, a moved source reported with its new path, a missing source starting once under launchd and coming back with its folder, and doctor reading a crashing service's exit code. The launchd tests skip themselves where there is no GUI login session, as on CI runners.

Before committing a feature, run make feature (bin/feature-check, about 8 minutes). It runs everything make all does with the bytecode cache off, reports coverage of the files changed since BASE, and then runs every test added since BASE against BASE's code. Each one must fail there, by assertion, because a new test that passes without the change it was written for is not testing it. One that only raises there (usually because what it calls is new) never reached its assertion, so it is listed to check by hand, as is a test in a module that only exists after the change. Coverage of the changed files, taken together, must be at least 80%; new e2e tests are red-checked too, from BASE's own tests/e2e. A test that guards behaviour the change must keep, and so passes before and after by design, is marked # holds on BASE on its def line. Deliberate breaks of the new code are still done by hand, per feature.

GitHub Actions runs the same checks on macOS runners across Python 3.10 and 3.13 — a linux runner would be cheaper and would prove nothing about a tool built on FSEvents, lsof and launchd. It also asserts lsof stays reachable, since a watcher that cannot find it once treated every file as permanently open and silently processed nothing.

The unit suite never reaches the real desktop or launchd: tests/_isolate puts stub alerter, terminal-notifier, osascript, open and launchctl first on PATH (logging to $TMPDIR/folder-watch-tests/stub-bin/calls.log), and test_harness fails if they are not the ones found. The e2e suite uses the real ones, under the label prefix com.folder-watch-e2e (FOLDER_WATCH_LABEL_PREFIX) so its jobs never sit among your services.

Config lives in pyproject.toml. E402 is ignored under tests/ — every suite must put the repo on sys.path and import tests/_isolate (which redirects state off ~/.local/state) before folder_watch is imported.

Testing the watch loops

The loops are the hard part to test: they never return, their timeouts run to a full day, and the event backend only wakes when the filesystem says so. So tests/_loopharness.py replaces three things and nothing else —

  • a virtual clock installed over the module's time, where sleeping advances the clock instead of blocking, and doubles as the tick callback a test uses to delete a directory, release a writer or skip past a timeout;
  • a stub observer that captures the event handler instead of starting a watchdog thread, so events are a function call rather than a race;
  • a scripted lsof, since whether a writer still holds a file is the one thing the settle logic cannot work out for itself.

Everything else is real: real files, real state, real queue. The result is that core/watch.py — where all three audit rounds found their bugs — is covered at 96% by tests that finish in well under a tenth of a second and cannot flake on a loaded machine. What is left uncovered there is error handling for filesystem races that cannot be provoked without patching the standard library.

Versioning and releases

folder_watch/_version.py is the single source of truth. pyproject.toml reads it through hatch and --version prints it, so the wheel metadata, the tag and the running binary cannot disagree — a test enforces that, and the release workflow refuses a tag that does not match.

Versions are semantic, read from the point of view of someone who has a watcher running unattended:

means
major an existing invocation changes behaviour or stops working — a removed flag, a preset key that no longer means what it did, a different default
minor new actions, flags or subcommands; existing setups keep working untouched
patch fixes and internals only

State on disk gets the same treatment as the CLI. The done-store, retry queue and preset files are read by whatever version happens to be installed after an upgrade, so a format change that an older version cannot read is a major bump.

Cutting one

# record what changed under ## [Unreleased] in CHANGELOG.md first
make release V=0.5.0
git push origin main --follow-tags

bin/release refuses a dirty tree, a branch other than main, a non-semantic version, a tag that already exists and an empty [Unreleased] section. Then it runs make all, bumps the version, promotes [Unreleased] to the new heading with today's date, commits and tags — and stops.

Pushing the tag is the publish step, and nothing before it leaves the machine. git tag -d v0.5.0 && git reset --soft HEAD~1 undoes the lot.

Once the tag lands, .github/workflows/release.yml re-runs the full gate at that commit on two runner pools, Apple silicon and Intel, checks the tag against __version__, builds the sdist and wheel, and opens a GitHub Release using that version's changelog section as the notes. A leg that never gets a machine (0.3.0 waited hours for one) is skipped; a leg that runs and fails stops the release. A release is never published from a build that did not pass.

The first tag is a bootstrap — bin/release bumps, and 0.1.0 is already the version in the tree:

git tag -a v0.1.0 -m "v0.1.0" && git push origin v0.1.0

About

macOS folder watcher: waits for files to finish writing, then copies, unzips or converts them

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages