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

171 lines
5.9 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";
export class GitPullCommand implements GitSubcommand {
name = 'pull';
description = 'Fetch from and integrate with another repository or a local branch';
usage = 'git pull [<remote>] [<branch>]';
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, branch } = this.parseArgs(args);
// Get current branch if not specified
let targetBranch = branch;
let currentBranch: string | null = null;
try {
currentBranch = await this.git.currentBranch({
dir: cwd,
}) || null;
if (!targetBranch) {
targetBranch = currentBranch || 'main';
}
} catch {
if (!targetBranch) {
targetBranch = 'main';
}
}
// 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`);
}
// Check for uncommitted changes (modified or staged).
// Untracked files are allowed (real git only blocks if they'd be overwritten).
const statusMatrix = await this.git.statusMatrix({
dir: cwd,
});
const modifiedFiles = statusMatrix
.filter(([, headStatus, workdirStatus, stageStatus]) => {
// Skip untracked files (not in HEAD, not in stage)
if (headStatus === 0 && stageStatus === 0) return false;
// Report if stage or workdir differs from HEAD
return headStatus !== workdirStatus || headStatus !== stageStatus;
})
.map(([filepath]) => filepath);
if (modifiedFiles.length > 0) {
const fileList = modifiedFiles.map(file => `\t${file}`).join('\n');
return createErrorResult(`error: Your local changes to the following files would be overwritten by merge:\n${fileList}\nPlease commit your changes or stash them before you merge.`);
}
try {
// Fetch from remote
await this.git.fetch({
dir: cwd,
remote: remote,
ref: targetBranch,
});
// Get the remote ref
const remoteRef = `refs/remotes/${remote}/${targetBranch}`;
let remoteOid: string;
try {
remoteOid = await this.git.resolveRef({
dir: cwd,
ref: remoteRef,
});
} catch {
return createErrorResult(`fatal: couldn't find remote ref ${targetBranch}`);
}
// Get current HEAD
let currentOid: string;
try {
currentOid = await this.git.resolveRef({
dir: cwd,
ref: 'HEAD',
});
} catch {
// Empty repository, just checkout the remote branch
await this.git.checkout({
dir: cwd,
ref: targetBranch,
});
return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`);
}
// Check if already up to date
if (currentOid === remoteOid) {
return createSuccessResult('Already up to date.\n');
}
// Perform fast-forward merge (simplified)
await this.git.merge({
dir: cwd,
ours: currentBranch || 'HEAD',
theirs: remoteRef,
fastForwardOnly: true,
});
return createSuccessResult(`From ${remoteUrl}\n ${currentOid.substring(0, 7)}..${remoteOid.substring(0, 7)} ${targetBranch} -> ${remote}/${targetBranch}\nUpdating ${currentOid.substring(0, 7)}..${remoteOid.substring(0, 7)}\nFast-forward\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('network')) {
return createErrorResult('fatal: unable to access remote repository. Please check your network connection.');
} else if (error.message.includes('merge conflict')) {
return createErrorResult('error: Merge conflict detected. Please resolve conflicts manually.');
} else if (error.message.includes('fast-forward')) {
return createErrorResult('fatal: Not possible to fast-forward, aborting.');
}
}
return createErrorResult(`Failed to pull: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
} catch (error) {
return createErrorResult(`git pull: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
private parseArgs(args: string[]): { remote: string; branch?: string } {
let remote = 'origin'; // Default remote
let branch: string | undefined;
const nonOptionArgs = args.filter(arg => !arg.startsWith('-'));
if (nonOptionArgs.length >= 1) {
remote = nonOptionArgs[0];
}
if (nonOptionArgs.length >= 2) {
branch = nonOptionArgs[1];
}
return { remote, branch };
}
}