Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions src/git/github-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ class LockfileRegenerationError extends Error {
}
}

class GitBranchUpdateError extends Error {}

/**
* `git -c` arguments that make git authenticate as `token` against `serverUrl`.
*
Expand Down Expand Up @@ -285,6 +287,10 @@ export class GitHubProvider implements GitProvider {
return
}

// The API fallback cannot retain the Git lease or regenerated lockfiles.
if (gitError instanceof GitBranchUpdateError)
throw gitError

this.logger.warn(`⚠️ Git CLI commit failed, falling back to GitHub API: ${gitError}`)
await this.commitChangesWithAPI(branchName, message, files, baseBranch)
}
Expand Down Expand Up @@ -355,6 +361,17 @@ export class GitHubProvider implements GitProvider {
// Fetch latest changes
await this.runCommand('git', ['fetch', 'origin'])

const targetRef = `refs/heads/${branchName}`
const pushToken = this.workflowToken || undefined
// A main-only checkout may have no remote-tracking ref for the bot branch.
// Observe the remote before preparing files and use that exact lease.
const advertised = (await this.runCommand('git', ['ls-remote', '--refs', 'origin', targetRef], pushToken).catch((error: unknown) => {
throw new GitBranchUpdateError(`Could not read the Git lease for ${targetRef}. ${formatError(error)}`)
})).trim()
const [expected = '', remoteRef] = advertised.split(/\s+/)
if (advertised && (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(expected) || remoteRef !== targetRef))
throw new GitBranchUpdateError(`Invalid Git lease for ${targetRef}`)

// Renovate-style branch recreation: reset the PR branch to the base branch tip,
// then apply dependency file changes fresh on top. This completely eliminates
// merge conflicts because there's nothing to merge — we start from a clean base
Expand Down Expand Up @@ -490,8 +507,12 @@ export class GitHubProvider implements GitProvider {
// files: GitHub runs no workflows for a push made with GITHUB_TOKEN, so
// a branch buddy refreshed with it never had its CI re-run and kept
// the old result, or none at all.
const pushToken = this.workflowToken || undefined
await this.runCommand('git', ['push', 'origin', branchName, '--force-with-lease'], pushToken)
try {
await this.runCommand('git', ['push', 'origin', `${branchName}:${targetRef}`, `--force-with-lease=${targetRef}:${expected}`], pushToken)
}
catch (error) {
throw new GitBranchUpdateError(`Could not update ${targetRef}. ${formatError(error)}`)
}

this.logger.info(`✅ Successfully recreated ${branchName} with fresh changes from ${baseBranch}: ${message}`)
}
Expand Down
94 changes: 94 additions & 0 deletions test/github-refresh-lease.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { expect, test } from 'bun:test'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import process from 'node:process'
import { GitHubProvider } from '../src/git/github-provider'

function git(cwd: string, ...args: string[]): string {
const child = Bun.spawnSync({ cmd: ['git', ...args], cwd, stderr: 'pipe', stdout: 'pipe' })
if (!child.success)
throw new Error(child.stderr.toString())
return child.stdout.toString().trim()
}

const branch = 'buddy/update-dependencies'
const branchRef = 'refs/heads/' + branch
const before = {
'dependencies.json': '{"name":"fixture","version":"1.0.0"}',
'bun.lock': '{"version":"1.0.0"}',
'pantry.lock': '{"version":"1.0.0"}',
}
const competing = {
...before,
'bun.lock': '{"version":"1.1.0"}',
'pantry.lock': '{"version":"1.1.0"}',
}
const files = [
{ path: 'dependencies.json', content: '{"name":"fixture","version":"2.0.0"}', type: 'update' },
{ path: 'bun.lock', content: '{"version":"2.0.0"}', type: 'update' },
{ path: 'pantry.lock', content: '{"version":"2.0.0"}', type: 'update' },
] as const

for (const competingUpdate of [false, true]) {
const scenario = competingUpdate ? 'a competing branch write preserves remote files' : 'a main-only clone refreshes both lockfiles'
test(scenario, async () => {
const previousDirectory = process.cwd()
const root = mkdtempSync(join(tmpdir(), 'buddy-refresh-lease-'))
const remote = join(root, 'remote.git')
const writer = join(root, 'writer')
const checkout = join(root, 'checkout')
try {
git(root, 'init', '--bare', remote)
mkdirSync(writer)
git(writer, 'init', '-b', 'main')
git(writer, 'config', 'user.name', 'Fixture')
git(writer, 'config', 'user.email', 'test@example.test')
for (const [path, content] of Object.entries(before))
writeFileSync(join(writer, path), content)
git(writer, 'add', '.')
git(writer, 'commit', '-m', 'Base')
git(writer, 'remote', 'add', 'origin', remote)
git(writer, 'push', 'origin', 'main')
git(writer, 'switch', '-c', branch)
git(writer, 'commit', '--allow-empty', '-m', 'Earlier dependency update')
git(writer, 'push', 'origin', branch)
for (const [path, content] of Object.entries(competing))
writeFileSync(join(writer, path), content)
git(writer, 'add', '.')
git(writer, 'commit', '-m', 'Competing dependency update')
const competingTip = git(writer, 'rev-parse', 'HEAD')
git(root, 'clone', '--single-branch', '--branch', 'main', remote, checkout)
expect(git(checkout, 'for-each-ref', '--format=%(objectname)', 'refs/remotes/origin/' + branch)).toBe('')

process.chdir(checkout)
const provider = new GitHubProvider('fixture-token', 'example', 'fixture', true)
let fallback = false
Object.assign(provider, { commitChangesWithAPI: async () => { fallback = true } })
const runCommand = provider.runCommand.bind(provider)
provider.runCommand = async (command, args, token) => {
if (competingUpdate && command === 'git' && args[0] === 'push')
git(writer, 'push', 'origin', branch)
return runCommand(command, args, token)
}

const refresh = provider.commitChanges(branch, 'Refresh dependency files', [...files])
if (competingUpdate) {
await expect(refresh).rejects.toThrow('Could not update ' + branchRef)
expect(git(remote, 'rev-parse', branchRef)).toBe(competingTip)
for (const [path, content] of Object.entries(competing))
expect(git(remote, 'show', branchRef + ':' + path)).toBe(content)
}
else {
await refresh
for (const file of files)
expect(git(remote, 'show', branchRef + ':' + file.path)).toBe(file.content)
}
expect(fallback).toBeFalse()
}
finally {
process.chdir(previousDirectory)
rmSync(root, { recursive: true, force: true })
}
})
}
2 changes: 1 addition & 1 deletion test/noop-commit-behavior.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ describe('No-op commit prevention', () => {
await prov.commitChanges('buddy/test-branch', 'test message', filesChanged)

const hasCommit = commands.some(c => c.args[0] === 'commit' && c.args[1] === '-m')
const hasPush = commands.some(c => c.args[0] === 'push' && c.args.includes('--force-with-lease'))
const hasPush = commands.some(c => c.args[0] === 'push' && c.args.includes('--force-with-lease=refs/heads/buddy/test-branch:'))
expect(hasCommit).toBeTrue()
expect(hasPush).toBeTrue()
})
Expand Down