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
127 changes: 65 additions & 62 deletions src/git/github-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { getGitHubApiUrl } from '../utils/endpoints'
import { formatError, GitHubApiError } from '../utils/errors'
import { assertUpdateTargetsExist, FileChangeValidationError, normalizeRepositoryPath } from '../utils/file-changes'
import { fetchWithTimeout } from '../utils/http'
import { detectRequiredPackageManagers, getAllLockFilePaths, nestedLockProjects, regenerateLockFile } from '../utils/lock-file'
import { detectRequiredPackageManagers, getAllLockFilePaths, isLockfileManifest, missingLockFiles, nestedLockProjects, regenerateLockFile } from '../utils/lock-file'
import { getDefaultLogger } from '../utils/logger'
import { isBuddyBranch } from '../utils/branches'

Expand Down Expand Up @@ -391,12 +391,14 @@ export class GitHubProvider implements GitProvider {
}
})

const updatedPaths: string[] = []
const isTestEnv = process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test'
// Apply file changes
for (const file of files) {
const cleanPath = normalizeRepositoryPath(file.path)

// Safety check: prevent writing to sensitive files during tests
if (process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test') {
if (isTestEnv) {
const sensitiveFiles = ['package.json', 'bun.lock', 'bun.lockb', 'package-lock.json', 'yarn.lock']
if (sensitiveFiles.includes(cleanPath) && file.content === '{"name":"x"}') {
this.logger.warn(`⚠️ Skipping test file write to ${cleanPath} to prevent overwriting project files`)
Expand All @@ -407,6 +409,7 @@ export class GitHubProvider implements GitProvider {
if (file.type === 'delete') {
try {
await this.runCommand('git', ['rm', cleanPath])
updatedPaths.push(cleanPath)
}
catch {
// File might not exist, that's ok for delete operations
Expand All @@ -416,69 +419,62 @@ export class GitHubProvider implements GitProvider {
// Bun.write creates parent directories automatically and is async
await Bun.write(cleanPath, file.content)
await this.runCommand('git', ['add', cleanPath])
updatedPaths.push(cleanPath)
}
}

// Regenerate lock files after manifest changes (skip in test environments).
// We HARD-FAIL if regeneration fails for any required manager: a PR with an
// updated manifest but stale lockfile is a correctness bug — consumers will
// install the wrong versions. Fail loudly so the caller can retry or
// investigate instead of silently opening a broken PR.
const isTestEnv = process.env.NODE_ENV === 'test' || process.env.BUN_ENV === 'test'
if (!isTestEnv) {
const updatedPaths = files.map(f => f.path.replace(/^\.\//, '').replace(/^\/+/, ''))
const requiredManagers = detectRequiredPackageManagers(updatedPaths)
// Real writes require matching locks even when the process uses a test environment.
const requiredManagers = detectRequiredPackageManagers(updatedPaths)

if (requiredManagers.length > 0) {
this.logger.info(`🔒 Regenerating lock files for: ${requiredManagers.join(', ')}`)
const cwd = process.cwd()
const failures: string[] = []
if (requiredManagers.length > 0) {
this.logger.info(`🔒 Regenerating lock files for: ${requiredManagers.join(', ')}`)
const cwd = process.cwd()
const failures: string[] = []

for (const manager of requiredManagers) {
try {
const result = await regenerateLockFile(manager, cwd)
if (result.success) {
// Stage any regenerated lock files
for (const lockFile of getAllLockFilePaths()) {
try {
await this.runCommand('git', ['add', lockFile])
}
catch {
// Lock file may not exist for this manager, that's fine
}
for (const manager of requiredManagers) {
try {
const result = await regenerateLockFile(manager, cwd)
if (result.success) {
// Stage any regenerated lock files
for (const lockFile of getAllLockFilePaths()) {
try {
await this.runCommand('git', ['add', lockFile])
}
catch {
// Lock file may not exist for this manager, that's fine
}
}
else {
failures.push(`${manager}: ${result.message}`)
}
}
catch (lockError) {
failures.push(`${manager}: ${lockError instanceof Error ? lockError.message : String(lockError)}`)
else {
failures.push(`${manager}: ${result.message}`)
}
}

// Projects with a lock file of their own beside a changed manifest
// are separate installs; the root install does not touch them.
for (const project of nestedLockProjects(updatedPaths, cwd)) {
try {
const result = await regenerateLockFile(project.manager, `${cwd}/${project.dir}`)
if (result.success)
await this.runCommand('git', ['add', project.lockFile])
else
failures.push(`${project.dir} (${project.manager}): ${result.message}`)
}
catch (lockError) {
failures.push(`${project.dir} (${project.manager}): ${lockError instanceof Error ? lockError.message : String(lockError)}`)
}
catch (lockError) {
failures.push(`${manager}: ${lockError instanceof Error ? lockError.message : String(lockError)}`)
}
}

if (failures.length > 0) {
const detail = failures.map(f => ` - ${f}`).join('\n')
throw new LockfileRegenerationError(
`Lock file regeneration failed; refusing to open PR with stale lockfiles.\n${detail}`,
)
// Projects with a lock file of their own beside a changed manifest
// are separate installs; the root install does not touch them.
for (const project of nestedLockProjects(updatedPaths, cwd)) {
try {
const result = await regenerateLockFile(project.manager, `${cwd}/${project.dir}`)
if (result.success)
await this.runCommand('git', ['add', project.lockFile])
else
failures.push(`${project.dir} (${project.manager}): ${result.message}`)
}
catch (lockError) {
failures.push(`${project.dir} (${project.manager}): ${lockError instanceof Error ? lockError.message : String(lockError)}`)
}
}

if (failures.length > 0) {
const detail = failures.map(f => ` - ${f}`).join('\n')
throw new LockfileRegenerationError(
`Lock file regeneration failed; refusing to open PR with stale lockfiles.\n${detail}`,
)
}
}

// Check if there are changes to commit against the current branch tip
Expand Down Expand Up @@ -542,16 +538,6 @@ export class GitHubProvider implements GitProvider {
this.logger.info(`✅ Including ${workflowFiles.length} workflow file(s) with elevated permissions`)
}

// Note: Lock files cannot be regenerated when committing via the API path
// because there is no local filesystem to run install commands against.
const hasManifestFiles = files.some(f =>
f.path.endsWith('package.json') || f.path.endsWith('composer.json'),
)
if (hasManifestFiles) {
this.logger.warn(`⚠️ Committing manifest files via API — lock files will not be updated.`)
this.logger.warn(` Lock file regeneration requires the Git CLI commit path (local filesystem).`)
}

// Renovate-style: base the new commit on the base branch (e.g. main), not the PR branch.
// This recreates the branch from scratch, eliminating any merge conflicts.
this.logger.info(`🔄 Recreating ${branchName} from ${baseBranch} via API (Renovate-style)...`)
Expand All @@ -565,7 +551,7 @@ export class GitHubProvider implements GitProvider {
await assertUpdateTargetsExist(files, async (cleanPath) => {
const encodedPath = cleanPath.split('/').map(segment => encodeURIComponent(segment)).join('/')
try {
await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodedPath}?ref=${encodeURIComponent(baseBranch)}`)
await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/contents/${encodedPath}?ref=${encodeURIComponent(baseSha)}`)
return true
}
catch (error: any) {
Expand All @@ -575,6 +561,23 @@ export class GitHubProvider implements GitProvider {
}
})

// The API cannot run the package managers. Check the exact base tree so
// a failed Git commit cannot discard the regenerated files on fallback.
const changedPaths = files
.filter(file => file.type !== 'delete' || isLockfileManifest(normalizeRepositoryPath(file.path)))
.map(file => normalizeRepositoryPath(file.path))
if (changedPaths.some(isLockfileManifest)) {
const baseTree: { truncated: boolean, tree: { path: string, type: string }[] }
= await this.apiRequest(`GET /repos/${this.owner}/${this.repo}/git/trees/${baseTreeSha}?recursive=1`)
if (baseTree.truncated || !Array.isArray(baseTree.tree))
throw new LockfileRegenerationError('The base tree is incomplete; use Git to verify and regenerate its lockfiles before publishing.')

const tracked = new Set(baseTree.tree.filter(entry => entry.type === 'blob').map(entry => entry.path))
const missing = missingLockFiles(changedPaths, '.', path => tracked.has(normalizeRepositoryPath(path)))
if (missing.length > 0)
throw new LockfileRegenerationError(`Refusing to publish dependency manifests without updated lockfiles: ${missing.join(', ')}. Use Git to regenerate them and retry.`)
}

// Create new tree with file changes
const tree = []
for (const file of files) {
Expand Down
56 changes: 25 additions & 31 deletions src/utils/lock-file.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { spawn } from 'node:child_process'
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import process from 'node:process'
import { detectPackageManager } from './helpers'
import { getDefaultLogger } from './logger'

export type PackageManagerType = 'bun' | 'npm' | 'yarn' | 'pnpm' | 'composer' | 'pantry'
Expand Down Expand Up @@ -149,6 +149,14 @@ export async function regenerateLockFile(
* Pantry's own manifests. A change to one of these only reaches `pantry.lock`.
*/
const PANTRY_MANIFESTS = new Set(['deps.yaml', 'deps.yml', 'pantry.jsonc', 'pantry.json', 'pantry.toml'])
const JS_PACKAGE_MANAGERS = ['bun', 'pnpm', 'yarn', 'npm'] as const
type FileExists = (path: string) => boolean

/** Whether changing this manifest can invalidate a dependency lockfile. */
export function isLockfileManifest(path: string): boolean {
const name = path.split('/').at(-1) ?? ''
return name === 'package.json' || name === 'composer.json' || PANTRY_MANIFESTS.has(name)
}

/**
* Examine which manifest files were updated to determine which package managers
Expand All @@ -163,7 +171,7 @@ const PANTRY_MANIFESTS = new Set(['deps.yaml', 'deps.yml', 'pantry.jsonc', 'pant
* @param updatedFilePaths - List of file paths that were updated
* @param cwd - Project root whose lock files decide the managers
*/
export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: string = process.cwd()): PackageManagerType[] {
export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: string = process.cwd(), exists: FileExists = existsSync): PackageManagerType[] {
const managers: Set<PackageManagerType> = new Set()
let pantryInputChanged = false

Expand All @@ -172,7 +180,7 @@ export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: s

if (fileName === 'package.json') {
// Detect the JS package manager from lock files on disk
managers.add(detectPackageManager(cwd))
managers.add(JS_PACKAGE_MANAGERS.find(manager => lockFileFor(manager, cwd, exists)) ?? 'bun')
pantryInputChanged = true
}

Expand All @@ -184,7 +192,7 @@ export function detectRequiredPackageManagers(updatedFilePaths: string[], cwd: s
pantryInputChanged = true
}

if (pantryInputChanged && hasLockFile('pantry', cwd))
if (pantryInputChanged && lockFileFor('pantry', cwd, exists))
managers.add('pantry')

return Array.from(managers)
Expand Down Expand Up @@ -212,7 +220,7 @@ export interface NestedLockProject {
* @param updatedFilePaths - Paths a change touches, relative to the root
* @param cwd - Repository root
*/
export function nestedLockProjects(updatedFilePaths: string[], cwd: string = process.cwd()): NestedLockProject[] {
export function nestedLockProjects(updatedFilePaths: string[], cwd: string = process.cwd(), exists: FileExists = existsSync): NestedLockProject[] {
const projects = new Map<string, NestedLockProject>()
for (const filePath of updatedFilePaths) {
const clean = filePath.replace(/^\.\//, '')
Expand All @@ -221,11 +229,11 @@ export function nestedLockProjects(updatedFilePaths: string[], cwd: string = pro
const dir = clean.slice(0, clean.lastIndexOf('/'))
if (projects.has(dir))
continue
const absolute = `${cwd}/${dir}`
const manager = (['bun', 'pnpm', 'yarn', 'npm'] as const).find(candidate => hasLockFile(candidate, absolute))
const absolute = join(cwd, dir)
const manager = JS_PACKAGE_MANAGERS.find(candidate => lockFileFor(candidate, absolute, exists))
if (!manager)
continue
const lockFile = lockFileFor(manager, absolute)
const lockFile = lockFileFor(manager, absolute, exists)
if (lockFile)
projects.set(dir, { dir, manager, lockFile: `${dir}/${lockFile}` })
}
Expand All @@ -235,7 +243,7 @@ export function nestedLockProjects(updatedFilePaths: string[], cwd: string = pro
/**
* The lock file a manager writes in this project, or null when it has none.
*/
export function lockFileFor(packageManager: PackageManagerType, cwd: string): string | null {
export function lockFileFor(packageManager: PackageManagerType, cwd: string, exists: FileExists = existsSync): string | null {
const candidates: Record<PackageManagerType, string[]> = {
bun: ['bun.lock', 'bun.lockb'],
npm: ['package-lock.json'],
Expand All @@ -244,7 +252,7 @@ export function lockFileFor(packageManager: PackageManagerType, cwd: string): st
composer: ['composer.lock'],
pantry: ['pantry.lock'],
}
return candidates[packageManager].find(name => existsSync(`${cwd}/${name}`)) ?? null
return candidates[packageManager].find(name => exists(join(cwd, name))) ?? null
}

/**
Expand All @@ -258,14 +266,15 @@ export function lockFileFor(packageManager: PackageManagerType, cwd: string): st
* @param changedPaths - Paths the pull request changes
* @param cwd - Project root whose lock files decide what is expected
*/
export function missingLockFiles(changedPaths: string[], cwd: string = process.cwd()): string[] {
export function missingLockFiles(changedPaths: string[], cwd: string = process.cwd(), exists: FileExists = existsSync): string[] {
const changed = new Set(changedPaths.map(path => path.replace(/^\.\//, '')))
const nestedDirs = new Set(nestedLockProjects(changedPaths, cwd).map(project => project.dir))
const nested = nestedLockProjects(changedPaths, cwd, exists)
const nestedDirs = new Set(nested.map(project => project.dir))
// A manifest inside a nested project needs only that project's lock file.
const rootPaths = changedPaths.filter(path => !nestedDirs.has(path.replace(/^\.\//, '').replace(/\/package\.json$/, '')))
const rootLocks = detectRequiredPackageManagers(rootPaths, cwd)
.map(manager => lockFileFor(manager, cwd))
const nestedLocks = nestedLockProjects(changedPaths, cwd).map(project => project.lockFile)
const rootLocks = detectRequiredPackageManagers(rootPaths, cwd, exists)
.map(manager => lockFileFor(manager, cwd, exists))
const nestedLocks = nested.map(project => project.lockFile)
return [...rootLocks, ...nestedLocks]
.filter((lockFile): lockFile is string => lockFile !== null && !changed.has(lockFile))
}
Expand All @@ -274,20 +283,5 @@ export function missingLockFiles(changedPaths: string[], cwd: string = process.c
* Check if a lock file exists for a given package manager in the working directory
*/
export function hasLockFile(packageManager: PackageManagerType, cwd: string): boolean {
const path = require('node:path')

switch (packageManager) {
case 'bun':
return existsSync(path.join(cwd, 'bun.lock')) || existsSync(path.join(cwd, 'bun.lockb'))
case 'npm':
return existsSync(path.join(cwd, 'package-lock.json'))
case 'yarn':
return existsSync(path.join(cwd, 'yarn.lock'))
case 'pnpm':
return existsSync(path.join(cwd, 'pnpm-lock.yaml'))
case 'composer':
return existsSync(path.join(cwd, 'composer.lock'))
case 'pantry':
return existsSync(path.join(cwd, 'pantry.lock'))
}
return lockFileFor(packageManager, cwd) !== null
}
Loading