Files
shakespeare/src/lib/commands/git/branch.ts
T
Alex Gleason b3fddf6cb3 Audit and overhaul virtual shell's git command
Fix critical bugs, add extensive missing flags, and add 8 new subcommands
to bring the browser-side git command closer to parity with real git.

Critical bug fixes:
- git commit: file-count classification used impossible stageStatus=1
  comparisons, always reporting 0 files changed
- git status --porcelain: untracked files could clobber staged indicators
- git add: directory walker skipped all dotfiles (including .gitignore
  itself), ignoring real git's .gitignore-based filtering
- git pull: untracked files incorrectly blocked pulls
- git reset: target regex rejected valid refs like branch names
- git diff: path filter used substring matching; --cached read working
  directory instead of index; <commit> and <commit>..<commit> forms were
  stubbed/unimplemented; used fake JS hashes instead of git.hashBlob

Implemented git reset --soft (was returning "not implemented").

New flags added across existing subcommands:
- commit: --signoff, --no-verify, -F/--file, --author, -C/--reuse-message,
  multiple -m support
- add: -u/--update, -f/--force, -n/--dry-run, absolute paths inside repo
- log: --stat, -p/--patch, --name-only, --name-status, --author, --grep,
  --since, --until, --no-merges, --reverse, --follow, custom
  --pretty=format:, proper timezone in output
- push: -u/--set-upstream (now wired to config), --tags, --delete,
  --dry-run, refspec (local:remote)
- fetch: --all, --tags, --prune now actually passed through
- branch: -a/--all, -r/--remotes, -m/-M (rename), --show-current, -v
- checkout: -B, -f/--force, commit-hash support (detached HEAD)
- config: --unset, --get-all, --add, --local, proper --list that reads
  the whole config file
- tag: real annotated tags via git.annotatedTag, -m, -f, -n, glob patterns
- clone: -b/--branch, -o/--origin, --bare
- init: -b/--initial-branch
- show: --stat, --name-only, --name-status
- diff: --stat, --name-only, --name-status
- remote: set-url, get-url, rename, show subcommands

New subcommands:
- git rm: remove files from index (and optionally worktree)
- git mv: rename/move files with index updates
- git restore: modern replacement for checkout of files
- git switch: modern replacement for branch checkout
- git merge: wrapper over git.merge (including --abort, --ff-only)
- git revert: create an inverse commit
- git rev-parse: resolve refs, --short, --abbrev-ref, --show-toplevel,
  --git-dir, HEAD~N / HEAD^N
- git ls-files: list tracked/modified/deleted/untracked files

All existing tests updated where behavior intentionally changed; new
subcommands have dedicated test suites. Final suite: 1392 passing.
2026-04-27 00:42:10 -05:00

317 lines
10 KiB
TypeScript

import type { JSRuntimeFS } from "../../JSRuntime";
import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
interface BranchOptions {
force: boolean;
all: boolean;
remote: boolean;
verbose: boolean;
showCurrent: boolean;
}
type BranchAction = 'list' | 'create' | 'delete' | 'rename' | 'show-current';
export class GitBranchCommand implements GitSubcommand {
name = 'branch';
description = 'List, create, or delete branches';
usage = 'git branch [--list | -a | -r | -v | --show-current] | git branch <branchname> [<start-point>] | git branch (-d | -D) <branchname> | git branch (-m | -M) [<oldname>] <newname>';
private git: Git;
private fs: JSRuntimeFS;
constructor(options: GitSubcommandOptions) {
this.git = options.git;
this.fs = options.fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
try {
// Check if we're in a git repository
try {
await this.fs.stat(`${cwd}/.git`);
} catch {
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
}
const { action, branchName, startPoint, newName, options } = this.parseArgs(args);
switch (action) {
case 'list':
return await this.listBranches(options, cwd);
case 'show-current':
return await this.showCurrentBranch(cwd);
case 'create':
return await this.createBranch(branchName!, startPoint, cwd);
case 'delete':
return await this.deleteBranch(branchName!, options.force, cwd);
case 'rename':
return await this.renameBranch(branchName, newName!, options.force, cwd);
default:
return await this.listBranches(options, cwd);
}
} catch (error) {
return createErrorResult(`git branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): {
action: BranchAction;
branchName?: string;
startPoint?: string;
newName?: string;
options: BranchOptions;
} {
const options: BranchOptions = {
force: false,
all: false,
remote: false,
verbose: false,
showCurrent: false,
};
let action: BranchAction = 'list';
let branchName: string | undefined;
let startPoint: string | undefined;
let newName: string | undefined;
const positionals: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--list' || arg === '-l') {
action = 'list';
} else if (arg === '-a' || arg === '--all') {
options.all = true;
action = 'list';
} else if (arg === '-r' || arg === '--remotes') {
options.remote = true;
action = 'list';
} else if (arg === '-v' || arg === '--verbose') {
options.verbose = true;
} else if (arg === '--show-current') {
action = 'show-current';
} else if (arg === '-d' || arg === '--delete') {
action = 'delete';
} else if (arg === '-D') {
action = 'delete';
options.force = true;
} else if (arg === '-m' || arg === '--move') {
action = 'rename';
} else if (arg === '-M') {
action = 'rename';
options.force = true;
} else if (arg === '-f' || arg === '--force') {
options.force = true;
} else if (!arg.startsWith('-')) {
positionals.push(arg);
}
}
if (action === 'delete') {
branchName = positionals[0];
} else if (action === 'rename') {
if (positionals.length === 1) {
newName = positionals[0];
} else if (positionals.length >= 2) {
branchName = positionals[0];
newName = positionals[1];
}
} else if (positionals.length >= 1) {
action = 'create';
branchName = positionals[0];
if (positionals.length >= 2) {
startPoint = positionals[1];
}
}
return { action, branchName, startPoint, newName, options };
}
private async showCurrentBranch(cwd: string): Promise<ShellCommandResult> {
try {
const currentBranch = await this.git.currentBranch({ dir: cwd });
if (!currentBranch) {
return createSuccessResult('');
}
return createSuccessResult(`${currentBranch}\n`);
} catch {
return createSuccessResult('');
}
}
private async listBranches(options: BranchOptions, cwd: string): Promise<ShellCommandResult> {
try {
const lines: string[] = [];
// Get current branch
let currentBranch: string | null = null;
try {
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
} catch {
// Detached HEAD
}
const listLocal = !options.remote || options.all;
const listRemote = options.remote || options.all;
if (listLocal) {
const branches = await this.git.listBranches({ dir: cwd });
for (const branch of branches) {
const prefix = branch === currentBranch ? '* ' : ' ';
let line = `${prefix}${branch}`;
if (options.verbose) {
try {
const oid = await this.git.resolveRef({ dir: cwd, ref: branch });
line += ` ${oid.substring(0, 7)}`;
// Get commit message
try {
const log = await this.git.log({ dir: cwd, depth: 1, ref: branch });
if (log.length > 0) {
line += ` ${log[0].commit.message.split('\n')[0]}`;
}
} catch { /* empty */ }
} catch { /* empty */ }
}
lines.push(line);
}
}
if (listRemote) {
try {
const remotes = await this.git.listRemotes({ dir: cwd });
for (const remote of remotes) {
try {
const remoteBranches = await this.git.listBranches({ dir: cwd, remote: remote.remote });
for (const branch of remoteBranches) {
lines.push(` remotes/${remote.remote}/${branch}`);
}
} catch { /* empty */ }
}
} catch { /* empty */ }
}
if (lines.length === 0) {
return createSuccessResult('');
}
return createSuccessResult(lines.join('\n') + '\n');
} catch (error) {
return createErrorResult(`Failed to list branches: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async createBranch(branchName: string, startPoint: string | undefined, cwd: string): Promise<ShellCommandResult> {
try {
// Check if branch already exists
const branches = await this.git.listBranches({ dir: cwd });
if (branches.includes(branchName)) {
return createErrorResult(`fatal: A branch named '${branchName}' already exists.`);
}
// Get starting ref
let startOid: string;
try {
startOid = await this.git.resolveRef({
dir: cwd,
ref: startPoint || 'HEAD',
});
} catch {
return createErrorResult(`fatal: Not a valid object name: '${startPoint || 'HEAD'}'.`);
}
// Create the new branch
await this.git.branch({
dir: cwd,
ref: branchName,
object: startOid,
});
return createSuccessResult('');
} catch (error) {
return createErrorResult(`Failed to create branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise<ShellCommandResult> {
try {
// Check if branch exists
const branches = await this.git.listBranches({ dir: cwd });
if (!branches.includes(branchName)) {
return createErrorResult(`error: branch '${branchName}' not found.`);
}
// Check if it's the current branch
let currentBranch: string | null = null;
try {
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
} catch {
// Continue
}
if (currentBranch === branchName) {
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${cwd}'`);
}
// Delete the branch
await this.git.deleteBranch({
dir: cwd,
ref: branchName,
});
return createSuccessResult(`Deleted branch ${branchName}.\n`);
} catch (error) {
if (!force && error instanceof Error && error.message.includes('not fully merged')) {
return createErrorResult(`error: The branch '${branchName}' is not fully merged.\nIf you are sure you want to delete it, run 'git branch -D ${branchName}'.`);
}
return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private async renameBranch(
oldName: string | undefined,
newName: string,
force: boolean,
cwd: string
): Promise<ShellCommandResult> {
try {
// If oldName not specified, rename the current branch
let actualOldName = oldName;
if (!actualOldName) {
try {
actualOldName = await this.git.currentBranch({ dir: cwd }) || undefined;
if (!actualOldName) {
return createErrorResult('fatal: Cannot rename the current branch while not on any.');
}
} catch {
return createErrorResult('fatal: Cannot determine current branch.');
}
}
const branches = await this.git.listBranches({ dir: cwd });
if (!branches.includes(actualOldName)) {
return createErrorResult(`error: refname refs/heads/${actualOldName} not found`);
}
if (!force && branches.includes(newName)) {
return createErrorResult(`fatal: A branch named '${newName}' already exists.`);
}
await this.git.renameBranch({
dir: cwd,
ref: newName,
oldref: actualOldName,
});
return createSuccessResult('');
} catch (error) {
return createErrorResult(`Failed to rename branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}