mirror of
https://github.com/AutoMaker-Org/automaker.git
synced 2026-03-17 10:03:08 +00:00
* fix(copilot): correct tool.execution_complete event handling The CopilotProvider was using incorrect event type and data structure for tool execution completion events from the @github/copilot-sdk, causing tool call outputs to be empty. Changes: - Update event type from 'tool.execution_end' to 'tool.execution_complete' - Fix data structure to use nested result.content instead of flat result - Fix error structure to use error.message instead of flat error - Add success field to match SDK event structure - Add tests for empty and missing result handling This aligns with the official @github/copilot-sdk v0.1.16 types defined in session-events.d.ts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * test(copilot): add edge case test for error with code field Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor(copilot): improve error handling and code quality Code review improvements: - Extract magic string '[ERROR]' to TOOL_ERROR_PREFIX constant - Add null-safe error handling with direct error variable assignment - Include error codes in error messages for better debugging - Add JSDoc documentation for tool.execution_complete handler - Update tests to verify error codes are displayed - Add missing tool_use_id assertion in error test These changes improve: - Code maintainability (no magic strings) - Debugging experience (error codes now visible) - Type safety (explicit null checks) - Test coverage (verify error code formatting) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Changes from fix/bug-fixes-1-0 * test(copilot): add edge case test for error with code field Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Changes from fix/bug-fixes-1-0 * fix: Handle detached HEAD state in worktree discovery and recovery * fix: Remove unused isDevServerStarting prop and md: breakpoint classes * fix: Add missing dependency and sanitize persisted cache data * feat: Ensure NODE_ENV is set to test in vitest configs * feat: Configure Playwright to run only E2E tests * fix: Improve PR tracking and dev server lifecycle management * feat: Add settings-based defaults for planning mode, model config, and custom providers. Fixes #816 * feat: Add worktree and branch selector to graph view * fix: Add timeout and error handling for worktree HEAD ref resolution * fix: use absolute icon path and place icon outside asar on Linux The hicolor icon theme index only lists sizes up to 512x512, so an icon installed only at 1024x1024 is invisible to GNOME/KDE's theme resolver, causing both the app launcher and taskbar to show a generic icon. Additionally, BrowserWindow.icon cannot be read by the window manager when the file is inside app.asar. - extraResources: copy logo_larger.png to resources/ (outside asar) so it lands at /opt/Automaker/resources/logo_larger.png on install - linux.desktop.Icon: set to the absolute resources path, bypassing the hicolor theme lookup and its size constraints entirely - icon-manager.ts: on Linux production use process.resourcesPath so BrowserWindow receives a real filesystem path the WM can read directly Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: use linux.desktop.entry for custom desktop Icon field electron-builder v26 rejects arbitrary keys in linux.desktop — the correct schema wraps custom .desktop overrides inside desktop.entry. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: set desktop name on Linux so taskbar uses the correct app icon Without app.setDesktopName(), the window manager cannot associate the running Electron process with automaker.desktop. GNOME/KDE fall back to _NET_WM_ICON which defaults to Electron's own bundled icon. Calling app.setDesktopName('automaker.desktop') before any window is created sets the _GTK_APPLICATION_ID hint and XDG app_id so the WM picks up the desktop entry's Icon for the taskbar. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix: memory and context views mobile friendly (#818) * Changes from fix/memory-and-context-mobile-friendly * fix: Improve file extension detection and add path traversal protection * refactor: Extract file extension utilities and add path traversal guards Code review improvements: - Extract isMarkdownFilename and isImageFilename to shared image-utils.ts - Remove duplicated code from context-view.tsx and memory-view.tsx - Add path traversal guard for context fixture utilities (matching memory) - Add 7 new tests for context fixture path traversal protection - Total 61 tests pass Addresses code review feedback from PR #813 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * test: Add e2e tests for profiles crud and board background persistence * Update apps/ui/playwright.config.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix: Add robust test navigation handling and file filtering * fix: Format NODE_OPTIONS configuration on single line * test: Update profiles and board background persistence tests * test: Replace iPhone 13 Pro with Pixel 5 for mobile test consistency * Update apps/ui/src/components/views/context-view.tsx Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * chore: Remove test project directory * feat: Filter context files by type and improve mobile menu visibility --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix: Improve test reliability and localhost handling * chore: Use explicit TEST_USE_EXTERNAL_BACKEND env var for server cleanup * feat: Add E2E/CI mock mode for provider factory and auth verification * feat: Add remoteBranch parameter to pull and rebase operations * chore: Enhance E2E testing setup with worker isolation and auth state management - Updated .gitignore to include worker-specific test fixtures. - Modified e2e-tests.yml to implement test sharding for improved CI performance. - Refactored global setup to authenticate once and save session state for reuse across tests. - Introduced worker-isolated fixture paths to prevent conflicts during parallel test execution. - Improved test navigation and loading handling for better reliability. - Updated various test files to utilize new auth state management and fixture paths. * fix: Update Playwright configuration and improve test reliability - Increased the number of workers in Playwright configuration for better parallelism in CI environments. - Enhanced the board background persistence test to ensure dropdown stability by waiting for the list to populate before interaction, improving test reliability. * chore: Simplify E2E test configuration and enhance mock implementations - Updated e2e-tests.yml to run tests in a single shard for streamlined CI execution. - Enhanced unit tests for worktree list handling by introducing a mock for execGitCommand, improving test reliability and coverage. - Refactored setup functions to better manage command mocks for git operations in tests. - Improved error handling in mkdirSafe function to account for undefined stats in certain environments. * refactor: Improve test configurations and enhance error handling - Updated Playwright configuration to clear VITE_SERVER_URL, ensuring the frontend uses the Vite proxy and preventing cookie domain mismatches. - Enhanced MergeRebaseDialog logic to normalize selectedBranch for better handling of various ref formats. - Improved global setup with a more robust backend health check, throwing an error if the backend is not healthy after retries. - Refactored project creation tests to handle file existence checks more reliably. - Added error handling for missing E2E source fixtures to guide setup process. - Enhanced memory navigation to handle sandbox dialog visibility more effectively. * refactor: Enhance Git command execution and improve test configurations - Updated Git command execution to merge environment paths correctly, ensuring proper command execution context. - Refactored the Git initialization process to handle errors more gracefully and ensure user configuration is set before creating the initial commit. - Improved test configurations by updating Playwright test identifiers for better clarity and consistency across different project states. - Enhanced cleanup functions in tests to handle directory removal more robustly, preventing errors during test execution. * fix: Resolve React hooks errors from duplicate instances in dependency tree * style: Format alias configuration for improved readability --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: DhanushSantosh <dhanushsantoshs05@gmail.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
547 lines
18 KiB
TypeScript
547 lines
18 KiB
TypeScript
/**
|
|
* PullService - Pull git operations without HTTP
|
|
*
|
|
* Encapsulates the full git pull workflow including:
|
|
* - Branch name and detached HEAD detection
|
|
* - Fetching from remote
|
|
* - Status parsing and local change detection
|
|
* - Stash push/pop logic
|
|
* - Upstream verification (rev-parse / --verify)
|
|
* - Pull execution and conflict detection
|
|
* - Conflict file list collection
|
|
*
|
|
* Extracted from the worktree pull route to improve organization
|
|
* and testability. Follows the same pattern as rebase-service.ts
|
|
* and cherry-pick-service.ts.
|
|
*/
|
|
|
|
import { createLogger, getErrorMessage } from '@automaker/utils';
|
|
import { execGitCommand, getConflictFiles } from '@automaker/git-utils';
|
|
import { execGitCommandWithLockRetry, getCurrentBranch } from '../lib/git.js';
|
|
|
|
const logger = createLogger('PullService');
|
|
|
|
// ============================================================================
|
|
// Types
|
|
// ============================================================================
|
|
|
|
export interface PullOptions {
|
|
/** Remote name to pull from (defaults to 'origin') */
|
|
remote?: string;
|
|
/** Specific remote branch to pull (e.g. 'main'). When provided, overrides the tracking branch and fetches this branch from the remote. */
|
|
remoteBranch?: string;
|
|
/** When true, automatically stash local changes before pulling and reapply after */
|
|
stashIfNeeded?: boolean;
|
|
}
|
|
|
|
export interface PullResult {
|
|
success: boolean;
|
|
error?: string;
|
|
branch?: string;
|
|
pulled?: boolean;
|
|
hasLocalChanges?: boolean;
|
|
localChangedFiles?: string[];
|
|
stashed?: boolean;
|
|
stashRestored?: boolean;
|
|
stashRecoveryFailed?: boolean;
|
|
hasConflicts?: boolean;
|
|
conflictSource?: 'pull' | 'stash';
|
|
conflictFiles?: string[];
|
|
message?: string;
|
|
/** Whether the pull resulted in a merge commit (not fast-forward) */
|
|
isMerge?: boolean;
|
|
/** Whether the pull was a fast-forward (no merge commit needed) */
|
|
isFastForward?: boolean;
|
|
/** Files affected by the merge (only present when isMerge is true) */
|
|
mergeAffectedFiles?: string[];
|
|
}
|
|
|
|
// ============================================================================
|
|
// Helper Functions
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Fetch the latest refs from a remote.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @param remote - Remote name (e.g. 'origin')
|
|
*/
|
|
export async function fetchRemote(worktreePath: string, remote: string): Promise<void> {
|
|
await execGitCommand(['fetch', remote], worktreePath);
|
|
}
|
|
|
|
/**
|
|
* Parse `git status --porcelain` output into a list of changed file paths.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @returns Object with hasLocalChanges flag and list of changed file paths
|
|
*/
|
|
export async function getLocalChanges(
|
|
worktreePath: string
|
|
): Promise<{ hasLocalChanges: boolean; localChangedFiles: string[] }> {
|
|
const statusOutput = await execGitCommand(['status', '--porcelain'], worktreePath);
|
|
const hasLocalChanges = statusOutput.trim().length > 0;
|
|
|
|
let localChangedFiles: string[] = [];
|
|
if (hasLocalChanges) {
|
|
localChangedFiles = statusOutput
|
|
.trim()
|
|
.split('\n')
|
|
.filter((line) => line.trim().length > 0)
|
|
.map((line) => {
|
|
const entry = line.substring(3).trim();
|
|
const arrowIndex = entry.indexOf(' -> ');
|
|
return arrowIndex !== -1 ? entry.substring(arrowIndex + 4).trim() : entry;
|
|
});
|
|
}
|
|
|
|
return { hasLocalChanges, localChangedFiles };
|
|
}
|
|
|
|
/**
|
|
* Stash local changes with a descriptive message.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @param branchName - Current branch name (used in stash message)
|
|
* @returns Promise<void> — resolves on success, throws on failure
|
|
*/
|
|
export async function stashChanges(worktreePath: string, branchName: string): Promise<void> {
|
|
const stashMessage = `automaker-pull-stash: Pre-pull stash on ${branchName}`;
|
|
await execGitCommandWithLockRetry(
|
|
['stash', 'push', '--include-untracked', '-m', stashMessage],
|
|
worktreePath
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Pop the top stash entry.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @returns The stdout from stash pop
|
|
*/
|
|
export async function popStash(worktreePath: string): Promise<string> {
|
|
return await execGitCommandWithLockRetry(['stash', 'pop'], worktreePath);
|
|
}
|
|
|
|
/**
|
|
* Try to pop the stash, returning whether the pop succeeded.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @returns true if stash pop succeeded, false if it failed
|
|
*/
|
|
async function tryPopStash(worktreePath: string): Promise<boolean> {
|
|
try {
|
|
await execGitCommandWithLockRetry(['stash', 'pop'], worktreePath);
|
|
return true;
|
|
} catch (stashPopError) {
|
|
// Stash pop failed - leave it in stash list for manual recovery
|
|
logger.error('Failed to reapply stash during error recovery', {
|
|
worktreePath,
|
|
error: getErrorMessage(stashPopError),
|
|
});
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Result of the upstream/remote branch check.
|
|
* - 'tracking': the branch has a configured upstream tracking ref
|
|
* - 'remote': no tracking ref, but the remote branch exists
|
|
* - 'none': neither a tracking ref nor a remote branch was found
|
|
*/
|
|
export type UpstreamStatus = 'tracking' | 'remote' | 'none';
|
|
|
|
/**
|
|
* Check whether the branch has an upstream tracking ref, or whether
|
|
* the remote branch exists.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @param branchName - Current branch name
|
|
* @param remote - Remote name
|
|
* @returns UpstreamStatus indicating tracking ref, remote branch, or neither
|
|
*/
|
|
export async function hasUpstreamOrRemoteBranch(
|
|
worktreePath: string,
|
|
branchName: string,
|
|
remote: string
|
|
): Promise<UpstreamStatus> {
|
|
try {
|
|
await execGitCommand(['rev-parse', '--abbrev-ref', `${branchName}@{upstream}`], worktreePath);
|
|
return 'tracking';
|
|
} catch {
|
|
// No upstream tracking - check if the remote branch exists
|
|
try {
|
|
await execGitCommand(['rev-parse', '--verify', `${remote}/${branchName}`], worktreePath);
|
|
return 'remote';
|
|
} catch {
|
|
return 'none';
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check whether an error output string indicates a merge conflict.
|
|
*/
|
|
function isConflictError(errorOutput: string): boolean {
|
|
return errorOutput.includes('CONFLICT') || errorOutput.includes('Automatic merge failed');
|
|
}
|
|
|
|
/**
|
|
* Determine whether the current HEAD commit is a merge commit by checking
|
|
* whether it has two or more parent hashes.
|
|
*
|
|
* Runs `git show -s --pretty=%P HEAD` which prints the parent SHAs separated
|
|
* by spaces. A merge commit has at least two parents; a regular commit has one.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @returns true if HEAD is a merge commit, false otherwise
|
|
*/
|
|
async function isMergeCommit(worktreePath: string): Promise<boolean> {
|
|
try {
|
|
const output = await execGitCommand(['show', '-s', '--pretty=%P', 'HEAD'], worktreePath);
|
|
// Each parent SHA is separated by a space; two or more means it's a merge
|
|
const parents = output
|
|
.trim()
|
|
.split(/\s+/)
|
|
.filter((p) => p.length > 0);
|
|
return parents.length >= 2;
|
|
} catch {
|
|
// If the check fails for any reason, assume it is not a merge commit
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check whether an output string indicates a stash conflict.
|
|
*/
|
|
function isStashConflict(output: string): boolean {
|
|
return output.includes('CONFLICT') || output.includes('Merge conflict');
|
|
}
|
|
|
|
// ============================================================================
|
|
// Main Service Function
|
|
// ============================================================================
|
|
|
|
/**
|
|
* Perform a full git pull workflow on the given worktree.
|
|
*
|
|
* The workflow:
|
|
* 1. Get current branch name (detect detached HEAD)
|
|
* 2. Fetch from remote
|
|
* 3. Check for local changes
|
|
* 4. If local changes and stashIfNeeded, stash them
|
|
* 5. Verify upstream tracking or remote branch exists
|
|
* 6. Execute `git pull`
|
|
* 7. If stash was created and pull succeeded, reapply stash
|
|
* 8. Detect and report conflicts from pull or stash reapplication
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @param options - Pull options (remote, stashIfNeeded)
|
|
* @returns PullResult with detailed status information
|
|
*/
|
|
export async function performPull(
|
|
worktreePath: string,
|
|
options?: PullOptions
|
|
): Promise<PullResult> {
|
|
const targetRemote = options?.remote || 'origin';
|
|
const stashIfNeeded = options?.stashIfNeeded ?? false;
|
|
const targetRemoteBranch = options?.remoteBranch;
|
|
|
|
// 1. Get current branch name
|
|
let branchName: string;
|
|
try {
|
|
branchName = await getCurrentBranch(worktreePath);
|
|
} catch (err) {
|
|
return {
|
|
success: false,
|
|
error: `Failed to get current branch: ${getErrorMessage(err)}`,
|
|
};
|
|
}
|
|
|
|
// 2. Check for detached HEAD state
|
|
if (branchName === 'HEAD') {
|
|
return {
|
|
success: false,
|
|
error: 'Cannot pull in detached HEAD state. Please checkout a branch first.',
|
|
};
|
|
}
|
|
|
|
// 3. Fetch latest from remote
|
|
try {
|
|
await fetchRemote(worktreePath, targetRemote);
|
|
} catch (fetchError) {
|
|
return {
|
|
success: false,
|
|
error: `Failed to fetch from remote '${targetRemote}': ${getErrorMessage(fetchError)}`,
|
|
};
|
|
}
|
|
|
|
// 4. Check for local changes
|
|
let hasLocalChanges: boolean;
|
|
let localChangedFiles: string[];
|
|
try {
|
|
({ hasLocalChanges, localChangedFiles } = await getLocalChanges(worktreePath));
|
|
} catch (err) {
|
|
return {
|
|
success: false,
|
|
error: `Failed to get local changes: ${getErrorMessage(err)}`,
|
|
};
|
|
}
|
|
|
|
// 5. If there are local changes and stashIfNeeded is not requested, return info
|
|
if (hasLocalChanges && !stashIfNeeded) {
|
|
return {
|
|
success: true,
|
|
branch: branchName,
|
|
pulled: false,
|
|
hasLocalChanges: true,
|
|
localChangedFiles,
|
|
message:
|
|
'Local changes detected. Use stashIfNeeded to automatically stash and reapply changes.',
|
|
};
|
|
}
|
|
|
|
// 6. Stash local changes if needed
|
|
let didStash = false;
|
|
if (hasLocalChanges && stashIfNeeded) {
|
|
try {
|
|
await stashChanges(worktreePath, branchName);
|
|
didStash = true;
|
|
} catch (stashError) {
|
|
return {
|
|
success: false,
|
|
error: `Failed to stash local changes: ${getErrorMessage(stashError)}`,
|
|
};
|
|
}
|
|
}
|
|
|
|
// 7. Verify upstream tracking or remote branch exists
|
|
// Skip this check when a specific remote branch is provided - we always use
|
|
// explicit 'git pull <remote> <branch>' args in that case.
|
|
let upstreamStatus: UpstreamStatus = 'tracking';
|
|
if (!targetRemoteBranch) {
|
|
upstreamStatus = await hasUpstreamOrRemoteBranch(worktreePath, branchName, targetRemote);
|
|
if (upstreamStatus === 'none') {
|
|
let stashRecoveryFailed = false;
|
|
if (didStash) {
|
|
const stashPopped = await tryPopStash(worktreePath);
|
|
stashRecoveryFailed = !stashPopped;
|
|
}
|
|
return {
|
|
success: false,
|
|
error: `Branch '${branchName}' has no upstream branch on remote '${targetRemote}'. Push it first or set upstream with: git branch --set-upstream-to=${targetRemote}/${branchName}${stashRecoveryFailed ? ' Local changes remain stashed and need manual recovery (run: git stash pop).' : ''}`,
|
|
stashRecoveryFailed: stashRecoveryFailed ? stashRecoveryFailed : undefined,
|
|
};
|
|
}
|
|
}
|
|
|
|
// 8. Pull latest changes
|
|
// When a specific remote branch is requested, always use explicit remote + branch args.
|
|
// When the branch has a configured upstream tracking ref, let Git use it automatically.
|
|
// When only the remote branch exists (no tracking ref), explicitly specify remote and branch.
|
|
const pullArgs = targetRemoteBranch
|
|
? ['pull', targetRemote, targetRemoteBranch]
|
|
: upstreamStatus === 'tracking'
|
|
? ['pull']
|
|
: ['pull', targetRemote, branchName];
|
|
let pullConflict = false;
|
|
let pullConflictFiles: string[] = [];
|
|
|
|
// Declare merge detection variables before the try block so they are accessible
|
|
// in the stash reapplication path even when didStash is true.
|
|
let isMerge = false;
|
|
let isFastForward = false;
|
|
let mergeAffectedFiles: string[] = [];
|
|
|
|
try {
|
|
const pullOutput = await execGitCommand(pullArgs, worktreePath);
|
|
|
|
const alreadyUpToDate = pullOutput.includes('Already up to date');
|
|
// Detect fast-forward from git pull output
|
|
isFastForward = pullOutput.includes('Fast-forward') || pullOutput.includes('fast-forward');
|
|
// Detect merge by checking whether the new HEAD has two parents (more reliable
|
|
// than string-matching localised pull output which may not contain 'Merge').
|
|
isMerge = !alreadyUpToDate && !isFastForward ? await isMergeCommit(worktreePath) : false;
|
|
|
|
// If it was a real merge (not fast-forward), get the affected files
|
|
if (isMerge) {
|
|
try {
|
|
// Get files changed in the merge commit
|
|
const diffOutput = await execGitCommand(
|
|
['diff', '--name-only', 'HEAD~1', 'HEAD'],
|
|
worktreePath
|
|
);
|
|
mergeAffectedFiles = diffOutput
|
|
.trim()
|
|
.split('\n')
|
|
.filter((f: string) => f.trim().length > 0);
|
|
} catch {
|
|
// Ignore errors - this is best-effort
|
|
}
|
|
}
|
|
|
|
// If no stash to reapply, return success
|
|
if (!didStash) {
|
|
return {
|
|
success: true,
|
|
branch: branchName,
|
|
pulled: !alreadyUpToDate,
|
|
hasLocalChanges: false,
|
|
stashed: false,
|
|
stashRestored: false,
|
|
message: alreadyUpToDate ? 'Already up to date' : 'Pulled latest changes',
|
|
...(isMerge ? { isMerge: true, mergeAffectedFiles } : {}),
|
|
...(isFastForward ? { isFastForward: true } : {}),
|
|
};
|
|
}
|
|
} catch (pullError: unknown) {
|
|
const err = pullError as { stderr?: string; stdout?: string; message?: string };
|
|
const errorOutput = `${err.stderr || ''} ${err.stdout || ''} ${err.message || ''}`;
|
|
|
|
if (isConflictError(errorOutput)) {
|
|
pullConflict = true;
|
|
try {
|
|
pullConflictFiles = await getConflictFiles(worktreePath);
|
|
} catch {
|
|
pullConflictFiles = [];
|
|
}
|
|
} else {
|
|
// Non-conflict pull error
|
|
let stashRecoveryFailed = false;
|
|
if (didStash) {
|
|
const stashPopped = await tryPopStash(worktreePath);
|
|
stashRecoveryFailed = !stashPopped;
|
|
}
|
|
|
|
// Check for common errors
|
|
const errorMsg = err.stderr || err.message || 'Pull failed';
|
|
if (errorMsg.includes('no tracking information')) {
|
|
return {
|
|
success: false,
|
|
error: `Branch '${branchName}' has no upstream branch. Push it first or set upstream with: git branch --set-upstream-to=${targetRemote}/${branchName}${stashRecoveryFailed ? ' Local changes remain stashed and need manual recovery (run: git stash pop).' : ''}`,
|
|
stashRecoveryFailed: stashRecoveryFailed ? stashRecoveryFailed : undefined,
|
|
};
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
error: `${errorMsg}${stashRecoveryFailed ? ' Local changes remain stashed and need manual recovery (run: git stash pop).' : ''}`,
|
|
stashRecoveryFailed: stashRecoveryFailed ? stashRecoveryFailed : undefined,
|
|
};
|
|
}
|
|
}
|
|
|
|
// 9. If pull had conflicts, return conflict info (don't try stash pop)
|
|
if (pullConflict) {
|
|
return {
|
|
success: false,
|
|
branch: branchName,
|
|
pulled: true,
|
|
hasConflicts: true,
|
|
conflictSource: 'pull',
|
|
conflictFiles: pullConflictFiles,
|
|
stashed: didStash,
|
|
stashRestored: false,
|
|
message:
|
|
`Pull resulted in merge conflicts. ${didStash ? 'Your local changes are still stashed.' : ''}`.trim(),
|
|
};
|
|
}
|
|
|
|
// 10. Pull succeeded, now try to reapply stash
|
|
if (didStash) {
|
|
return await reapplyStash(worktreePath, branchName, {
|
|
isMerge,
|
|
isFastForward,
|
|
mergeAffectedFiles,
|
|
});
|
|
}
|
|
|
|
// Shouldn't reach here, but return a safe default
|
|
return {
|
|
success: true,
|
|
branch: branchName,
|
|
pulled: true,
|
|
message: 'Pulled latest changes',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Attempt to reapply stashed changes after a successful pull.
|
|
* Handles both clean reapplication and conflict scenarios.
|
|
*
|
|
* @param worktreePath - Path to the git worktree
|
|
* @param branchName - Current branch name
|
|
* @param mergeInfo - Merge/fast-forward detection info from the pull step
|
|
* @returns PullResult reflecting stash reapplication status
|
|
*/
|
|
async function reapplyStash(
|
|
worktreePath: string,
|
|
branchName: string,
|
|
mergeInfo: { isMerge: boolean; isFastForward: boolean; mergeAffectedFiles: string[] }
|
|
): Promise<PullResult> {
|
|
const mergeFields: Partial<PullResult> = {
|
|
...(mergeInfo.isMerge
|
|
? { isMerge: true, mergeAffectedFiles: mergeInfo.mergeAffectedFiles }
|
|
: {}),
|
|
...(mergeInfo.isFastForward ? { isFastForward: true } : {}),
|
|
};
|
|
|
|
try {
|
|
await popStash(worktreePath);
|
|
|
|
// Stash pop succeeded cleanly (popStash throws on non-zero exit)
|
|
return {
|
|
success: true,
|
|
branch: branchName,
|
|
pulled: true,
|
|
hasConflicts: false,
|
|
stashed: true,
|
|
stashRestored: true,
|
|
...mergeFields,
|
|
message: 'Pulled latest changes and restored your stashed changes.',
|
|
};
|
|
} catch (stashPopError: unknown) {
|
|
const err = stashPopError as { stderr?: string; stdout?: string; message?: string };
|
|
const errorOutput = `${err.stderr || ''} ${err.stdout || ''} ${err.message || ''}`;
|
|
|
|
// Check if stash pop failed due to conflicts
|
|
// The stash remains in the stash list when conflicts occur, so stashRestored is false
|
|
if (isStashConflict(errorOutput)) {
|
|
let stashConflictFiles: string[] = [];
|
|
try {
|
|
stashConflictFiles = await getConflictFiles(worktreePath);
|
|
} catch {
|
|
stashConflictFiles = [];
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
branch: branchName,
|
|
pulled: true,
|
|
hasConflicts: true,
|
|
conflictSource: 'stash',
|
|
conflictFiles: stashConflictFiles,
|
|
stashed: true,
|
|
stashRestored: false,
|
|
...mergeFields,
|
|
message: 'Pull succeeded but reapplying your stashed changes resulted in merge conflicts.',
|
|
};
|
|
}
|
|
|
|
// Non-conflict stash pop error - stash is still in the stash list
|
|
logger.warn('Failed to reapply stash after pull', { worktreePath, error: errorOutput });
|
|
|
|
return {
|
|
success: true,
|
|
branch: branchName,
|
|
pulled: true,
|
|
hasConflicts: false,
|
|
stashed: true,
|
|
stashRestored: false,
|
|
...mergeFields,
|
|
message:
|
|
'Pull succeeded but failed to reapply stashed changes. Your changes are still in the stash list.',
|
|
};
|
|
}
|
|
}
|