the first commit
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
.venv/
|
||||
__pycache__/
|
||||
build/
|
||||
dist/
|
||||
@@ -1,3 +1,214 @@
|
||||
# dotnuke
|
||||
|
||||
A small cross-platform service that keeps a directory free of MacOS metadata clutter.
|
||||
A small cross-platform service that keeps a directory free of macOS metadata clutter. It deletes
|
||||
files as soon as they appear, and also cleans up whatever is already there when it starts.
|
||||
|
||||
Files removed:
|
||||
|
||||
| Pattern | What it is |
|
||||
|-------------|-----------------------------------------------------------------------------------|
|
||||
| `._*` | AppleDouble files. macOS writes these to non-HFS/APFS volumes (SMB/NFS shares, exFAT/FAT32/NTFS drives) to store resource forks and extended attributes. |
|
||||
| `.DS_Store` | Finder's per-folder view settings (icon positions, sort order, etc.). |
|
||||
|
||||
This is most useful on network shares, external drives, or servers (Linux, Windows) that are
|
||||
accessed from Macs, where these files otherwise accumulate and show up as junk to other systems.
|
||||
|
||||
Matching is by file name only and is case-sensitive. Only files are removed, never directories.
|
||||
|
||||
## Supported platforms
|
||||
|
||||
| OS | Supported | Notes |
|
||||
|---------|-----------|-----------------------------------------------------------------------|
|
||||
| macOS | Yes | `fswatch` uses the native FSEvents backend. |
|
||||
| Linux | Yes | `fswatch` uses inotify (or another available backend). |
|
||||
| Windows | Yes | `fswatch` uses the native Windows backend; see the Windows notes below. |
|
||||
|
||||
The script itself is plain Python and uses only portable standard-library calls; the only
|
||||
platform-specific piece is installing `fswatch`.
|
||||
|
||||
## Dependencies
|
||||
|
||||
1. **Python 3.6 or newer.** Standard library only; no `pip install` needed.
|
||||
2. **[fswatch](https://github.com/emcrisostomo/fswatch)** available on your `PATH`. It is the
|
||||
program that reports filesystem events to the script.
|
||||
|
||||
Installing `fswatch`:
|
||||
|
||||
| OS | Command |
|
||||
|---------|---------------------------------------------------------------------------------|
|
||||
| macOS | `brew install fswatch` |
|
||||
| Debian/Ubuntu | `sudo apt install fswatch` |
|
||||
| Fedora | `sudo dnf install fswatch` |
|
||||
| Arch | `sudo pacman -S fswatch` |
|
||||
| Other Linux | Build from source (see the fswatch repository) |
|
||||
| Windows | Install through [MSYS2](https://www.msys2.org/) (`pacman -S fswatch`) or Cygwin, then add its `bin` directory to `PATH` |
|
||||
|
||||
Verify the installation with `fswatch --version`.
|
||||
|
||||
## Setting up a virtual environment
|
||||
|
||||
Using a virtual environment keeps the build tooling (PyInstaller) separate from your system
|
||||
Python. The script itself needs no third-party packages, so the venv is only strictly needed for
|
||||
building the executable.
|
||||
|
||||
```sh
|
||||
# macOS / Linux
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
# Windows (Command Prompt)
|
||||
py -m venv .venv
|
||||
.venv\Scripts\activate.bat
|
||||
|
||||
# Windows (PowerShell)
|
||||
py -m venv .venv
|
||||
.venv\Scripts\Activate.ps1
|
||||
```
|
||||
|
||||
Once activated, `python` refers to the venv interpreter and the prompt shows `(.venv)`. Run the
|
||||
script with `python dotnuke.py`. Leave the environment with `deactivate`.
|
||||
|
||||
Note that `fswatch` is not a Python package; it is still installed system-wide as described above.
|
||||
|
||||
## Building a portable executable (PyInstaller)
|
||||
|
||||
You can bundle the script and the Python interpreter into one self-contained file, so the target
|
||||
machine does not need Python installed. (`fswatch` must still be installed there.)
|
||||
|
||||
1. Activate the virtual environment (see above) and install PyInstaller:
|
||||
|
||||
```sh
|
||||
pip install pyinstaller
|
||||
```
|
||||
|
||||
2. Build a single-file executable:
|
||||
|
||||
```sh
|
||||
pyinstaller --onefile --name dotnuke dotnuke.py
|
||||
```
|
||||
|
||||
3. Find the result in `dist/`: `dist/dotnuke` (macOS/Linux) or `dist\dotnuke.exe`
|
||||
(Windows).
|
||||
|
||||
4. Place `dotnuke.ini` in the **same folder as the executable**, then run it:
|
||||
|
||||
```sh
|
||||
./dotnuke # macOS / Linux
|
||||
dotnuke.exe # Windows
|
||||
```
|
||||
|
||||
The executable looks for its config next to itself (not in PyInstaller's temporary extraction
|
||||
folder), so the file can be edited without rebuilding. You can still pass an explicit config path
|
||||
as the first argument. Copy the executable and ini file together to move them to another machine.
|
||||
|
||||
Notes:
|
||||
|
||||
- PyInstaller does not cross-compile. Build on each OS (and CPU architecture) you target.
|
||||
- Build artifacts (`build/`, `dist/`, `dotnuke.spec`) can be deleted or git-ignored.
|
||||
- On macOS, an unsigned binary copied from another machine may be blocked by Gatekeeper; clear it
|
||||
with `xattr -d com.apple.quarantine dotnuke`.
|
||||
|
||||
## Configuration
|
||||
|
||||
Settings are read from an ini file, by default `dotnuke.ini` in the same folder as the
|
||||
script (or as the executable, when running the PyInstaller build):
|
||||
|
||||
```ini
|
||||
[watch]
|
||||
dir = /Volumes/omniplex/dek-charlie
|
||||
```
|
||||
|
||||
| Section | Option | Required | Description |
|
||||
|---------|--------|----------|------------------------------------------------------------------|
|
||||
| `watch` | `dir` | Yes | Directory to clean and monitor. Subdirectories are included. |
|
||||
|
||||
Path examples for each platform:
|
||||
|
||||
```ini
|
||||
; macOS
|
||||
dir = /Volumes/omniplex/dek-charlie
|
||||
|
||||
; Linux
|
||||
dir = /mnt/omniplex/dek-charlie
|
||||
|
||||
; Windows (forward slashes or backslashes both work; no escaping needed)
|
||||
dir = D:\omniplex\dek-charlie
|
||||
dir = //server/share/dek-charlie
|
||||
```
|
||||
|
||||
Only one `dir` should be active at a time. A leading `~` is expanded to the home directory, and
|
||||
surrounding double quotes are ignored.
|
||||
|
||||
## Usage
|
||||
|
||||
Run from the folder containing the script:
|
||||
|
||||
```sh
|
||||
# macOS / Linux
|
||||
python3 dotnuke.py
|
||||
|
||||
# Windows (Command Prompt or PowerShell)
|
||||
py dotnuke.py
|
||||
```
|
||||
|
||||
To use a different config file, pass its path as the only argument:
|
||||
|
||||
```sh
|
||||
python3 dotnuke.py /path/to/other.ini
|
||||
```
|
||||
|
||||
Stop the service with `Ctrl+C`. If you built the executable, run it instead of the `python`
|
||||
command; arguments work the same way.
|
||||
|
||||
### Running in the background
|
||||
|
||||
The script runs in the foreground and logs to standard output. To keep it running permanently,
|
||||
use your platform's service manager:
|
||||
|
||||
- **macOS:** a `launchd` agent in `~/Library/LaunchAgents`.
|
||||
- **Linux:** a `systemd` unit (or user unit) running `python3 /path/to/dotnuke.py`.
|
||||
- **Windows:** Task Scheduler with the trigger "At log on" or "At startup".
|
||||
|
||||
## How it works
|
||||
|
||||
1. **Initial sweep.** If the configured directory exists, the script walks it recursively, counts
|
||||
the matching files, deletes them, and prints how many were purged. If the directory does not
|
||||
exist yet (for example, a network volume that is not mounted), the sweep is skipped and the
|
||||
script continues to the next step.
|
||||
2. **Watch mode.** The script starts `fswatch` for the directory, subscribed to file *creation*
|
||||
events. Each time `fswatch` reports a batch of events, the script rescans the whole tree and
|
||||
deletes any matching files. Rescanning (rather than parsing individual event paths) keeps the
|
||||
logic simple and handles bursts of events reliably.
|
||||
|
||||
Deletion failures (a file already gone, in use, or read-only) are ignored, so one problem file
|
||||
never stops the service. The file is retried on the next event.
|
||||
|
||||
## Sample output
|
||||
|
||||
```text
|
||||
Starting AppleDouble (._) and .DS_Store auto-cleanup service...
|
||||
👀 Target folder: /Volumes/omniplex/dek-charlie
|
||||
🧹 Running initial cleaning sweep to remove existing ._ and .DS_Store files...
|
||||
Initial cleanup complete. Purged 12 legacy file(s).
|
||||
Entering active watch mode. Listening for new filesystem events...
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause and fix |
|
||||
|---------------------------------------------------|-----------------------------------------------------------------|
|
||||
| `fswatch not found. Install it ...` | `fswatch` is not installed or not on `PATH`. See Dependencies. |
|
||||
| `Config file not found or unreadable: ...` | The ini file is missing; create it or pass its path as an argument. |
|
||||
| `Config file ... must contain [watch] with a 'dir' option.` | The section or option name is misspelled or absent. |
|
||||
| "Target directory does not exist yet..." message | The path is wrong or the volume is not mounted. Mount the volume or fix `dir`, then restart the script (`fswatch` may exit if the path does not exist). |
|
||||
| New files are not removed on a network share | Some network filesystems do not deliver change events. Run the script on the machine that hosts the share, or on a local mount of it. |
|
||||
| Permission errors (silent) | The user running the script needs delete permission on the directory. |
|
||||
|
||||
## Notes
|
||||
|
||||
- The script deletes files permanently; they do not go to the Trash or Recycle Bin. Double-check
|
||||
`dir` before running.
|
||||
- Only the `._*` and `.DS_Store` patterns are matched. To add more, edit the `PATTERNS` tuple near
|
||||
the top of `dotnuke.py`.
|
||||
- Cross-platform behavior beyond macOS follows from the portable Python code and `fswatch`'s
|
||||
per-OS backends; it has not been exercised on every OS/filesystem combination.
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
[watch]
|
||||
dir = /Volumes/omniplex/dek-charlie
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Monitor a directory and remove AppleDouble (._*) and .DS_Store files."""
|
||||
|
||||
import configparser
|
||||
import fnmatch
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
def app_dir():
|
||||
"""Folder containing the executable (frozen) or this script (normal run)."""
|
||||
if getattr(sys, "frozen", False):
|
||||
# In a PyInstaller one-file build __file__ points into a temporary extraction
|
||||
# folder, so use the real executable location instead
|
||||
return os.path.dirname(os.path.abspath(sys.executable))
|
||||
return os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
# Default config lives next to the executable / script
|
||||
DEFAULT_CONFIG = os.path.join(app_dir(), "dotnuke.ini")
|
||||
|
||||
# Glob patterns (matched against file names only) of files to delete
|
||||
PATTERNS = ("._*", ".DS_Store")
|
||||
|
||||
|
||||
def read_watch_dir(config_path):
|
||||
"""Return the directory to watch from the [watch] section of the ini file."""
|
||||
parser = configparser.ConfigParser()
|
||||
# parser.read() returns an empty list if the file is missing or unreadable
|
||||
if not parser.read(config_path):
|
||||
sys.exit(f"Config file not found or unreadable: {config_path}")
|
||||
try:
|
||||
# Tolerate surrounding quotes and a leading "~" in the configured path
|
||||
return os.path.expanduser(parser.get("watch", "dir").strip().strip('"'))
|
||||
except (configparser.NoSectionError, configparser.NoOptionError):
|
||||
sys.exit(f"Config file {config_path} must contain [watch] with a 'dir' option.")
|
||||
|
||||
|
||||
def matches(name):
|
||||
"""True if a file name matches any of the target patterns (case-sensitive)."""
|
||||
return any(fnmatch.fnmatchcase(name, p) for p in PATTERNS)
|
||||
|
||||
|
||||
def find_targets(root):
|
||||
"""Yield paths of matching non-directory entries under root."""
|
||||
# Bottom-up walk mirrors the shell script's "find -depth"
|
||||
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
|
||||
for name in filenames:
|
||||
if matches(name):
|
||||
yield os.path.join(dirpath, name)
|
||||
|
||||
|
||||
def purge(root):
|
||||
"""Remove all matching files; returns number removed."""
|
||||
count = 0
|
||||
for path in find_targets(root):
|
||||
try:
|
||||
os.remove(path)
|
||||
print(f"Removed: {path}", flush=True)
|
||||
count += 1
|
||||
except OSError:
|
||||
# Equivalent of "rm -f" with errors silenced: file may already be gone
|
||||
pass
|
||||
return count
|
||||
|
||||
|
||||
def main():
|
||||
# Optional first argument overrides the config file location
|
||||
config_path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CONFIG
|
||||
watch_dir = read_watch_dir(config_path)
|
||||
|
||||
print("Starting AppleDouble (._) and .DS_Store auto-cleanup service...", flush=True)
|
||||
print(f"👀 Target folder: {watch_dir}", flush=True)
|
||||
|
||||
# STEP 1: initial cleaning sweep
|
||||
if os.path.isdir(watch_dir):
|
||||
print("Running initial cleaning sweep to remove existing ._ and .DS_Store files...",
|
||||
flush=True)
|
||||
# Count first (regular files only, as "find -type f" does) so we can report it
|
||||
initial = sum(
|
||||
1 for p in find_targets(watch_dir)
|
||||
if os.path.isfile(p) and not os.path.islink(p)
|
||||
)
|
||||
if initial > 0:
|
||||
purge(watch_dir)
|
||||
print(f"Initial cleanup complete. Purged {initial} legacy file(s).", flush=True)
|
||||
else:
|
||||
print("Clean sweep complete. No existing ._ or .DS_Store files found.", flush=True)
|
||||
else:
|
||||
# The volume may not be mounted yet; fswatch below is still started
|
||||
print("Target directory does not exist yet. "
|
||||
"Skipping initial clean and waiting for mount...", flush=True)
|
||||
|
||||
# STEP 2: real-time monitoring
|
||||
print("Entering active watch mode. Listening for new filesystem events...", flush=True)
|
||||
|
||||
try:
|
||||
# -o prints a single line with the event count per batch of events,
|
||||
# so each line read below means "something was created"
|
||||
proc = subprocess.Popen(
|
||||
["fswatch", "-o", "--event", "Created", "-x", watch_dir],
|
||||
stdout=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
sys.exit("fswatch not found. Install it (e.g. 'brew install fswatch').")
|
||||
|
||||
try:
|
||||
for _ in proc.stdout:
|
||||
# Rescan the whole tree on each event rather than parsing event paths
|
||||
purge(watch_dir)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
# Make sure the fswatch child does not outlive this script
|
||||
proc.terminate()
|
||||
return proc.wait()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,38 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
|
||||
a = Analysis(
|
||||
['dotnuke.py'],
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[],
|
||||
hiddenimports=[],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
optimize=0,
|
||||
)
|
||||
pyz = PYZ(a.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.datas,
|
||||
[],
|
||||
name='dotnuke',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
runtime_tmpdir=None,
|
||||
console=True,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
Reference in New Issue
Block a user