lock-files.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/env bun
  2. /**
  3. * Lock files transform - handles lock file conflicts by accepting ours and regenerating
  4. *
  5. * Lock files (bun.lock, package-lock.json, yarn.lock, Cargo.lock, etc.) should not be
  6. * manually merged. Instead, we accept our version to resolve the conflict, then regenerate
  7. * the lock file fresh after the merge is complete.
  8. */
  9. import { $ } from "bun"
  10. import { info, success, warn, debug } from "../utils/logger"
  11. import { defaultConfig } from "../utils/config"
  12. import { checkoutOurs, stageFiles, getConflictedFiles } from "../utils/git"
  13. export interface LockFileResult {
  14. file: string
  15. action: "resolved" | "skipped" | "regenerated" | "failed"
  16. dryRun: boolean
  17. }
  18. export interface LockFileOptions {
  19. dryRun?: boolean
  20. verbose?: boolean
  21. patterns?: string[]
  22. }
  23. /**
  24. * Check if a file is a lock file based on patterns
  25. */
  26. export function isLockFile(path: string, patterns?: string[]): boolean {
  27. const lockPatterns = patterns || defaultConfig.lockFiles
  28. return lockPatterns.some((pattern) => {
  29. // Exact match
  30. if (path === pattern) return true
  31. // Glob pattern with **
  32. if (pattern.includes("**")) {
  33. const regex = new RegExp("^" + pattern.replace(/\*\*/g, ".*").replace(/\./g, "\\.") + "$")
  34. return regex.test(path)
  35. }
  36. // Simple glob pattern
  37. if (pattern.includes("*")) {
  38. const regex = new RegExp("^" + pattern.replace(/\./g, "\\.").replace(/\*/g, "[^/]*") + "$")
  39. return regex.test(path)
  40. }
  41. // Basename match (e.g., "bun.lock" matches "packages/foo/bun.lock")
  42. const basename = path.split("/").pop()
  43. return basename === pattern
  44. })
  45. }
  46. /**
  47. * Resolve lock file conflicts by accepting our version
  48. */
  49. export async function resolveLockFileConflicts(options: LockFileOptions = {}): Promise<LockFileResult[]> {
  50. const results: LockFileResult[] = []
  51. const patterns = options.patterns || defaultConfig.lockFiles
  52. const conflicted = await getConflictedFiles()
  53. if (conflicted.length === 0) {
  54. debug("No conflicted files found")
  55. return results
  56. }
  57. const lockFiles = conflicted.filter((file) => isLockFile(file, patterns))
  58. if (lockFiles.length === 0) {
  59. debug("No lock file conflicts found")
  60. return results
  61. }
  62. info(`Found ${lockFiles.length} conflicted lock file(s)`)
  63. for (const file of lockFiles) {
  64. if (options.dryRun) {
  65. info(`[DRY-RUN] Would resolve conflict (accept ours): ${file}`)
  66. results.push({ file, action: "resolved", dryRun: true })
  67. continue
  68. }
  69. try {
  70. await checkoutOurs([file])
  71. await stageFiles([file])
  72. success(`Resolved lock file conflict (accepted ours): ${file}`)
  73. results.push({ file, action: "resolved", dryRun: false })
  74. } catch (err) {
  75. warn(`Failed to resolve lock file conflict: ${file} - ${err}`)
  76. results.push({ file, action: "failed", dryRun: false })
  77. }
  78. }
  79. return results
  80. }
  81. /**
  82. * Regenerate lock files after merge
  83. */
  84. export async function regenerateLockFiles(options: LockFileOptions = {}): Promise<LockFileResult[]> {
  85. const results: LockFileResult[] = []
  86. // Check if bun.lock exists or was part of the merge
  87. const hasBunLock = await Bun.file("bun.lock").exists()
  88. if (hasBunLock) {
  89. if (options.dryRun) {
  90. info("[DRY-RUN] Would regenerate bun.lock via 'bun install'")
  91. results.push({ file: "bun.lock", action: "regenerated", dryRun: true })
  92. } else {
  93. info("Regenerating bun.lock...")
  94. const result = await $`bun install`.quiet().nothrow()
  95. if (result.exitCode === 0) {
  96. success("Regenerated bun.lock")
  97. results.push({ file: "bun.lock", action: "regenerated", dryRun: false })
  98. } else {
  99. warn(`Failed to regenerate bun.lock: ${result.stderr.toString()}`)
  100. results.push({ file: "bun.lock", action: "failed", dryRun: false })
  101. }
  102. }
  103. }
  104. // Check for Cargo.lock in Tauri package
  105. const cargoLockPath = "packages/desktop/src-tauri/Cargo.lock"
  106. const hasCargoLock = await Bun.file(cargoLockPath).exists()
  107. if (hasCargoLock) {
  108. if (options.dryRun) {
  109. info("[DRY-RUN] Would regenerate Cargo.lock via 'cargo generate-lockfile'")
  110. results.push({ file: cargoLockPath, action: "regenerated", dryRun: true })
  111. } else {
  112. info("Regenerating Cargo.lock...")
  113. const result = await $`cargo generate-lockfile`.cwd("packages/desktop/src-tauri").quiet().nothrow()
  114. if (result.exitCode === 0) {
  115. success("Regenerated Cargo.lock")
  116. results.push({ file: cargoLockPath, action: "regenerated", dryRun: false })
  117. } else {
  118. // Cargo might not be installed, just warn
  119. warn(`Could not regenerate Cargo.lock (cargo may not be installed): ${result.stderr.toString()}`)
  120. results.push({ file: cargoLockPath, action: "skipped", dryRun: false })
  121. }
  122. }
  123. }
  124. // Note about nix/hashes.json - regenerated by CI, not locally
  125. const nixHashesPath = "nix/hashes.json"
  126. const hasNixHashes = await Bun.file(nixHashesPath).exists()
  127. if (hasNixHashes) {
  128. info("Note: nix/hashes.json will be regenerated by CI (update-nix-hashes.yml) after PR is created")
  129. results.push({ file: nixHashesPath, action: "skipped", dryRun: options.dryRun ?? false })
  130. }
  131. return results
  132. }
  133. // CLI entry point
  134. if (import.meta.main) {
  135. const args = process.argv.slice(2)
  136. const dryRun = args.includes("--dry-run")
  137. const verbose = args.includes("--verbose")
  138. const regenerate = args.includes("--regenerate")
  139. if (dryRun) {
  140. info("Running in dry-run mode (no files will be modified)")
  141. }
  142. if (regenerate) {
  143. const results = await regenerateLockFiles({ dryRun, verbose })
  144. const regenerated = results.filter((r) => r.action === "regenerated")
  145. console.log()
  146. success(`Regenerated ${regenerated.length} lock file(s)`)
  147. } else {
  148. const results = await resolveLockFileConflicts({ dryRun, verbose })
  149. const resolved = results.filter((r) => r.action === "resolved")
  150. console.log()
  151. success(`Resolved ${resolved.length} lock file conflict(s)`)
  152. }
  153. if (dryRun) {
  154. info("Run without --dry-run to apply changes")
  155. }
  156. }