-
Notifications
You must be signed in to change notification settings - Fork 228
feat(settings): add automated remote branch cleanup on task archive/delete #1442
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
singhvibhanshu
wants to merge
3
commits into
generalaction:main
Choose a base branch
from
singhvibhanshu:autodeleteBranches
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| import { execFile } from 'child_process'; | ||
| import { promisify } from 'util'; | ||
| import { log } from '../lib/logger'; | ||
|
|
||
| const execFileAsync = promisify(execFile); | ||
|
|
||
| /** | ||
| * Result of a remote branch deletion attempt. | ||
| */ | ||
| export interface RemoteBranchDeletionResult { | ||
| /** Whether the deletion was executed (true even if the branch was already absent). */ | ||
| success: boolean; | ||
| /** True if the branch did not exist on the remote (already deleted or never pushed). */ | ||
| alreadyAbsent: boolean; | ||
| /** True if the remote ('origin' by default) is not configured for the repo. */ | ||
| noRemote: boolean; | ||
| /** Human-readable detail message suitable for logs / UI toasts. */ | ||
| message: string; | ||
| } | ||
|
|
||
| /** Patterns that indicate the remote branch was already gone. */ | ||
| const ALREADY_ABSENT_PATTERNS = [ | ||
| /remote ref does not exist/i, | ||
| /unknown revision/i, | ||
| /error: unable to delete '[^']*': remote ref does not exist/i, | ||
| ]; | ||
|
|
||
| /** | ||
| * Check whether a given remote alias exists for the repository. | ||
| */ | ||
| async function hasRemote(projectPath: string, remote: string): Promise<boolean> { | ||
| try { | ||
| const { stdout } = await execFileAsync('git', ['remote'], { cwd: projectPath }); | ||
| return stdout | ||
| .split('\n') | ||
| .map((l) => l.trim()) | ||
| .includes(remote); | ||
| } catch { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Determine the date (ISO string) of the most recent commit on a branch. | ||
| * Returns `null` if the branch doesn't exist locally. | ||
| */ | ||
| async function getLastCommitDate(projectPath: string, branch: string): Promise<string | null> { | ||
| try { | ||
| const { stdout } = await execFileAsync('git', ['log', '-1', '--format=%aI', branch, '--'], { | ||
| cwd: projectPath, | ||
| }); | ||
| const trimmed = stdout.trim(); | ||
| return trimmed || null; | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Dedicated service for managing remote branch lifecycle operations. | ||
| * | ||
| * This service encapsulates the logic for deleting remote branches | ||
| * with robust error handling and graceful degradation for common | ||
| * failure scenarios (branch already deleted, no remote configured, | ||
| * network timeouts, etc.). | ||
| */ | ||
| export class RemoteBranchService { | ||
| /** | ||
| * Delete a remote branch. | ||
| * | ||
| * @param projectPath — Absolute path to the local git repository (or worktree root). | ||
| * @param branch — Branch name to delete on the remote. May optionally include | ||
| * the `origin/` prefix, which is stripped automatically. | ||
| * @param remote — Remote alias (defaults to `'origin'`). | ||
| * | ||
| * @returns `RemoteBranchDeletionResult` describing the outcome. The method | ||
| * **never throws** — all errors are caught and returned as a failed result. | ||
| */ | ||
| async deleteRemoteBranch( | ||
| projectPath: string, | ||
| branch: string, | ||
| remote = 'origin' | ||
| ): Promise<RemoteBranchDeletionResult> { | ||
| // ------------------------------------------------------------------- | ||
| // Guard: no remote configured | ||
| // ------------------------------------------------------------------- | ||
| try { | ||
| const remoteExists = await hasRemote(projectPath, remote); | ||
| if (!remoteExists) { | ||
| const msg = `Skipping remote branch deletion — no remote "${remote}" configured.`; | ||
| log.info(msg); | ||
| return { success: true, alreadyAbsent: false, noRemote: true, message: msg }; | ||
| } | ||
| } catch (err) { | ||
| const msg = `Could not verify remote "${remote}" existence: ${String(err)}`; | ||
| log.warn(msg); | ||
| return { success: false, alreadyAbsent: false, noRemote: false, message: msg }; | ||
| } | ||
|
|
||
| // Normalise: remove leading "origin/" if present | ||
| let remoteBranch = branch; | ||
| const prefixPattern = new RegExp(`^${remote}/`); | ||
| if (prefixPattern.test(remoteBranch)) { | ||
| remoteBranch = remoteBranch.replace(prefixPattern, ''); | ||
| } | ||
|
|
||
| if (!remoteBranch) { | ||
| const msg = 'Cannot delete remote branch — empty branch name.'; | ||
| log.warn(msg); | ||
| return { success: false, alreadyAbsent: false, noRemote: false, message: msg }; | ||
| } | ||
|
|
||
| // ------------------------------------------------------------------- | ||
| // Execute: git push <remote> --delete <branch> | ||
| // ------------------------------------------------------------------- | ||
| try { | ||
| await execFileAsync('git', ['push', remote, '--delete', remoteBranch], { | ||
| cwd: projectPath, | ||
| timeout: 30_000, // 30 s network timeout | ||
| }); | ||
| const msg = `Deleted remote branch ${remote}/${remoteBranch}.`; | ||
| log.info(msg); | ||
| return { success: true, alreadyAbsent: false, noRemote: false, message: msg }; | ||
| } catch (error: unknown) { | ||
| const stderr = extractStderr(error); | ||
|
|
||
| // Known benign errors: branch was already absent | ||
| if (ALREADY_ABSENT_PATTERNS.some((pattern) => pattern.test(stderr))) { | ||
| const msg = `Remote branch ${remote}/${remoteBranch} already absent.`; | ||
| log.info(msg); | ||
| return { success: true, alreadyAbsent: true, noRemote: false, message: msg }; | ||
| } | ||
|
|
||
| // Unknown / network error — log, but don't throw | ||
| const msg = `Failed to delete remote branch ${remote}/${remoteBranch}: ${stderr}`; | ||
| log.warn(msg); | ||
| return { success: false, alreadyAbsent: false, noRemote: false, message: msg }; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Determine whether a branch qualifies as "stale" based on the configured | ||
| * days threshold and the date of its most recent commit. | ||
| * | ||
| * @returns `true` if the branch's last commit is older than `daysThreshold` | ||
| * days, or if the last commit date cannot be determined (conservative). | ||
| */ | ||
| async isBranchStale( | ||
| projectPath: string, | ||
| branch: string, | ||
| daysThreshold: number | ||
| ): Promise<boolean> { | ||
| const dateStr = await getLastCommitDate(projectPath, branch); | ||
| if (!dateStr) { | ||
| // Cannot determine — fail closed (skip deletion) to prevent | ||
| // accidental removal of live branches we can't verify. | ||
| return false; | ||
| } | ||
|
|
||
| const commitDate = new Date(dateStr); | ||
| if (isNaN(commitDate.getTime())) { | ||
| return false; | ||
| } | ||
|
|
||
| const now = new Date(); | ||
| const diffMs = now.getTime() - commitDate.getTime(); | ||
| const diffDays = diffMs / (1000 * 60 * 60 * 24); | ||
| return diffDays >= daysThreshold; | ||
| } | ||
|
|
||
| /** | ||
| * Evaluate the cleanup setting to decide whether a remote branch should be | ||
| * deleted right now. This does **not** perform the deletion — call | ||
| * `deleteRemoteBranch()` separately if the answer is `'delete'`. | ||
| * | ||
| * @returns `'delete'` | `'skip'` | `'ask'` | ||
| */ | ||
| async evaluateCleanupAction( | ||
| projectPath: string, | ||
| branch: string, | ||
| mode: import('@shared/remoteBranchCleanup').RemoteBranchCleanupMode, | ||
| daysThreshold: number | ||
| ): Promise<'delete' | 'skip' | 'ask'> { | ||
| switch (mode) { | ||
| case 'always': | ||
| return 'delete'; | ||
| case 'never': | ||
| return 'skip'; | ||
| case 'ask': | ||
| return 'ask'; | ||
| case 'auto': { | ||
| const stale = await this.isBranchStale(projectPath, branch, daysThreshold); | ||
| return stale ? 'delete' : 'skip'; | ||
| } | ||
| default: | ||
| return 'skip'; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** Extract the stderr string from a child-process error. */ | ||
| function extractStderr(error: unknown): string { | ||
| if (error && typeof error === 'object') { | ||
| const e = error as Record<string, unknown>; | ||
| if (typeof e.stderr === 'string' && e.stderr) return e.stderr; | ||
| if (typeof e.message === 'string' && e.message) return e.message; | ||
| } | ||
| return String(error); | ||
| } | ||
|
|
||
| /** Module-level singleton, following the project convention. */ | ||
| export const remoteBranchService = new RemoteBranchService(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Overly broad
not foundpattern can mask network errorsThe pattern
/not found/iis too generic. Git error messages for network failures (e.g.,Could not resolve hostname 'github.com': Name or service not found,SSL_connect: Connection not found) also contain "not found". When this pattern matches a transient network error, the code returns{ success: true, alreadyAbsent: true }— silently reporting success and masking what was actually a failed deletion.Consider tightening the pattern to specifically match git branch-not-found output:
The fourth pattern (
error: unable to delete '...') is already a precise superset of the first for the branch-absent case; andunknown revisioncovers the remaining scenario, so dropping the broad/not found/iloses no real coverage while eliminating false positives.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Implemented!