clean.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import { lstat, readdir, rm } from 'node:fs/promises'
  2. import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
  3. import { fileURLToPath } from 'node:url'
  4. import ts from 'typescript'
  5. const knownOrphanEntries = new Set(['node_modules', 'lib', '.typecheck'])
  6. const configHost: ts.ParseConfigFileHost = {
  7. useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
  8. readDirectory: (...args) => ts.sys.readDirectory(...args),
  9. fileExists: fileName => ts.sys.fileExists(fileName),
  10. readFile: fileName => ts.sys.readFile(fileName),
  11. getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
  12. onUnRecoverableConfigFileDiagnostic(diagnostic) {
  13. throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'))
  14. },
  15. }
  16. function isMissing(error: unknown): boolean {
  17. return error instanceof Error && 'code' in error && error.code === 'ENOENT'
  18. }
  19. async function exists(path: string): Promise<boolean> {
  20. try {
  21. await lstat(path)
  22. return true
  23. } catch (error) {
  24. if (isMissing(error)) return false
  25. throw error
  26. }
  27. }
  28. async function childDirectories(path: string): Promise<string[]> {
  29. try {
  30. const entries = await readdir(path, { withFileTypes: true })
  31. return entries.filter(entry => entry.isDirectory()).map(entry => join(path, entry.name))
  32. } catch (error) {
  33. if (isMissing(error)) return []
  34. throw error
  35. }
  36. }
  37. function repositoryPath(root: string, path: string): string {
  38. return relative(root, path).split(sep).join('/')
  39. }
  40. function parseConfig(configPath: string): ts.ParsedCommandLine {
  41. const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
  42. if (!parsed) throw new Error(`clean: cannot parse TypeScript config ${configPath}`)
  43. if (parsed.errors.length > 0) {
  44. throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  45. }
  46. return parsed
  47. }
  48. /** Plans and removes repository-owned build output without crossing the repository boundary. */
  49. export class RepositoryCleaner {
  50. constructor(private readonly root: string) {}
  51. /**
  52. * Remove generated build state and package directories containing only known residue.
  53. * @returns Repository-relative paths that were removed.
  54. */
  55. async clean(): Promise<string[]> {
  56. const targets = await this.plan()
  57. // Planning validates every target first, so an unsafe orphan prevents all deletion.
  58. for (const target of targets) await rm(target, { recursive: true, force: true })
  59. return targets.map(target => repositoryPath(this.root, target))
  60. }
  61. private async plan(): Promise<string[]> {
  62. const targets = new Set<string>()
  63. const unsafeOrphans: string[] = []
  64. // These checks cover legacy root-level incremental state emitted by older configs.
  65. await this.addIfPresent(targets, join(this.root, '.typecheck'))
  66. for (const entry of await readdir(this.root, { withFileTypes: true })) {
  67. if (entry.isFile() && entry.name.endsWith('.tsbuildinfo')) targets.add(join(this.root, entry.name))
  68. }
  69. // The root project-reference graph is the source of truth for live build targets.
  70. // Each emitting project declares lib/types as outDir; its parent lib also owns
  71. // the sibling runtime bundles, so the complete build output root is removed.
  72. for (const outputDirectory of this.buildOutputDirectories()) {
  73. await this.addIfPresent(targets, outputDirectory)
  74. }
  75. for (const groupDirectory of await childDirectories(join(this.root, 'packages'))) {
  76. for (const packageDirectory of await childDirectories(groupDirectory)) {
  77. // A package.json marks a live package; its output was discovered from the
  78. // project graph above, and its package-local node_modules must be preserved.
  79. if (await exists(join(packageDirectory, 'package.json'))) {
  80. continue
  81. }
  82. // A manifest-less package directory is stale only when every remaining
  83. // entry is known generated residue; unknown files make the whole clean fail.
  84. const entries = await readdir(packageDirectory)
  85. const unknown = entries.filter(entry => !knownOrphanEntries.has(entry) && !entry.endsWith('.tsbuildinfo'))
  86. if (unknown.length > 0) {
  87. unsafeOrphans.push(...unknown.map(entry => repositoryPath(this.root, join(packageDirectory, entry))))
  88. } else {
  89. targets.add(packageDirectory)
  90. }
  91. }
  92. }
  93. if (unsafeOrphans.length > 0) {
  94. throw new Error([
  95. 'clean: refusing to remove package directories without package.json; unknown entries remain:',
  96. ...unsafeOrphans.sort().map(path => ` ${path}`),
  97. ].join('\n'))
  98. }
  99. return [...targets].sort()
  100. }
  101. private buildOutputDirectories(): string[] {
  102. const outputs = new Set<string>()
  103. const pending = [join(this.root, 'tsconfig.json')]
  104. const visited = new Set<string>()
  105. while (pending.length > 0) {
  106. const nextConfigPath = pending.pop()
  107. if (nextConfigPath === undefined) break
  108. const configPath = resolve(nextConfigPath)
  109. if (visited.has(configPath)) continue
  110. visited.add(configPath)
  111. const parsed = parseConfig(configPath)
  112. if (parsed.options.outDir !== undefined) {
  113. const typesDirectory = resolve(parsed.options.outDir)
  114. if (basename(typesDirectory) !== 'types') {
  115. throw new Error(`clean: expected TypeScript outDir to end in /types: ${repositoryPath(this.root, typesDirectory)}`)
  116. }
  117. const outputDirectory = dirname(typesDirectory)
  118. this.assertRepositoryTarget(outputDirectory)
  119. outputs.add(outputDirectory)
  120. }
  121. for (const reference of parsed.projectReferences ?? []) {
  122. pending.push(ts.resolveProjectReferencePath(reference))
  123. }
  124. }
  125. return [...outputs]
  126. }
  127. private assertRepositoryTarget(path: string): void {
  128. const repositoryRelative = relative(this.root, path)
  129. if (repositoryRelative === '' || repositoryRelative === '..' || repositoryRelative.startsWith(`..${sep}`) || isAbsolute(repositoryRelative)) {
  130. throw new Error(`clean: refusing build output outside repository: ${path}`)
  131. }
  132. }
  133. private async addIfPresent(targets: Set<string>, path: string): Promise<void> {
  134. // Missing outputs are normal on a clean checkout; only existing paths become deletion targets.
  135. if (await exists(path)) targets.add(path)
  136. }
  137. }
  138. const scriptPath = fileURLToPath(import.meta.url)
  139. if (process.argv[1] !== undefined && resolve(process.argv[1]) === scriptPath) {
  140. try {
  141. const removed = await new RepositoryCleaner(resolve(dirname(scriptPath), '..')).clean()
  142. if (removed.length === 0) {
  143. console.log('clean: already clean')
  144. } else {
  145. console.log(`clean: removed ${removed.length} paths`)
  146. }
  147. } catch (error) {
  148. console.error(error instanceof Error ? error.message : error)
  149. process.exitCode = 1
  150. }
  151. }