Compare commits

25 Commits

Author SHA1 Message Date
e76c8726a2 Add automatic prune of trash older than RESRM_TRASH_LIFE value, update README, package version bump 2025-11-12 17:36:51 +00:00
657f14d95d Update README 2025-11-11 19:02:30 +00:00
Marco D'Aleo
b6c6fcc14d Merge pull request #10 from mdaleo404/flags_improvement
Flags improvement
2025-11-11 18:54:05 +00:00
e5f029738a Add version flag, add error message for missing operand, add metavar for restore flag, remove unused recursive argument in move_to_trash function 2025-11-11 18:50:51 +00:00
1fbe499177 Flags improvements and package version bump 2025-11-11 18:11:58 +00:00
662166afb8 Add CODEOWNERS file 2025-11-11 17:30:42 +00:00
Marco D'Aleo
7197bfce0c Merge pull request #9 from mig5/mig/readme-sudo
Clarifications about sudo and secure_path
2025-11-11 17:25:38 +00:00
Miguel Jacq
7ee0e0a99e Clarifications about sudo and secure_path 2025-11-11 15:56:30 +11:00
dcd1165066 Remove legacy resrm repository subdirectory 2025-11-10 13:07:04 +00:00
Marco D'Aleo
45ebe97a9a Merge pull request #8 from mdaleo404/folder_restructure
Folder restructure
2025-11-10 13:05:23 +00:00
dfcffb19e4 Folder restructure 2025-11-10 13:04:02 +00:00
b221fa3534 Release bump to 0.2.0 2025-11-09 11:15:42 +00:00
a24cc8f2b9 remove CONTRIBUTING.md 2025-11-09 11:13:42 +00:00
Marco D'Aleo
d7330933bc Merge pull request #7 from mdaleo404/remove_actions
Remove actions/workflows
2025-11-09 11:11:32 +00:00
ac32bae975 Remove actions/workflows 2025-11-09 11:11:05 +00:00
Marco D'Aleo
b181e31a0c Merge pull request #6 from mdaleo404/gitignore_tweak
chore: remove end of the file line in .gitignore
2025-11-09 11:02:33 +00:00
4fd1243472 chore: remove end of the file line in .gitignore 2025-11-09 11:02:11 +00:00
Marco D'Aleo
328eeaca7a chore: force release
chore: fix workflow
2025-11-09 10:55:32 +00:00
19b79b26ff fix workflow 2025-11-09 10:54:53 +00:00
Marco D'Aleo
a67e31c65d chore: re-trigger release
chore: add new line to end of file core.py
2025-11-09 10:45:50 +00:00
9d4608bd34 add new line to end of file core.py 2025-11-09 10:44:48 +00:00
Marco D'Aleo
27468ae0d0 feat: prepare release cycle
feat: prepare release cycle
2025-11-09 10:35:52 +00:00
8b1d9a81a1 minor change to core.py 2025-11-09 10:34:46 +00:00
6eb3f5a210 Minor fix to inline documentation 2025-11-09 10:25:33 +00:00
Marco D'Aleo
9a64bef661 chore: trigger release
docs: remove end-of-the-file line in CONTRIBUTING.md
2025-11-09 10:10:44 +00:00
16 changed files with 93 additions and 268 deletions

1
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1 @@
* @mdaleo404

View File

@@ -1,48 +0,0 @@
name: Publish to PyPI
on:
push:
tags:
- "*"
jobs:
build-publish:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install Poetry
uses: snok/install-poetry@v1
with:
version: 1.8.4
- name: Install dependencies
run: poetry install --no-root --only main
- name: Build package
run: poetry build
- name: Generate checksums
run: |
cd dist
for file in *; do
sha256sum "$file" > "$file.sha256"
done
- name: Publish to PyPI
env:
POETRY_PYPI_TOKEN_PYPI: ${{ secrets.PYPI_TOKEN }}
run: poetry publish
- name: Upload artifacts to GitHub Release
uses: softprops/action-gh-release@v1
with:
files: |
dist/*

View File

@@ -1,18 +0,0 @@
name: Release Please
on:
push:
branches: ["main"]
permissions:
contents: write
pull-requests: write
jobs:
release-please:
runs-on: ubuntu-latest
steps:
- name: Release Please
uses: googleapis/release-please-action@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}

2
.gitignore vendored
View File

@@ -1,3 +1,3 @@
__pycache__ __pycache__
.pytest_cache .pytest_cache
dist dist

View File

@@ -1,3 +0,0 @@
{
".": "0.1.1"
}

View File

@@ -1,95 +0,0 @@
# How to Contribute to `resrm`
Thanks for your interest in contributing to `resrm`! This guide walks you through the process step by step so you can send contributions with confidence.
### For external contributors
1. **Fork the repository** via GitHub: click *Fork* at the top right.
2. **Clone your fork**:
```bash
git clone https://github.com/<your-username>/resrm.git
cd resrm
```
3. **Add the upstream repo** so you can sync later:
```bash
git remote add upstream https://github.com/mdaleo404/resrm.git
```
4. **Create a feature branch**:
```bash
git checkout -b feature/my-new-thing
```
5. Make your changes and test them locally.
6. **Push to your fork**:
```bash
git push -u origin feature/my-new-thing
```
7. Open a **Pull Request** targeting the `main` branch of the upstream repo.
### For maintainers
You may create branches directly in the main repository without forking.
## Commit Message Style Commit Message Style
To keep the automated changelog clean, follow this commit style:
**Format:**
```
type: short description
```
**Accepted types:**
* `feat:` new features
* `fix:` bug fixes
* `refactor:` internal improvements
* `perf:` performance changes
* `docs:` documentation updates
* `chore:` maintenance
* `test:` test-only changes
**Examples:**
```
feat: add --dry-run flag
fix: handle unicode paths
refactor: simplify cleanup logic
```
Dont overthink it — the maintainer can adjust commit types during merge if needed.
## What Happens After You Submit a PR?
After reviewing your changes, your PR (hopefully) gets merged. Then:
* **Release Please** automatically creates a **release PR** summarizing changes
* The maintainer merges that release PR
* A GitHub Release is created
* The package is published to PyPI
* Wheels, source tarballs, and checksums are attached to the GitHub Release
No need to bump versions manually (unless needed).
## Code Style
* Follow standard Python formatting
* Add type hints when possible
* Keep functions small and readable
* Stick to clear naming
## Need Help, Found a Bug, Have a Request?
If you're unsure about anything:
* **Open an issue**
* Start a discussion
* Ask questions before writing lots of code
## Thank You
Your contributions — large or small — help make `resrm` better for everyone. Thanks for being part of the project!

View File

@@ -7,18 +7,37 @@ It moves files to a per-user _trash_ instead of permanently deleting them, while
## Features ## Features
- Move files and directories to a **trash folder** instead of permanent deletion - Move files and directories to a **Trash folder** instead of permanent deletion
- Restore deleted files by **short ID or exact basename** - Restore deleted files by **short ID or exact basename**
- Empty trash safely - Empty trash safely
- Supports `-r`, `-f`, `-i`, `--perma` options - Supports `-r`, `-f`, `-i`, `--skip-trash` options
- Works with `sudo` for root-owned files - Works with `sudo` for root-owned files
- Automatically prunes Trash entries older than `$RESRM_TRASH_LIFE` days (default **7**, minimum **1**)
> Note: if you need immediate deletion, use the regular `rm` command instead.
---
## Configuration
To control how long trashed files are kept, add this line to your shell configuration (e.g. `~/.bashrc`):
```bash
export RESRM_TRASH_LIFE=10
```
--- ---
## Installation ## Installation
**NOTE:** To use `resrm` with `sudo`, the path to `resrm` must be in the `$PATH` seen by `root`.\ **NOTE:** To use `resrm` with `sudo`, the path to `resrm` must be in the `$PATH` seen by `root`.\
Either install `resrm` as `root` (_preferred_), use `sudo -E resrm`, or add the `$PATH` to `/etc/sudoers` using its `Defaults secure_path` parameter. Either:
* install `resrm` as `root` (_preferred_), or
* add the path to `resrm` to the `secure_path` parameter in `/etc/sudoers`. For example, where `/home/user/.local/bin` is where `resrm` is:
``` bash
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/user/.local/bin"
```
Install via PyPI (_preferred_): Install via PyPI (_preferred_):
@@ -30,7 +49,7 @@ Or clone the repo and install locally:
```bash ```bash
git clone https://github.com/mdaleo404/resrm.git git clone https://github.com/mdaleo404/resrm.git
cd resrm/resrm cd resrm/
poetry install poetry install
``` ```
@@ -50,7 +69,7 @@ resrm -f file
resrm -i file resrm -i file
# Permanent delete (bypass trash) # Permanent delete (bypass trash)
resrm --perma file resrm --skip-trash file
# List trash entries # List trash entries
resrm -l resrm -l
@@ -66,4 +85,4 @@ resrm --empty
Normal users: `~/.local/share/resrm/files` Normal users: `~/.local/share/resrm/files`
Root user: `/root/.local/share/resrm/files` Root user: `/root/.local/share/resrm/files`

View File

View File

@@ -1,6 +1,6 @@
[tool.poetry] [tool.poetry]
name = "resrm" name = "resrm"
version = "0.1.1" version = "0.3.0"
description = "drop-in replacement for rm with undo/restore built-in." description = "drop-in replacement for rm with undo/restore built-in."
authors = ["Marco D'Aleo <marco@marcodaleo.com>"] authors = ["Marco D'Aleo <marco@marcodaleo.com>"]
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"

View File

@@ -1,11 +0,0 @@
{
"release-type": "python",
"package-name": "resrm",
"changelog-sections": [
{ "type": "feat", "section": "Added", "hidden": false },
{ "type": "fix", "section": "Fixed", "hidden": false },
{ "type": "refactor", "section": "Changed", "hidden": false },
{ "type": "perf", "section": "Changed", "hidden": false },
{ "type": "docs", "section": "Documentation", "hidden": false }
]
}

View File

@@ -1,69 +0,0 @@
# resrm
**resrm** is a safe, drop-in replacement for the Linux `rm` command with **undo/restore support**.
It moves files to a per-user _trash_ instead of permanently deleting them, while still allowing full `sudo` support for root-owned files.
---
## Features
- Move files and directories to a **trash folder** instead of permanent deletion
- Restore deleted files by **short ID or exact basename**
- Empty trash safely
- Supports `-r`, `-f`, `-i`, `--perma` options
- Works with `sudo` for root-owned files
---
## Installation
**NOTE:** To use `resrm` with `sudo`, the path to `resrm` must be in the `$PATH` seen by `root`.\
Either install `resrm` as `root` (_preferred_), use `sudo -E resrm`, or add the `$PATH` to `/etc/sudoers` using its `Defaults secure_path` parameter.
Install via PyPI (_preferred_):
```bash
pip install resrm
```
Or clone the repo and install locally:
```bash
git clone https://github.com/mdaleo404/resrm.git
cd resrm/resrm
poetry install
```
## Usage
```bash
# Move files to trash
resrm file1 file2
# Recursive remove of a directory
resrm -r mydir
# Force remove (ignore nonexistent)
resrm -f file
# Interactive remove
resrm -i file
# Permanent delete (bypass trash)
resrm --perma file
# List trash entries
resrm -l
# Restore a file by ID or basename
resrm --restore <id|name>
# Empty the trash permanently
resrm --empty
```
## Trash Location
Normal users: `~/.local/share/resrm/files`
Root user: `/root/.local/share/resrm/files`

View File

@@ -7,7 +7,7 @@ Basic usage:
resrm -r dir # recursive remove (moves dir to trash) resrm -r dir # recursive remove (moves dir to trash)
resrm -f file # ignore nonexistent, no prompt resrm -f file # ignore nonexistent, no prompt
resrm -i file # interactive prompt before removal resrm -i file # interactive prompt before removal
resrm --perma file # permanent delete (bypass trash) resrm --skip-trash file # permanent delete (bypass trash)
resrm -l # list trash entries (neat table) resrm -l # list trash entries (neat table)
resrm --restore <id|name> # restore by short-id (8 chars) or exact basename resrm --restore <id|name> # restore by short-id (8 chars) or exact basename
resrm --empty # empty trash entries (permanent) resrm --empty # empty trash entries (permanent)
@@ -53,6 +53,42 @@ def get_trash_paths() -> tuple[Path, Path]:
TRASH_DIR, META_FILE = get_trash_paths() TRASH_DIR, META_FILE = get_trash_paths()
DATEFMT = "%Y-%m-%d %H:%M" DATEFMT = "%Y-%m-%d %H:%M"
def prune_old_trash():
"""Remove trash entries older than RESRM_TRASH_LIFE days (default 7)."""
try:
life_days = int(os.environ.get("RESRM_TRASH_LIFE", "7"))
except ValueError:
life_days = 7
if life_days < 1:
life_days = 1
cutoff = datetime.datetime.now() - datetime.timedelta(days=life_days)
removed = 0
for entry in list(meta): # make copy since we'll modify meta
try:
ts = datetime.datetime.fromisoformat(entry["timestamp"])
except Exception:
continue # skip malformed entries
if ts < cutoff:
f = TRASH_DIR / entry["id"]
try:
if f.exists():
if f.is_dir():
shutil.rmtree(f, ignore_errors=True)
else:
f.unlink(missing_ok=True)
meta.remove(entry)
removed += 1
except Exception as e:
print(f"Failed to prune {f}: {e}")
if removed > 0:
save_meta(meta)
print(f"Pruned {removed} trash entr{'y' if removed == 1 else 'ies'} older than {life_days} da{'y' if life_days == 1 else 'ys'}.")
def load_meta() -> List[Dict]: def load_meta() -> List[Dict]:
if META_FILE.exists(): if META_FILE.exists():
try: try:
@@ -116,6 +152,8 @@ def find_candidates(identifier: str) -> List[Dict]:
if id_matches: if id_matches:
return id_matches return id_matches
return []
def restore_many(identifiers: List[str]): def restore_many(identifiers: List[str]):
"""Restore multiple files, prompting when needed.""" """Restore multiple files, prompting when needed."""
for identifier in identifiers: for identifier in identifiers:
@@ -216,7 +254,7 @@ def empty_trash():
save_meta(meta) save_meta(meta)
print(f"Trash emptied ({count} entries removed).") print(f"Trash emptied ({count} entries removed).")
def move_to_trash(path: Path, interactive: bool, force: bool, recursive: bool, perma: bool): def move_to_trash(path: Path, interactive: bool, force: bool, skip_trash: bool):
if not path.exists(): if not path.exists():
if force: if force:
return return
@@ -224,7 +262,7 @@ def move_to_trash(path: Path, interactive: bool, force: bool, recursive: bool, p
return return
# Interactive prompt # Interactive prompt
if interactive: if interactive and not force:
try: try:
yn = input(f"remove '{path}'? [y/N] ").strip().lower() yn = input(f"remove '{path}'? [y/N] ").strip().lower()
except KeyboardInterrupt: except KeyboardInterrupt:
@@ -234,7 +272,7 @@ def move_to_trash(path: Path, interactive: bool, force: bool, recursive: bool, p
return return
# Permanent delete path # Permanent delete path
if perma: if skip_trash:
try: try:
if path.is_dir() and not path.is_symlink(): if path.is_dir() and not path.is_symlink():
shutil.rmtree(path) shutil.rmtree(path)
@@ -244,7 +282,7 @@ def move_to_trash(path: Path, interactive: bool, force: bool, recursive: bool, p
print(f"Failed permanent delete: {e}") print(f"Failed permanent delete: {e}")
return return
# 🚫 Prevent non-root user deleting root-owned files # Prevent non-root user deleting root-owned files
try: try:
st = path.stat() st = path.stat()
if st.st_uid == 0 and os.geteuid() != 0: if st.st_uid == 0 and os.geteuid() != 0:
@@ -253,7 +291,7 @@ def move_to_trash(path: Path, interactive: bool, force: bool, recursive: bool, p
except Exception: except Exception:
pass pass
# 🧭 Detect which trash to use (based on file owner) # Detect which trash to use (based on file owner)
try: try:
import pwd import pwd
owner_uid = path.stat().st_uid owner_uid = path.stat().st_uid
@@ -302,23 +340,34 @@ def move_to_trash(path: Path, interactive: bool, force: bool, recursive: bool, p
def main(argv: Optional[List[str]] = None): def main(argv: Optional[List[str]] = None):
if argv is None: if argv is None:
argv = sys.argv[1:] argv = sys.argv[1:]
prune_old_trash()
parser = argparse.ArgumentParser(add_help=False) parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("paths", nargs="*", help="files to remove") parser.add_argument("paths", nargs="*", help="files to remove")
parser.add_argument("-r", action="store_true", help="recursive") parser.add_argument("-r", action="store_true", help="recursive")
parser.add_argument("-f", action="store_true", help="force") parser.add_argument("-f", "--force", action="store_true", help="force")
parser.add_argument("-i", action="store_true", help="interactive") parser.add_argument("-i", action="store_true", help="interactive")
parser.add_argument("--perma", action="store_true", help="permanent delete") parser.add_argument("--skip-trash", action="store_true", help="permanent delete")
parser.add_argument("--restore", nargs="+", help="restore by id or basename") parser.add_argument("--restore", nargs="+", metavar="item", help="restore by id or basename")
parser.add_argument("-l", action="store_true", help="list trash") parser.add_argument("-l", action="store_true", help="list trash")
parser.add_argument("--empty", action="store_true", help="empty the trash permanently") parser.add_argument("--empty", action="store_true", help="empty the trash permanently")
parser.add_argument("--help", action="store_true", help="show help") parser.add_argument("-h", "--help", action="store_true", help="show help")
parser.add_argument("-V", "--version", action="store_true", help="show version")
args = parser.parse_args(argv) args = parser.parse_args(argv)
# Always print docstring if --help or no args # Always print docstring if -h or --help
if args.help or not argv: if args.help:
print(__doc__) print(__doc__)
return return
if args.version:
print("resrm 0.2.1")
return
if not args.paths and not (args.l or args.empty or args.restore):
print("resrm: missing operand")
print("Try 'resrm --help' for more information.")
return
if args.l: if args.l:
list_trash() list_trash()
return return
@@ -344,4 +393,4 @@ def main(argv: Optional[List[str]] = None):
continue continue
print(f"resrm: cannot remove '{pth}': Is a directory") print(f"resrm: cannot remove '{pth}': Is a directory")
continue continue
move_to_trash(pth, interactive=args.i, force=args.f, recursive=args.r, perma=args.perma) move_to_trash(pth, interactive=args.i, force=args.force, skip_trash=args.skip_trash)