collapse-barrel.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #!/usr/bin/env bun
  2. /**
  3. * Collapse a single-namespace barrel directory into a dir/index.ts module.
  4. *
  5. * Given a directory `src/foo/` that contains:
  6. *
  7. * - `index.ts` (exactly `export * as Foo from "./foo"`)
  8. * - `foo.ts` (the real implementation)
  9. * - zero or more sibling files
  10. *
  11. * this script:
  12. *
  13. * 1. Deletes the old `index.ts` barrel.
  14. * 2. `git mv`s `foo.ts` → `index.ts` so the implementation IS the directory entry.
  15. * 3. Appends `export * as Foo from "."` to the new `index.ts`.
  16. * 4. Rewrites any same-directory sibling `*.ts` files that imported
  17. * `./foo` (with or without the namespace name) to import `"."` instead.
  18. *
  19. * Consumer files outside the directory keep importing from the directory
  20. * (`"@/foo"` / `"../foo"` / etc.) and continue to work, because
  21. * `dir/index.ts` now provides the `Foo` named export directly.
  22. *
  23. * Usage:
  24. *
  25. * bun script/collapse-barrel.ts src/bus
  26. * bun script/collapse-barrel.ts src/bus --dry-run
  27. *
  28. * Notes:
  29. *
  30. * - Only works on directories whose barrel is a single
  31. * `export * as Name from "./file"` line. Refuses otherwise.
  32. * - Refuses if the implementation file name already conflicts with
  33. * `index.ts`.
  34. * - Safe to run repeatedly: a second run on an already-collapsed dir
  35. * will exit with a clear message.
  36. */
  37. import fs from "node:fs"
  38. import path from "node:path"
  39. import { spawnSync } from "node:child_process"
  40. const args = process.argv.slice(2)
  41. const dryRun = args.includes("--dry-run")
  42. const targetArg = args.find((a) => !a.startsWith("--"))
  43. if (!targetArg) {
  44. console.error("Usage: bun script/collapse-barrel.ts <dir> [--dry-run]")
  45. process.exit(1)
  46. }
  47. const dir = path.resolve(targetArg)
  48. const indexPath = path.join(dir, "index.ts")
  49. if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
  50. console.error(`Not a directory: ${dir}`)
  51. process.exit(1)
  52. }
  53. if (!fs.existsSync(indexPath)) {
  54. console.error(`No index.ts in ${dir}`)
  55. process.exit(1)
  56. }
  57. // Validate barrel shape.
  58. const indexContent = fs.readFileSync(indexPath, "utf-8").trim()
  59. const match = indexContent.match(/^export\s+\*\s+as\s+(\w+)\s+from\s+["']\.\/([^"']+)["']\s*;?\s*$/)
  60. if (!match) {
  61. console.error(`Not a simple single-namespace barrel:\n${indexContent}`)
  62. process.exit(1)
  63. }
  64. const namespaceName = match[1]
  65. const implRel = match[2].replace(/\.ts$/, "")
  66. const implPath = path.join(dir, `${implRel}.ts`)
  67. if (!fs.existsSync(implPath)) {
  68. console.error(`Implementation file not found: ${implPath}`)
  69. process.exit(1)
  70. }
  71. if (implRel === "index") {
  72. console.error(`Nothing to do — impl file is already index.ts`)
  73. process.exit(0)
  74. }
  75. console.log(`Collapsing ${path.relative(process.cwd(), dir)}`)
  76. console.log(` namespace: ${namespaceName}`)
  77. console.log(` impl file: ${implRel}.ts → index.ts`)
  78. // Figure out which sibling files need rewriting.
  79. const siblings = fs
  80. .readdirSync(dir)
  81. .filter((f) => f.endsWith(".ts") || f.endsWith(".tsx"))
  82. .filter((f) => f !== "index.ts" && f !== `${implRel}.ts`)
  83. .map((f) => path.join(dir, f))
  84. type SiblingEdit = { file: string; content: string }
  85. const siblingEdits: SiblingEdit[] = []
  86. for (const sibling of siblings) {
  87. const content = fs.readFileSync(sibling, "utf-8")
  88. // Match any import or re-export referring to "./<implRel>" inside this directory.
  89. const siblingRegex = new RegExp(`(from\\s*["'])\\.\\/${implRel.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&")}(["'])`, "g")
  90. if (!siblingRegex.test(content)) continue
  91. const updated = content.replace(siblingRegex, `$1.$2`)
  92. siblingEdits.push({ file: sibling, content: updated })
  93. }
  94. if (siblingEdits.length > 0) {
  95. console.log(` sibling rewrites: ${siblingEdits.length}`)
  96. for (const edit of siblingEdits) {
  97. console.log(` ${path.relative(process.cwd(), edit.file)}`)
  98. }
  99. } else {
  100. console.log(` sibling rewrites: none`)
  101. }
  102. if (dryRun) {
  103. console.log(`\n(dry run) would:`)
  104. console.log(` - delete ${path.relative(process.cwd(), indexPath)}`)
  105. console.log(` - git mv ${path.relative(process.cwd(), implPath)} ${path.relative(process.cwd(), indexPath)}`)
  106. console.log(` - append \`export * as ${namespaceName} from "."\` to the new index.ts`)
  107. for (const edit of siblingEdits) {
  108. console.log(` - rewrite sibling: ${path.relative(process.cwd(), edit.file)}`)
  109. }
  110. process.exit(0)
  111. }
  112. // Apply: remove the old barrel, git-mv the impl onto it, then rewrite content.
  113. // We can't git-mv on top of an existing tracked file, so we remove the barrel first.
  114. function runGit(...cmd: string[]) {
  115. const res = spawnSync("git", cmd, { stdio: "inherit" })
  116. if (res.status !== 0) {
  117. console.error(`git ${cmd.join(" ")} failed`)
  118. process.exit(res.status ?? 1)
  119. }
  120. }
  121. // Step 1: remove the barrel
  122. runGit("rm", "-f", indexPath)
  123. // Step 2: rename the impl file into index.ts
  124. runGit("mv", implPath, indexPath)
  125. // Step 3: append the self-reexport to the new index.ts
  126. const newContent = fs.readFileSync(indexPath, "utf-8")
  127. const trimmed = newContent.endsWith("\n") ? newContent : newContent + "\n"
  128. fs.writeFileSync(indexPath, `${trimmed}\nexport * as ${namespaceName} from "."\n`)
  129. console.log(` appended: export * as ${namespaceName} from "."`)
  130. // Step 4: rewrite siblings
  131. for (const edit of siblingEdits) {
  132. fs.writeFileSync(edit.file, edit.content)
  133. }
  134. if (siblingEdits.length > 0) {
  135. console.log(` rewrote ${siblingEdits.length} sibling file(s)`)
  136. }
  137. console.log(`\nDone. Verify with:`)
  138. console.log(` cd packages/opencode`)
  139. console.log(` bunx --bun tsgo --noEmit`)
  140. console.log(` bun run --conditions=browser ./src/index.ts generate`)
  141. console.log(` bun run test`)