122 lines
4.0 KiB
Python
122 lines
4.0 KiB
Python
#!/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())
|