clean.ts 6.3 KB

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