clean.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. import { lstat, readdir, realpath, 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. private readonly root: string
  42. constructor(root: string) {
  43. this.root = resolve(root)
  44. }
  45. /**
  46. * Remove generated build state and package directories containing only known residue.
  47. * @returns Repository-relative paths that were removed.
  48. */
  49. async clean(): Promise<string[]> {
  50. const targets = await this.plan()
  51. // Planning validates every target first, so an unsafe orphan prevents all deletion.
  52. for (const target of targets) await rm(target, { recursive: true, force: true })
  53. return targets.map(target => repositoryPath(this.root, target))
  54. }
  55. private async plan(): Promise<string[]> {
  56. const targets = new Set<string>()
  57. const unsafeOrphans: string[] = []
  58. const canonicalRoot = await realpath(this.root)
  59. // These checks cover legacy root-level incremental state emitted by older configs.
  60. await this.addIfPresent(targets, join(this.root, '.typecheck'), canonicalRoot)
  61. for (const entry of await readdir(this.root, { withFileTypes: true })) {
  62. if (entry.isFile() && entry.name.endsWith('.tsbuildinfo')) targets.add(join(this.root, entry.name))
  63. }
  64. // The root project-reference graph is the source of truth for live build targets.
  65. // Each emitting project declares lib/types as outDir; its parent lib also owns
  66. // the sibling runtime bundles, so the complete build output root is removed.
  67. for (const outputDirectory of this.buildOutputDirectories()) {
  68. await this.addIfPresent(targets, outputDirectory, canonicalRoot)
  69. }
  70. for (const groupDirectory of await childDirectories(join(this.root, 'packages'))) {
  71. for (const packageDirectory of await childDirectories(groupDirectory)) {
  72. // A package.json marks a live package; its output was discovered from the
  73. // project graph above, and its package-local node_modules must be preserved.
  74. if (await exists(join(packageDirectory, 'package.json'))) {
  75. continue
  76. }
  77. // A manifest-less package directory is stale only when every remaining
  78. // entry is known generated residue; unknown files make the whole clean fail.
  79. const entries = await readdir(packageDirectory)
  80. const unknown = entries.filter(entry => !knownOrphanEntries.has(entry) && !entry.endsWith('.tsbuildinfo'))
  81. if (unknown.length > 0) {
  82. unsafeOrphans.push(...unknown.map(entry => repositoryPath(this.root, join(packageDirectory, entry))))
  83. } else {
  84. await this.addIfPresent(targets, packageDirectory, canonicalRoot)
  85. }
  86. }
  87. }
  88. if (unsafeOrphans.length > 0) {
  89. throw new Error([
  90. 'clean: refusing to remove package directories without package.json; unknown entries remain:',
  91. ...unsafeOrphans.sort().map(path => ` ${path}`),
  92. ].join('\n'))
  93. }
  94. return [...targets].sort()
  95. }
  96. private buildOutputDirectories(): string[] {
  97. const outputs = new Set<string>()
  98. const pending = [join(this.root, 'tsconfig.json')]
  99. const visited = new Set<string>()
  100. while (pending.length > 0) {
  101. const nextConfigPath = pending.pop()
  102. if (nextConfigPath === undefined) break
  103. const configPath = resolve(nextConfigPath)
  104. if (visited.has(configPath)) continue
  105. visited.add(configPath)
  106. const parsed = parseConfig(configPath)
  107. if (parsed.options.outDir !== undefined) {
  108. const typesDirectory = resolve(parsed.options.outDir)
  109. if (basename(typesDirectory) !== 'types') {
  110. throw new Error(`clean: expected TypeScript outDir to end in /types: ${repositoryPath(this.root, typesDirectory)}`)
  111. }
  112. const outputDirectory = dirname(typesDirectory)
  113. this.assertRepositoryTarget(outputDirectory)
  114. outputs.add(outputDirectory)
  115. }
  116. for (const reference of parsed.projectReferences ?? []) {
  117. pending.push(ts.resolveProjectReferencePath(reference))
  118. }
  119. }
  120. return [...outputs]
  121. }
  122. private assertRepositoryTarget(path: string): void {
  123. this.assertDescendant(this.root, path, path)
  124. }
  125. private assertDescendant(root: string, path: string, displayPath: string): void {
  126. const repositoryRelative = relative(root, path)
  127. if (repositoryRelative === '' || repositoryRelative === '..' || repositoryRelative.startsWith(`..${sep}`) || isAbsolute(repositoryRelative)) {
  128. throw new Error(`clean: refusing deletion target outside repository: ${displayPath}`)
  129. }
  130. }
  131. private async addIfPresent(targets: Set<string>, path: string, canonicalRoot: string): Promise<void> {
  132. // Missing outputs are normal on a clean checkout; only existing paths become deletion targets.
  133. if (!await exists(path)) return
  134. // Resolve the parent rather than the final entry: rm unlinks a final symlink,
  135. // but a symlink in an ancestor would make deletion cross the repository boundary.
  136. const canonicalParent = await realpath(dirname(path))
  137. this.assertDescendant(canonicalRoot, join(canonicalParent, basename(path)), path)
  138. targets.add(path)
  139. }
  140. }
  141. const scriptPath = fileURLToPath(import.meta.url)
  142. if (process.argv[1] !== undefined && resolve(process.argv[1]) === scriptPath) {
  143. try {
  144. const removed = await new RepositoryCleaner(resolve(dirname(scriptPath), '..')).clean()
  145. if (removed.length === 0) {
  146. console.log('clean: already clean')
  147. } else {
  148. console.log(`clean: removed ${removed.length} paths`)
  149. }
  150. } catch (error) {
  151. console.error(error instanceof Error ? error.message : error)
  152. process.exitCode = 1
  153. }
  154. }