Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,15 @@ For other platforms and more installation options, visit: https://cli.github.com

# Commands

## Output Modes

Ghouls supports two output modes to suit different use cases:

- **Default mode**: Shows essential information only - final results, summaries, and errors. Ideal for scripts and everyday use.
- **Verbose mode** (`-v` or `--verbose`): Shows detailed progress information including scanning progress, branch analysis details, and progress bars. Useful for debugging or understanding what the tool is doing.

All commands support both output modes. Use the verbose flag when you need more insight into the cleanup process.

## Delete remote branches

Safely deletes remote branches that have been merged via pull requests.
Expand All @@ -104,13 +113,24 @@ Run from within a git repository (auto-detects repo):
ghouls remote --dry-run
```

For detailed output including progress information, use the verbose flag:
```bash
ghouls remote --dry-run --verbose
# or
ghouls remote --dry-run -v
```

The auto-detection feature works with both github.com and GitHub Enterprise repositories, automatically detecting the repository owner/name from the remote URL.

Or specify a repository explicitly:
```bash
ghouls remote --dry-run myorg/myrepo
```

### Interactive Mode

When running without `--dry-run` or `--force` flags, the remote command runs in interactive mode, allowing you to review and confirm each branch deletion. Press **Escape** at any time during the interactive selection to cancel the operation and return to the command prompt without making any changes.

```
$ ghouls remote myorg/myrepo
#1871 - Deleting remote: heads/fix/fe-nits
Expand All @@ -129,11 +149,22 @@ Run from within a git repository (auto-detects repo):
ghouls local --dry-run
```

For detailed output including progress information, use the verbose flag:
```bash
ghouls local --dry-run --verbose
# or
ghouls local --dry-run -v
```

Or specify a repository explicitly:
```bash
ghouls local --dry-run myorg/myrepo
```

### Interactive Mode

When running without `--dry-run` or `--force` flags, the local command runs in interactive mode, allowing you to review and confirm each branch deletion. Press **Escape** at any time during the interactive selection to cancel the operation and return to the command prompt without making any changes.

### Safety Features

The `local` command includes several safety checks to prevent accidental deletion of important branches:
Expand Down Expand Up @@ -184,11 +215,22 @@ Run from within a git repository (auto-detects repo):
ghouls all --dry-run
```

For detailed output including progress information, use the verbose flag:
```bash
ghouls all --dry-run --verbose
# or
ghouls all --dry-run -v
```

Or specify a repository explicitly:
```bash
ghouls all --dry-run myorg/myrepo
```

### Interactive Mode

When running without `--dry-run` or `--force` flags, the all command runs in interactive mode for both remote and local cleanup phases. Press **Escape** at any time during either interactive selection to cancel the current operation and return to the command prompt without making any changes.

### Execution Order

The command executes in two phases:
Expand Down
41 changes: 30 additions & 11 deletions src/commands/PruneAll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,22 @@ import type { CommandModule } from "yargs";
import { createOctokitPlus } from "../utils/createOctokitPlus.js";
import { getGitRemote } from "../utils/getGitRemote.js";
import { isGitRepository } from "../utils/localGitOperations.js";
import {
output,
outputSection,
outputSuccess,
outputError,
outputWarning
} from "../utils/outputFormatter.js";

export const pruneAllCommand: CommandModule = {
handler: async (args: any) => {
// Set output options based on CLI flags
const { setOutputOptions } = await import("../utils/outputFormatter.js");
setOutputOptions({
verbose: Boolean(args.verbose)
});

let owner: string;
let repo: string;

Expand All @@ -31,15 +44,15 @@ export const pruneAllCommand: CommandModule = {
// but the actual API calls are made within the individual command handlers
createOctokitPlus();

console.log("🚀 Starting combined branch cleanup...\n");
output("🚀 Starting combined branch cleanup...");

let remoteSuccess = false;
let localSuccess = false;
let remoteError: Error | undefined;
let localError: Error | undefined;

// Phase 1: Remote branch pruning
console.log("=== Phase 1: Remote Branch Cleanup ===");
outputSection("Phase 1: Remote Branch Cleanup");
try {
// Import dynamically to avoid circular dependencies
const { prunePullRequestsCommand } = await import("./PrunePullRequests.js");
Expand All @@ -50,11 +63,11 @@ export const pruneAllCommand: CommandModule = {
remoteSuccess = true;
} catch (error) {
remoteError = error instanceof Error ? error : new Error(String(error));
console.error(`\n❌ Remote cleanup failed: ${remoteError.message}`);
outputError(`❌ Remote cleanup failed: ${remoteError.message}`);
}

// Phase 2: Local branch pruning (continue even if remote failed)
console.log("\n=== Phase 2: Local Branch Cleanup ===");
outputSection("Phase 2: Local Branch Cleanup");
try {
// Import dynamically to avoid circular dependencies
const { pruneLocalBranchesCommand } = await import("./PruneLocalBranches.js");
Expand All @@ -65,24 +78,24 @@ export const pruneAllCommand: CommandModule = {
localSuccess = true;
} catch (error) {
localError = error instanceof Error ? error : new Error(String(error));
console.error(`\n❌ Local cleanup failed: ${localError.message}`);
outputError(`❌ Local cleanup failed: ${localError.message}`);
}

// Final summary
console.log("\n=== Combined Cleanup Summary ===");
console.log(`Remote cleanup: ${remoteSuccess ? "✅ Success" : "❌ Failed"}`);
console.log(`Local cleanup: ${localSuccess ? "✅ Success" : "❌ Failed"}`);
outputSection("Combined Cleanup Summary");
output(`Remote cleanup: ${remoteSuccess ? "✅ Success" : "❌ Failed"}`);
output(`Local cleanup: ${localSuccess ? "✅ Success" : "❌ Failed"}`);

// Exit with error code if both operations failed
if (!remoteSuccess && !localSuccess) {
console.error("\n❌ Both cleanup operations failed!");
outputError("❌ Both cleanup operations failed!");
process.exit(1);
} else if (!remoteSuccess || !localSuccess) {
// Partial success
console.log("\n⚠️ Cleanup completed with some errors.");
outputWarning("Cleanup completed with some errors.");
process.exit(0);
} else {
console.log("\n✅ All cleanup operations completed successfully!");
outputSuccess("All cleanup operations completed successfully!");
}
},
command: "all [--dry-run] [--force] [repo]",
Expand All @@ -98,6 +111,12 @@ export const pruneAllCommand: CommandModule = {
type: "boolean",
description: "Skip interactive mode and delete all safe branches automatically"
})
.option("verbose", {
alias: "v",
type: "boolean",
description: "Show detailed output including progress information",
default: false
})
.positional("repo", {
type: "string",
coerce: (s: string | undefined) => {
Expand Down
16 changes: 8 additions & 8 deletions src/commands/PruneLocalBranches.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,10 +338,10 @@ describe('PruneLocalBranches', () => {
const asyncGenerator = (async function* () {})();
(mockOctokitPlus.getPullRequests as any).mockImplementation(() => asyncGenerator);

await pruneLocalBranchesCommand.handler!({ dryRun: false, _: [], $0: 'ghouls' });
await pruneLocalBranchesCommand.handler!({ dryRun: false, verbose: true, _: [], $0: 'ghouls' });

expect(consoleLogSpy).toHaveBeenCalledWith('\nNo branches are safe to delete.');
expect(consoleLogSpy).toHaveBeenCalledWith('\nSkipping unsafe branches:');
expect(consoleLogSpy).toHaveBeenCalledWith('No local branches are safe to delete.');
expect(consoleLogSpy).toHaveBeenCalledWith('\nSkipping 2 unsafe branches:');
expect(consoleLogSpy).toHaveBeenCalledWith(' - main (current branch)');
expect(consoleLogSpy).toHaveBeenCalledWith(' - develop (protected branch)');
});
Expand Down Expand Up @@ -373,8 +373,8 @@ describe('PruneLocalBranches', () => {

expect(mockedDeleteLocalBranch).toHaveBeenCalledWith('feature-1');
expect(mockedDeleteLocalBranch).toHaveBeenCalledWith('feature-2');
expect(consoleLogSpy).toHaveBeenCalledWith('Deleted: feature-1 (#1)');
expect(consoleLogSpy).toHaveBeenCalledWith('Deleted: feature-2 (#2)');
expect(consoleLogSpy).toHaveBeenCalledWith(' Deleted: feature-1 (#1)');
expect(consoleLogSpy).toHaveBeenCalledWith(' Deleted: feature-2 (#2)');
});

it('should simulate deletion in dry-run mode', async () => {
Expand All @@ -398,8 +398,8 @@ describe('PruneLocalBranches', () => {
await pruneLocalBranchesCommand.handler!({ dryRun: true, _: [], $0: 'ghouls' });

expect(mockedDeleteLocalBranch).not.toHaveBeenCalled();
expect(consoleLogSpy).toHaveBeenCalledWith('[DRY RUN] Would delete: feature-1 (#1)');
expect(consoleLogSpy).toHaveBeenCalledWith(' Would delete: 1 branch');
expect(consoleLogSpy).toHaveBeenCalledWith(' [DRY RUN] Would delete: feature-1 (#1)');
expect(consoleLogSpy).toHaveBeenCalledWith(' Would delete: 1 local branch');
});

it('should handle branches without matching PRs', async () => {
Expand All @@ -419,7 +419,7 @@ describe('PruneLocalBranches', () => {

await pruneLocalBranchesCommand.handler!({ dryRun: true, _: [], $0: 'ghouls' });

expect(consoleLogSpy).toHaveBeenCalledWith('[DRY RUN] Would delete: feature-no-pr (no PR)');
expect(consoleLogSpy).toHaveBeenCalledWith(' [DRY RUN] Would delete: feature-no-pr (no PR)');
});

it('should handle deletion errors', async () => {
Expand Down
Loading