Fix git push through terminal

Fixes https://gitlab.com/soapbox-pub/act2/-/issues/10
This commit is contained in:
Alex Gleason committed 2025-09-15 23:14:51 -05:00
1 parent 373f25db76
commit 015a6c8536
2 files changed
+211 -9

No files matched your search

+185
View File
@@ -0,0 +1,185 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { GitPushCommand } from './push';
import type { Git } from '../../git';
import type { JSRuntimeFS } from '../../JSRuntime';
// Mock filesystem
const createMockFS = (): JSRuntimeFS => ({
readFile: vi.fn().mockResolvedValue('mock content'),
writeFile: vi.fn().mockResolvedValue(undefined),
readdir: vi.fn().mockResolvedValue([]),
mkdir: vi.fn().mockResolvedValue(undefined),
stat: vi.fn().mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now(),
}),
lstat: vi.fn().mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
size: 0,
mtimeMs: Date.now(),
}),
unlink: vi.fn().mockResolvedValue(undefined),
rmdir: vi.fn().mockResolvedValue(undefined),
rename: vi.fn().mockResolvedValue(undefined),
readlink: vi.fn().mockResolvedValue('mock link'),
symlink: vi.fn().mockResolvedValue(undefined),
});
describe('GitPushCommand', () => {
let pushCommand: GitPushCommand;
let mockGit: Git;
let mockFS: JSRuntimeFS;
const testPwd = '/test';
beforeEach(() => {
mockFS = createMockFS();
mockGit = {
currentBranch: vi.fn().mockResolvedValue('main'),
listRemotes: vi.fn().mockResolvedValue([
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
]),
push: vi.fn().mockResolvedValue(undefined),
} as any;
pushCommand = new GitPushCommand({
git: mockGit,
fs: mockFS,
pwd: testPwd,
});
});
it('should have correct command properties', () => {
expect(pushCommand.name).toBe('push');
expect(pushCommand.description).toBe('Update remote refs along with associated objects');
expect(pushCommand.usage).toBe('git push [<remote>] [<branch>]');
});
describe('argument parsing', () => {
it('should parse "origin main" correctly', () => {
// Access the private parseArgs method for testing
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs(['origin', 'main']);
expect(result).toEqual({
remote: 'origin',
branch: 'main',
options: { force: false, setUpstream: false }
});
});
it('should use default remote "origin" when no arguments provided', () => {
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs([]);
expect(result).toEqual({
remote: 'origin',
branch: undefined,
options: { force: false, setUpstream: false }
});
});
it('should parse remote only', () => {
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs(['upstream']);
expect(result).toEqual({
remote: 'upstream',
branch: undefined,
options: { force: false, setUpstream: false }
});
});
it('should parse remote and branch', () => {
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs(['upstream', 'feature-branch']);
expect(result).toEqual({
remote: 'upstream',
branch: 'feature-branch',
options: { force: false, setUpstream: false }
});
});
it('should parse force flag', () => {
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs(['--force', 'origin', 'main']);
expect(result).toEqual({
remote: 'origin',
branch: 'main',
options: { force: true, setUpstream: false }
});
});
it('should parse set-upstream flag', () => {
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs(['-u', 'origin', 'main']);
expect(result).toEqual({
remote: 'origin',
branch: 'main',
options: { force: false, setUpstream: true }
});
});
it('should handle mixed flags and arguments', () => {
const parseArgs = (pushCommand as any).parseArgs.bind(pushCommand);
const result = parseArgs(['--force', 'upstream', '--set-upstream', 'feature']);
expect(result).toEqual({
remote: 'upstream',
branch: 'feature',
options: { force: true, setUpstream: true }
});
});
});
describe('execution', () => {
it('should fail when not in a git repository', async () => {
// Mock stat to throw error (no .git directory)
mockFS.stat = vi.fn().mockRejectedValue(new Error('ENOENT'));
const result = await pushCommand.execute(['origin', 'main']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('fatal: not a git repository');
});
it('should fail when remote does not exist', async () => {
// Mock listRemotes to return empty array
mockGit.listRemotes = vi.fn().mockResolvedValue([]);
const result = await pushCommand.execute(['nonexistent', 'main']);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
});
it('should use current branch when no branch specified', async () => {
mockGit.currentBranch = vi.fn().mockResolvedValue('feature-branch');
const result = await pushCommand.execute(['origin']);
expect(mockGit.push).toHaveBeenCalledWith({
dir: testPwd,
remote: 'origin',
ref: 'feature-branch',
remoteRef: 'feature-branch',
});
});
it('should use specified branch', async () => {
const result = await pushCommand.execute(['origin', 'main']);
expect(mockGit.push).toHaveBeenCalledWith({
dir: testPwd,
remote: 'origin',
ref: 'main',
remoteRef: 'main',
});
});
});
});
+26 -9
View File
@@ -3,6 +3,8 @@ import type { ShellCommandResult } from "../ShellCommand";
import { createSuccessResult, createErrorResult } from "../ShellCommand";
import type { GitSubcommand, GitSubcommandOptions } from "../git";
import type { Git } from "../../git";
import { findCredentialsForRepo } from "@/lib/gitCredentials";
import { readGitSettings } from "@/lib/configUtils";
export class GitPushCommand implements GitSubcommand {
name = 'push';
@@ -35,7 +37,7 @@ export class GitPushCommand implements GitSubcommand {
if (!targetBranch) {
try {
targetBranch = await this.git.currentBranch({
dir: this.pwd,
}) || undefined;
if (!targetBranch) {
@@ -50,7 +52,6 @@ export class GitPushCommand implements GitSubcommand {
let remoteUrl: string;
try {
const remotes = await this.git.listRemotes({
dir: this.pwd,
});
@@ -63,12 +64,24 @@ export class GitPushCommand implements GitSubcommand {
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
}
const settings = await readGitSettings(this.fs);
const currentCredentials = findCredentialsForRepo(remoteUrl, settings.credentials);
// Prepare authentication if credentials are available
const authOptions = currentCredentials ? {
onAuth: () => ({
username: currentCredentials.username,
password: currentCredentials.password,
}),
} : {};
try {
await this.git.push({
dir: this.pwd,
remote: remote,
ref: targetBranch,
remoteRef: targetBranch,
...authOptions,
});
return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`);
@@ -100,7 +113,9 @@ export class GitPushCommand implements GitSubcommand {
const options = { force: false, setUpstream: false };
let remote = 'origin'; // Default remote
let branch: string | undefined;
const positionalArgs: string[] = [];
// First, collect all non-option arguments
for (let i = 0; i < args.length; i++) {
const arg = args[i];
@@ -109,16 +124,18 @@ export class GitPushCommand implements GitSubcommand {
} else if (arg === '--set-upstream' || arg === '-u') {
options.setUpstream = true;
} else if (!arg.startsWith('-')) {
if (remote === 'origin' && !branch) {
// First non-option argument is remote
remote = arg;
} else if (!branch) {
// Second non-option argument is branch
branch = arg;
}
positionalArgs.push(arg);
}
}
// Parse positional arguments: [remote] [branch]
if (positionalArgs.length >= 1) {
remote = positionalArgs[0];
}
if (positionalArgs.length >= 2) {
branch = positionalArgs[1];
}
return { remote, branch, options };
}
}