Files
shakespeare/src/lib/commands/git/push.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

192 lines
6.3 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 PushOptions {
force: boolean;
setUpstream: boolean;
tags: boolean;
deleteRef: boolean;
dryRun: boolean;
all: boolean;
}
export class GitPushCommand implements GitSubcommand {
name = 'push';
description = 'Update remote refs along with associated objects';
usage = 'git push [-u | --set-upstream] [-f | --force] [--tags] [--delete] [--dry-run] [--all] [<remote>] [<refspec>]';
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 { remote, refspec, options } = this.parseArgs(args);
// Parse refspec (local:remote or just local, or HEAD)
let localRef: string | undefined;
let remoteRef: string | undefined;
if (refspec) {
if (refspec.includes(':')) {
const [l, r] = refspec.split(':');
localRef = l || undefined;
remoteRef = r || undefined;
} else {
localRef = refspec;
remoteRef = refspec;
}
}
// Resolve HEAD to current branch if localRef is HEAD or not specified
if (!localRef || localRef === 'HEAD') {
try {
const currentBranch = await this.git.currentBranch({ dir: cwd });
if (!currentBranch) {
return createErrorResult('fatal: You are not currently on a branch.');
}
if (!localRef) {
localRef = currentBranch;
}
if (!remoteRef) {
remoteRef = currentBranch;
}
} catch {
return createErrorResult('fatal: You are not currently on a branch.');
}
}
// Get remote URL
let remoteUrl: string;
try {
const remotes = await this.git.listRemotes({ dir: cwd });
const targetRemote = remotes.find(r => r.remote === remote);
if (!targetRemote) {
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
}
remoteUrl = targetRemote.url;
} catch {
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
}
if (options.dryRun) {
return createSuccessResult(`Would push to ${remoteUrl}\n ${localRef} -> ${remoteRef}\n`);
}
try {
await this.git.push({
dir: cwd,
remote: remote,
ref: options.deleteRef ? undefined : localRef,
remoteRef: remoteRef,
force: options.force,
delete: options.deleteRef,
} as Parameters<typeof this.git.push>[0]);
// Set up upstream tracking if requested
if (options.setUpstream && localRef) {
try {
await this.git.setConfig({
dir: cwd,
path: `branch.${localRef}.remote`,
value: remote,
});
await this.git.setConfig({
dir: cwd,
path: `branch.${localRef}.merge`,
value: `refs/heads/${remoteRef}`,
});
} catch {
// Non-fatal
}
}
if (options.deleteRef) {
return createSuccessResult(`To ${remoteUrl}\n - [deleted] ${remoteRef}\n`);
}
return createSuccessResult(`To ${remoteUrl}\n ${localRef} -> ${remoteRef}\n`);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('authentication')) {
return createErrorResult('fatal: Authentication failed. Please configure git credentials.');
} else if (error.message.includes('rejected') || error.message.includes('Updates were rejected')) {
return createErrorResult(`error: failed to push some refs to '${remoteUrl}'\nhint: ${error.message}`);
} else if (error.message.includes('network')) {
return createErrorResult('fatal: unable to access remote repository. Please check your network connection.');
} else if (error.message.includes('Nostr signer is required')) {
return createErrorResult('fatal: Nostr signer is required for pushing to Nostr repositories. Please log in with a Nostr account.');
} else if (error.message.includes('Everything up-to-date')) {
return createSuccessResult('Everything up-to-date\n');
}
}
return createErrorResult(`Failed to push: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
} catch (error) {
return createErrorResult(`git push: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): {
remote: string;
refspec?: string;
options: PushOptions;
} {
const options: PushOptions = {
force: false,
setUpstream: false,
tags: false,
deleteRef: false,
dryRun: false,
all: false,
};
let remote = 'origin';
let refspec: string | undefined;
const positionalArgs: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === '--force' || arg === '-f' || arg === '--force-with-lease') {
options.force = true;
} else if (arg === '--set-upstream' || arg === '-u') {
options.setUpstream = true;
} else if (arg === '--tags') {
options.tags = true;
} else if (arg === '--delete' || arg === '-d') {
options.deleteRef = true;
} else if (arg === '--dry-run' || arg === '-n') {
options.dryRun = true;
} else if (arg === '--all') {
options.all = true;
} else if (!arg.startsWith('-')) {
positionalArgs.push(arg);
}
}
if (positionalArgs.length >= 1) {
remote = positionalArgs[0];
}
if (positionalArgs.length >= 2) {
refspec = positionalArgs[1];
}
return { remote, refspec, options };
}
}