From ecb149971b1ebe1fb7ba869c199def591d5623ce Mon Sep 17 00:00:00 2001 From: indroneel Date: Wed, 16 Sep 2026 23:31:13 +0530 Subject: [PATCH] major changes --- .gitignore | 1 + README.md | 203 ++++++++++++++++-- docs/build-from-source.md | 65 ++++++ docs/usage.md | 96 +++++++++ pyproject.toml | 3 +- .../command.py => commands/create/handler.py} | 34 ++- src/unique/commands/duplicate/handler.py | 33 +++ src/unique/commands/install/handler.py | 30 +++ src/unique/commands/retouch/handler.py | 2 + .../command.py => commands/touch/handler.py} | 22 +- src/unique/lib/suffix.py | 18 +- src/unique/main.py | 5 +- src/unique/modules/duplicate/command.py | 13 -- src/unique/modules/install/command.py | 13 -- src/unique/modules/retouch/command.py | 39 ---- unique.spec | 40 ++++ 16 files changed, 500 insertions(+), 117 deletions(-) create mode 100644 docs/build-from-source.md create mode 100644 docs/usage.md rename src/unique/{modules/create/command.py => commands/create/handler.py} (55%) create mode 100644 src/unique/commands/duplicate/handler.py create mode 100644 src/unique/commands/install/handler.py create mode 100644 src/unique/commands/retouch/handler.py rename src/unique/{modules/touch/command.py => commands/touch/handler.py} (52%) delete mode 100644 src/unique/modules/duplicate/command.py delete mode 100644 src/unique/modules/install/command.py delete mode 100644 src/unique/modules/retouch/command.py create mode 100644 unique.spec diff --git a/.gitignore b/.gitignore index 4fdfc91..2084afb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /.venv /dist +/build *.egg-info __pycache__ diff --git a/README.md b/README.md index 7e9b9a6..3114102 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,202 @@ # unique -A utility that appends a suffix to files and folders to ensure name uniqueness. +A small but practical command-line utility for creating safe, unique file and directory names. -## Building from source +When scripts, backups, content pipelines, or file-based workflows need to create or rename paths +without collisions, `unique` appends a timestamp-, UUID-, or entropy-based suffix to keep names +distinct, readable, and easy to trace. -### 1. Virtual Environment +## Why use unique? -Create a virtual environment for Python, and activate the same. +File naming collisions are a recurring problem in scripting, automation, backups, content pipelines, +and content authoring workflows. `unique` gives you a simple interface to: -```sh +- create a new file or directory with a guaranteed unique name +- rename an existing path to have a unique name +- duplicate a file while preserving its original contents under a fresh name +- choose the suffix generation method that best fits your workflow + +## Features + +- Create files or directories with unique names +- Rename existing files or folders safely +- Duplicate files with a unique derivative name +- Multiple suffix strategies: + - `datetime` + - `epoch` + - `uuid` + - `uuid7` + - `uuid-b36` + - `uuid7-b36` +- Python-based CLI design for simple automation and scripting + +## Documentation + +- [Build from Source](docs/build-from-source.md) — set up the project and produce a distributable build. +- [Using unique](usage.md) — learn the CLI commands and examples. + +## Installation + +### Prerequisites + +- Python 3 +- `pip` + +### Set up a virtual environment + +```bash python3 -m venv .venv - source .venv/bin/activate ``` -### 2. Resolve Dependencies +### Install dependencies -Unique has a dependency on Scott: a framework to create scoped task-oriented terminal tools. To resolve this, run: - -```sh +```bash pip install "git+https://rprime.indroneel.co/termhole/scott.git" -``` - -For older versions of Python, Unique has a dependency on a backported UUID library: - -```sh pip install uuid6 ``` -### 3. Installing the Application +### Install the project -To install `unique` in the virtual environment, run: - -```sh +```bash pip install -e . ``` + +You can then invoke the CLI as: + +```bash +unique --help +``` + +## Usage + +The CLI is organized around a small set of commands. + +### Create a unique file + +```bash +unique create --file notes.txt +``` + +Example result: + +```text +notes-20260916-153425.txt +``` + +### Create a unique directory + +```bash +unique create --dir project +``` + +Example result: + +```text +project-20260916-153425 +``` + +### Rename an existing file or directory + +```bash +unique touch report.md +``` + +This appends a generated suffix to the original path instead of overwriting an existing file. + +### Duplicate a file with a unique name + +```bash +unique duplicate ./archive.tar.gz +``` + +Example result: + +```text +archive-20260916-153425.tar.gz +``` + +## Suffix methods + +You can control the suffix algorithm with the `--method` option: + +```bash +unique create --file draft.txt --method uuid7 +``` + +Available methods: + +- `datetime` — current date and time +- `epoch` — Unix timestamp in milliseconds +- `uuid` — UUID v4 +- `uuid7` — UUID v7 +- `uuid-b36` — base36 UUID representation +- `uuid7-b36` — base36 UUID v7 representation + +## Command reference + +### `unique create` + +Create a file or directory with a unique name. + +```bash +unique create PATH --file|--dir [--method METHOD] +``` + +### `unique touch` + +Rename an existing file or directory to a unique variant. + +```bash +unique touch PATH [--method METHOD] +``` + +### `unique duplicate` + +Create a copy of an existing file with a unique name. + +```bash +unique duplicate PATH [--method METHOD] +``` + +## Examples + +```bash +# Create a unique file using a UUID v7 suffix +unique create --file draft.md --method uuid7 + +# Create a unique directory using the current timestamp +unique create --dir content --method datetime + +# Rename an existing file to a unique version +unique touch ./notes.txt --method epoch + +# Duplicate a file without clobbering the original +unique duplicate ./backup.db --method uuid-b36 +``` + +## Project layout + +```text +unique/ +├── LICENSE +├── README.md +├── pyproject.toml +├── unique.spec +├── src/ +│ └── unique/ +│ ├── commands/ +│ ├── lib/ +│ └── main.py +└── .venv/ +``` + +## License + +This project is licensed under the terms of the repository license. See [LICENSE](LICENSE) for details. + +## Notes + +This project is intentionally compact and script-friendly: it focuses on one task well—creating unique names for paths—while leaving room for automation in shell scripts, build tooling, and content workflows. + +If you want to package it into a standalone executable, the repository includes a PyInstaller spec file at [unique.spec](unique.spec). diff --git a/docs/build-from-source.md b/docs/build-from-source.md new file mode 100644 index 0000000..7dfefe6 --- /dev/null +++ b/docs/build-from-source.md @@ -0,0 +1,65 @@ +--- +title: Unique - Build from Source +--- + +# Unique - Build from Source + +Open a terminal and change the active directory to the project root folder for `unique`. + +Follow the given steps in order to create a clean Python sandbox, activate it, install the build +tool, and then use that tool to compile `unique` into distributable artifacts. + +__Step 1: Create an isolated virtual environment.__ + +```sh +python3 -m venv .venv +``` + +The virtual environment is created in a folder called `.venv` under the project root folder. This +gives the project its own Python interpreter and package space, so dependencies don't conflict with +the system Python or other projects. + +__Step 2: Activate the virtual environment.__ + +```sh +source .venv/bin/activate +``` + +Activation happens for the current shell session only. It prepends `.venv/bin/` to your `PATH`, so +`python` and `pip` now resolve to the environment's copies. Your prompt typically changes to show +`(.venv)`. + +__Step 3: Install (or upgrade) the build package.__ + +```sh +pip install --upgrade build +``` + +The virtual environment now has the latest `build` package. `build` is the PyPA-recommended PEP 517 +build frontend — it reads the project's `pyproject.toml`, sets up an isolated build environment, and +invokes the configured build backend (`setuptools`) to produce distribution artifacts. + +__Step 4: Install unique.__ + +```sh +pip install -e . +``` + +This installs unique in editable mode. In the process, all required depedencies (`scott` and +`uuid6`) are also installed in the virtual environment. + +__Step 5: Create a binary distributable.__ + +Firstly install `pyinstaller` in the virtual environment. + +```sh +pip install pyinstaller +``` + +Then create the executable: + +```sh +pyinstaller unique.spec +``` + +This creates an executable file named `unique` that is placed in `/dist` under project root folder. diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..6345ac3 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,96 @@ +--- +title: Unique - Usage +--- + +# Using Unique + +`Unique` is organized around a small set of commands. You can get a list of available commands by +invoking `unique` with help option. + +```sh +$ ./unique -h + +usage: unique [-h] {install,create,touch,retouch,duplicate} ... + +Append a suffix to files and folders to ensure unique names + +positional arguments: + {install,create,touch,retouch,duplicate} + install installs unique so that it can be used from the command line + create Create a new file or directory with a unique name + touch appends a prefix to the original file name to create a unique name + retouch + duplicate Creates an exact copy of a file, preserving its contents, but with an unique name + +options: + -h, --help show this help message and exit +``` + +## Command: create + +```sh +$ ./unique create -h +usage: unique create [-h] (-f | -d) [-m METHOD] PATH + +positional arguments: + PATH The path to the file or directory to be created with a unique name + +options: + -h, --help show this help message and exit + -f, --file Indicates that the target is a file + -d, --dir Indicates that the target is a folder + -m METHOD, --method METHOD + Select the method to generate the suffix: + 'datetime' : Use the current date and time as a unique suffix + 'epoch' : Use the timestamp (milliseconds since epoch) as a unique suffix + 'uuid' : Use the v4 universally unique identifier as a unique suffix + 'uuid7' : Use the v7 universally unique identifier as a unique suffix + 'uuid-b36' : Use the base36 representation of a UUID as a unique suffix + 'uuid7-b36' : Use the base36 representation of a UUID7 as a unique suffix + Default is 'datetime'. +``` + +## Command: touch + +```sh +$ ./unique touch -h +usage: unique touch [-h] [-m METHOD] PATH + +positional arguments: + PATH The path to the file or directory that needs a unique name + +options: + -h, --help show this help message and exit + -m METHOD, --method METHOD + Select the method to generate the suffix: + 'datetime' : Use the current date and time as a unique suffix + 'epoch' : Use the timestamp (milliseconds since epoch) as a unique suffix + 'uuid' : Use the v4 universally unique identifier as a unique suffix + 'uuid7' : Use the v7 universally unique identifier as a unique suffix + 'uuid-b36' : Use the base36 representation of a UUID as a unique suffix + 'uuid7-b36' : Use the base36 representation of a UUID7 as a unique suffix + Default is 'datetime'. +``` + +## Command: duplicate + +```sh +$ ./unique duplicate -h +usage: unique duplicate [-h] [-m METHOD] PATH + +positional arguments: + PATH The path to the file or directory to be created with a unique name + +options: + -h, --help show this help message and exit + -m METHOD, --method METHOD + Select the method to generate the suffix: + 'datetime' : Use the current date and time as a unique suffix + 'epoch' : Use the timestamp (milliseconds since epoch) as a unique suffix + 'uuid' : Use the v4 universally unique identifier as a unique suffix + 'uuid7' : Use the v7 universally unique identifier as a unique suffix + 'uuid-b36' : Use the base36 representation of a UUID as a unique suffix + 'uuid7-b36' : Use the base36 representation of a UUID7 as a unique suffix + Default is 'datetime'. +``` + diff --git a/pyproject.toml b/pyproject.toml index 727461f..85d8c18 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,8 @@ description = "A utility that appends a suffix to files and folders to ensure na #External dependencies dependencies = [ - "scott @ git+https://rprime.indroneel.co/termhole/scott.git" + "scott @ git+https://rprime.indroneel.co/termhole/scott.git", + "uuid6" ] # Command-line interface (CLI) entry points diff --git a/src/unique/modules/create/command.py b/src/unique/commands/create/handler.py similarity index 55% rename from src/unique/modules/create/command.py rename to src/unique/commands/create/handler.py index 7c0afce..1352d22 100644 --- a/src/unique/modules/create/command.py +++ b/src/unique/commands/create/handler.py @@ -1,10 +1,18 @@ from pathlib import Path from unique.lib import suffix -def scott_description(): +""" ===== +Describes this command. +===== """ + +def s_description(): return "Create a new file or directory with a unique name" -def scott_arguments(parser): +""" ===== +Lets the user specify the arguments for the create command. +===== """ + +def s_arguments(parser): parser.add_argument( "path", type=str, metavar="PATH", help = "The path to the file or directory to be created with a unique name" @@ -22,23 +30,27 @@ def scott_arguments(parser): suffix.add_method_argument(parser) -def scott_run(args): +""" ===== +Executes the create command, creating a new file or directory with a unique name. +===== """ + +def s_run(args): path = Path(args.path) - suffix = suffix.get_suffix(args.method) + sufstr = suffix.get_suffix(args.method) if args.file: - candidate = path.with_name(f"{path.stem}-{suffix}{path.suffix}") + target = path.with_name(f"{path.stem}-{sufstr}{path.suffix}") else: - candidate = path.with_name(f"{path.name}-{suffix}") + target = path.with_name(f"{path.name}-{sufstr}") - if candidate.exists(): - print(f"Cannot create '{candidate}': candidate already exists.") + if target.exists(): + print(f"Cannot create '{target}': target already exists.") return if args.file: - candidate.touch() + target.touch() else: - candidate.mkdir() + target.mkdir() - print(f"Created unique { 'file' if args.file else 'directory' }: {candidate}") + print(f"Created unique { 'file' if args.file else 'directory' }: {target}") diff --git a/src/unique/commands/duplicate/handler.py b/src/unique/commands/duplicate/handler.py new file mode 100644 index 0000000..e950722 --- /dev/null +++ b/src/unique/commands/duplicate/handler.py @@ -0,0 +1,33 @@ +from pathlib import Path +import shutil +from unique.lib import suffix + +def s_description(): + return "Creates an exact copy of a file, preserving its contents, but with an unique name" + +def s_arguments(parser): + parser.add_argument( + "path", type=str, metavar="PATH", + help = "The path to the file or directory to be created with a unique name" + ) + suffix.add_method_argument(parser) + + +def s_run(args): + path = Path(args.path) + if not path.exists(): + print(f"Cannot duplicate '{path}': candidate does not exist.") + return + if not path.is_file(): + print(f"Cannot duplicate '{path}': candidate is not a file.") + return + + sufstr = suffix.get_suffix(args.method) + + target = path.with_name(f"{path.stem}-{sufstr}{path.suffix}") + if target.exists(): + print(f"Cannot duplicate '{path}': candidate already exists.") + return + + shutil.copy2(path, target) + print(f"Duplicated into: {target}") \ No newline at end of file diff --git a/src/unique/commands/install/handler.py b/src/unique/commands/install/handler.py new file mode 100644 index 0000000..16ed127 --- /dev/null +++ b/src/unique/commands/install/handler.py @@ -0,0 +1,30 @@ +import sys +from pathlib import Path + + +def s_description(): + return "installs unique so that it can be used from the command line" + + +def s_run(args): + + """ + This checks whether the program is running as a PyInstaller-built executable. + sys.frozen is set by PyInstaller when the application is packaged. + getattr(sys, "frozen", False) safely reads it: returns its value if present and returns False if + it does not exist + """ + + if not getattr(sys, "frozen", False): + raise RuntimeError("install must be run from the PyInstaller executable") + + executable = Path(sys.executable).resolve() + link_path = Path.home() / ".local" / "bin" / "unique" + link_path.parent.mkdir(parents=True, exist_ok=True) + + if link_path.exists() and link_path.is_dir() and not link_path.is_symlink(): + raise RuntimeError(f"cannot replace directory: {link_path}") + + link_path.unlink(missing_ok=True) + link_path.symlink_to(executable) + print(f"Installed {link_path} -> {executable}") \ No newline at end of file diff --git a/src/unique/commands/retouch/handler.py b/src/unique/commands/retouch/handler.py new file mode 100644 index 0000000..97977f0 --- /dev/null +++ b/src/unique/commands/retouch/handler.py @@ -0,0 +1,2 @@ +def s_run(args): + pass \ No newline at end of file diff --git a/src/unique/modules/touch/command.py b/src/unique/commands/touch/handler.py similarity index 52% rename from src/unique/modules/touch/command.py rename to src/unique/commands/touch/handler.py index d679f4f..a43ce6f 100644 --- a/src/unique/modules/touch/command.py +++ b/src/unique/commands/touch/handler.py @@ -1,10 +1,10 @@ from pathlib import Path from unique.lib import suffix -def scott_description(): +def s_description(): return "appends a prefix to the original file name to create a unique name" -def scott_arguments(parser): +def s_arguments(parser): parser.add_argument( "path", type=str, metavar="PATH", @@ -13,23 +13,23 @@ def scott_arguments(parser): suffix.add_method_argument(parser) -def scott_run(args): +def s_run(args): path = Path(args.path) if not path.exists(): print(f"Cannot touch '{path}': path does not exist.") return - generated_suffix = suffix.get_suffix(args.method) + sufstr = suffix.get_suffix(args.method) if path.is_file(): - candidate = path.with_name( - f"{path.stem}-{generated_suffix}{path.suffix}" + target = path.with_name( + f"{path.stem}-{sufstr}{path.suffix}" ) else: - candidate = path.with_name(f"{path.name}-{generated_suffix}") + target = path.with_name(f"{path.name}-{sufstr}") - if candidate.exists(): - print(f"Cannot touch '{path}': candidate already exists.") + if target.exists(): + print(f"Cannot touch '{path}': file already exists.") return - path.rename(candidate) - print(f"Touched '{path}' to '{candidate}'") \ No newline at end of file + path.rename(target) + print(f"Touched '{path}' to '{target}'") \ No newline at end of file diff --git a/src/unique/lib/suffix.py b/src/unique/lib/suffix.py index 7461e13..6c10f7d 100644 --- a/src/unique/lib/suffix.py +++ b/src/unique/lib/suffix.py @@ -51,12 +51,14 @@ def add_method_argument(parser): type=str, metavar="METHOD", choices=["datetime", "epoch", "uuid", "uuid7", "uuid-b36", "uuid7-b36"], required=False, default="datetime", - help = """Select the method to generate the suffix: - 'datetime' : Use the current date and time as a unique suffix - 'epoch' : Use the timestamp (milliseconds since epoch) as a unique suffix - 'uuid' : Use the v4 universally unique identifier as a unique suffix - 'uuid7' : Use the v7 universally unique identifier as a unique suffix - 'uuid-b36' : Use the base36 representation of a UUID as a unique suffix - 'uuid7-b36' : Use the base36 representation of a UUID7 as a unique suffix - Default is 'datetime'.""" + help=textwrap.dedent("""\ + Select the method to generate the suffix: + 'datetime' : Use the current date and time as a unique suffix + 'epoch' : Use the timestamp (milliseconds since epoch) as a unique suffix + 'uuid' : Use the v4 universally unique identifier as a unique suffix + 'uuid7' : Use the v7 universally unique identifier as a unique suffix + 'uuid-b36' : Use the base36 representation of a UUID as a unique suffix + 'uuid7-b36' : Use the base36 representation of a UUID7 as a unique suffix + Default is 'datetime'. + """).strip(), ) \ No newline at end of file diff --git a/src/unique/main.py b/src/unique/main.py index 55afc84..2143753 100644 --- a/src/unique/main.py +++ b/src/unique/main.py @@ -2,6 +2,7 @@ import sys sys.dont_write_bytecode = True from scott import Scott +from unique.lib import suffix def main(): scott = Scott(__file__, "Append a suffix to files and folders to ensure unique names") @@ -12,8 +13,8 @@ def main(): "retouch", "duplicate", ] - for command in commands: - scott.register_command(command) + for cmd in commands: + scott.register(cmd) scott.run() diff --git a/src/unique/modules/duplicate/command.py b/src/unique/modules/duplicate/command.py deleted file mode 100644 index 7f58072..0000000 --- a/src/unique/modules/duplicate/command.py +++ /dev/null @@ -1,13 +0,0 @@ -def scott_description(): - return "Creates an exact copy of a file, preserving its contents, but with an unique name" - -def scott_arguments(parser): - """ - parser.add_argument( - "file_path", - help="The path where the file to be unpacked." - ) - """ - -def scott_run(args): - print("command: duplicate") diff --git a/src/unique/modules/install/command.py b/src/unique/modules/install/command.py deleted file mode 100644 index 6e5680b..0000000 --- a/src/unique/modules/install/command.py +++ /dev/null @@ -1,13 +0,0 @@ -def scott_description(): - return "your description here" - -def scott_arguments(parser): - """ - parser.add_argument( - "file_path", - help="The path where the file to be unpacked." - ) - """ - -def scott_run(args): - print("command: install") diff --git a/src/unique/modules/retouch/command.py b/src/unique/modules/retouch/command.py deleted file mode 100644 index 2f1628a..0000000 --- a/src/unique/modules/retouch/command.py +++ /dev/null @@ -1,39 +0,0 @@ -def scott_description(): - return "updates an existing file name with a new prefix" - -def scott_arguments(parser): - parser.add_argument( - "path", type=str, metavar="PATH", - help = "The path to the file or directory that needs a unique name" - ) - - target = parser.add_mutually_exclusive_group(required=True) - target.add_argument( - "-f", "--file", action="store_true", - help = "Indicates that the target is a file" - ) - target.add_argument( - "-d", "--dir", action="store_true", - help = "Indicates that the target is a folder" - ) - - method = parser.add_mutually_exclusive_group(required=True) - method.add_argument( - "--datetime", action="store_true", - help = "Use the current date and time as a unique suffix" - ) - method.add_argument( - "--epoch", action="store_true", - help = "Use the timestamp (milliseconds since epoch) as a unique suffix" - ) - method.add_argument( - "--uuid", action="store_true", - help = "Use the universally unique identifier as a unique suffix" - ) - method.add_argument( - "--random", action="store_true", - help = "Use a random number as a unique suffix" - ) - -def scott_run(args): - print("command: retouch") diff --git a/unique.spec b/unique.spec new file mode 100644 index 0000000..ff53361 --- /dev/null +++ b/unique.spec @@ -0,0 +1,40 @@ +# -*- mode: python ; coding: utf-8 -*- + + +a = Analysis( + ['src/unique/main.py'], + pathex=[], + binaries=[], + datas=[ + ('src/unique/commands', 'commands'), + ('src/unique/lib', 'unique/lib')], + hiddenimports=[], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=[], + noarchive=False, + optimize=0, +) +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + a.binaries, + a.datas, + [], + name='unique', + 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, +)