Skip to content

Instantly share code, notes, and snippets.

@sunfkny
Last active March 3, 2024 13:54
Show Gist options
  • Save sunfkny/df27f70ff068f914717e0d2ea8c973c4 to your computer and use it in GitHub Desktop.
Save sunfkny/df27f70ff068f914717e0d2ea8c973c4 to your computer and use it in GitHub Desktop.
import os
import shutil
import click
from pathlib import Path
def is_apple_double_file(path: Path) -> bool:
return (
path.is_file()
and path.name.startswith("._")
and path.with_name(path.name.removeprefix("._")).is_file()
)
def is_ds_store_file(path: Path) -> bool:
return path.is_file() and path.name == ".DS_Store"
def is_macosx_directory(path: Path) -> bool:
return path.is_dir() and path.name == "__MACOSX"
def is_path_in_macosx_directory(path: Path) -> bool:
return "__MACOSX" in path.parent.parts
@click.command()
@click.argument(
"directories",
nargs=-1,
type=click.Path(exists=True, file_okay=False),
required=True,
)
@click.option("-y", "--yes", is_flag=True, help="Delete without confirmation")
def unmac(directories: list[str], yes: bool):
files_to_delete: list[Path] = []
directories_to_delete: list[Path] = []
directories_path = [Path(directory) for directory in directories]
for directory_path in directories_path:
click.echo(f"Processing directory: {directory_path}")
for item in directory_path.glob("**/*"):
if is_macosx_directory(item):
click.echo(f"Would delete: {item}{os.sep}")
directories_to_delete.append(item)
if (
is_ds_store_file(item) or is_apple_double_file(item)
) and not is_path_in_macosx_directory(path=item):
click.echo(f"Would delete: {item}")
files_to_delete.append(item)
if not directories_to_delete and not files_to_delete:
click.echo("Nothing to delete")
return
if not yes:
click.confirm("Are you sure to delete these files/directories?", abort=True)
for path in directories_to_delete:
click.echo(f"Deleting: {path}")
if path.is_dir():
shutil.rmtree(path)
for path in files_to_delete:
click.echo(f"Deleting: {path}")
if path.is_file():
path.unlink()
if __name__ == "__main__":
unmac()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment