-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
feat(cli): gitnexus remove <target> to unindex a registered repo by name or path (#664) #1003
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
magyargergo
merged 5 commits into
abhigyanpatwari:main
from
azizur100389:feat/cli-remove-command
Apr 21, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
1f4235a
feat(cli): gitnexus remove <target> to unindex a registered repo by n…
azizur100389 c5eceba
fix(cli): canonicalize repo paths so remove/register match across pla…
azizur100389 608299c
fix(cli): store resolved (non-canonical) path, compare via canonicali…
azizur100389 610ee9b
fix(cli): refuse destructive fs.rm when registry storagePath isn't <r…
azizur100389 99c47e3
test(cli): assert full remove dry-run + success output shape (#1003 NIT)
azizur100389 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| /** | ||
| * Remove Command (#664) | ||
| * | ||
| * Delete the `.gitnexus/` index for a registered repo and unregister it | ||
| * from the global registry (~/.gitnexus/registry.json). The target is | ||
| * identified by alias / basename-derived name / remote-inferred name / | ||
| * absolute path — no `--repo` flag, just a positional argument so the | ||
| * destructive-command ergonomics match `clean` (which is also | ||
| * destructive but scoped to `process.cwd()`). | ||
| * | ||
| * Compared to `clean`: | ||
| * - `clean` acts on the repo discovered by walking up from cwd. | ||
| * - `remove` acts on any registered repo identified by name or path. | ||
| * | ||
| * Behaviour notes: | ||
| * - Idempotent on unknown targets: exits 0 with a warning so that | ||
| * `remove X && analyze Y` keeps working in scripts. Per #664: | ||
| * "behave atomically and idempotently so retries are safe". | ||
| * - Atomic order mirrors `clean`: fs.rm FIRST, then unregister. A | ||
| * partial failure leaves the registry pointing at a missing dir | ||
| * (recoverable by `listRegisteredRepos({ validate: true })` on | ||
| * next read) rather than the opposite, which would orphan | ||
| * .gitnexus/ directories on disk. | ||
| * - `-f` / `--force` matches the confirmation-skip semantics of | ||
| * `clean -f`. (Distinct from `analyze --force`, which re-indexes; | ||
| * here there is no pipeline, so no conflation.) | ||
| */ | ||
|
|
||
| import fs from 'fs/promises'; | ||
| import { | ||
| readRegistry, | ||
| resolveRegistryEntry, | ||
| assertSafeStoragePath, | ||
| unregisterRepo, | ||
| RegistryNotFoundError, | ||
| RegistryAmbiguousTargetError, | ||
| UnsafeStoragePathError, | ||
| } from '../storage/repo-manager.js'; | ||
|
|
||
| export const removeCommand = async (target: string, options?: { force?: boolean }) => { | ||
| // Read the registry snapshot once and pass it to the resolver — this | ||
| // lets us render the "before" state in the dry-run path without a | ||
| // second disk read. | ||
| const entries = await readRegistry(); | ||
|
|
||
| let entry; | ||
| try { | ||
| entry = resolveRegistryEntry(entries, target); | ||
| } catch (err) { | ||
| if (err instanceof RegistryNotFoundError) { | ||
| // Idempotent: missing target is a no-op warning, not an error. | ||
| // The `availableNames` hint comes from the error itself so users | ||
| // can see what they might have meant. | ||
| console.warn(`Nothing to remove: ${err.message}`); | ||
| return; | ||
| } | ||
| if (err instanceof RegistryAmbiguousTargetError) { | ||
| // Duplicate aliases are allowed via --allow-duplicate-name (#829); | ||
| // refuse to guess which one the user meant — surface the full list | ||
| // and exit non-zero so scripts don't silently pick the wrong repo. | ||
| console.error(`Error: ${err.message}`); | ||
| process.exit(1); | ||
| } | ||
| throw err; | ||
| } | ||
|
|
||
| // Confirmation gate — same shape as `clean`. Default is a dry-run | ||
| // that describes what would be deleted; `--force` actually deletes. | ||
| if (!options?.force) { | ||
| console.log(`This will delete the GitNexus index for: ${entry.name}`); | ||
| console.log(` Path: ${entry.path}`); | ||
| console.log(` Storage: ${entry.storagePath}`); | ||
| console.log('\nRun with --force to confirm deletion.'); | ||
| return; | ||
| } | ||
|
|
||
| // Safety guard (#1003 review — @magyargergo): refuse to proceed if | ||
| // the registry entry's `storagePath` isn't the canonical | ||
| // `<entry.path>/.gitnexus` subfolder. `~/.gitnexus/registry.json` is | ||
| // user-writable, so a corrupted or hand-edited entry could point | ||
| // storagePath at the repo root, an empty string (→ cwd), a parent | ||
| // dir, or anywhere else; `fs.rm(recursive: true, force: true)` on | ||
| // any of those would be a runtime disaster. Bail before touching | ||
| // disk, with an actionable hint for recovering a broken registry. | ||
| try { | ||
| assertSafeStoragePath(entry); | ||
| } catch (err) { | ||
| if (err instanceof UnsafeStoragePathError) { | ||
| console.error(`Error: ${err.message}`); | ||
| process.exit(1); | ||
| } | ||
| throw err; | ||
| } | ||
|
|
||
| // Deletion order: fs.rm first, then unregister. If fs.rm fails mid-way, | ||
| // the registry entry stays so the user can retry. If fs.rm succeeds but | ||
| // unregister throws (e.g. ENOSPC on registry write), the entry becomes | ||
| // orphaned — `listRegisteredRepos({ validate: true })` prunes those on | ||
| // next read, so the failure is self-healing. | ||
| try { | ||
| await fs.rm(entry.storagePath, { recursive: true, force: true }); | ||
| await unregisterRepo(entry.path); | ||
| console.log(`Removed: ${entry.name}`); | ||
| console.log(` Path: ${entry.path}`); | ||
| console.log(` Storage: ${entry.storagePath}`); | ||
| } catch (err) { | ||
| console.error(`Failed to remove ${entry.name}:`, err); | ||
| process.exit(1); | ||
| } | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please be very careful here! We don't want to remove the physical path of the code base. We can safely remove files/folders int the
.gitnexusfolder but outside is prohibited. Please introduce safe guards here.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch, thank you. Addressed in
610ee9b9with a guard that blocks destructive fs.rm whenever the registry entry's storagePath isn't the canonical<entry.path>/.gitnexussubfolder.The threat model
~/.gitnexus/registry.jsonis a plain-text user-writable file. A corrupted or hand-edited entry could plausibly end up with:storagePath === entry.path(the repo root → catastrophic: fs.rm recursively wipes the working tree)storagePath === ""(path.resolve resolves to cwd → rm cwd)storagePathpointing at a parent dir, sibling dir, or anywhere elsefs.rm(recursive: true, force: true)on any of those is a runtime disaster.Fix shape
New
UnsafeStoragePathError+ exportedassertSafeStoragePath()inrepo-manager.ts. Pure lexical string check (Windows case-insensitive) assertingentry.storagePath === path.join(entry.path, '.gitnexus'). Does NOT depend on the paths existing — it's a structural integrity check on the registry, not a filesystem probe.Audit & sibling fix
Before committing I audited every
fs.rm(...storagePath...)site in the codebase:remove.tsentry.storagePathfrom registryclean.ts --allentry.storagePathfrom registry (same pattern)clean.tsdefaultfindRepo(cwd)→ lexically recomputedserver/api.tsgetStoragePath(entry.path)→ lexically recomputedclean --allskips poisoned entries with a warning and continues with the rest of the batch — preserves its existing per-repo error-tolerance semantics (one bad entry doesn't halt cleanup).Tests
<repo>/.gitnexus, repo-root-as-storage (catastrophic case), parent-as-storage, empty storage (→ cwd), totally-unrelated path, sibling.gitnexus(right basename, wrong parent), error payload shape, Windows case-insensitive acceptance..git/+.gitnexus/all survive on disk, (c) registry state is correct (poisoned entry retained, valid siblings cleaned). One test coversremove, one coversclean --allwith a mixed good/bad registry.Local verification
tsc --noEmitcleanrepo-manager.test.ts49/49cli-e2e.test.ts -t "remove|clean --all"4/4 (3 remove + 1 new clean --all poisoned)CI on
610ee9b9should light up green shortly.