detect-pr-changes.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import { describe, expect, test } from 'bun:test'
  2. import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
  3. import { tmpdir } from 'node:os'
  4. import { join } from 'node:path'
  5. import {
  6. classifyChangedPaths,
  7. formatGitHubOutput,
  8. parseChangedPaths,
  9. } from './detect-pr-changes'
  10. const NO_CHANGES = {
  11. 'has-evals': false,
  12. 'has-docs': false,
  13. 'has-workflows': false,
  14. 'has-packages': false,
  15. }
  16. const SCRIPT_PATH = join(import.meta.dir, 'detect-pr-changes.ts')
  17. const WORKFLOW_PATH = join(import.meta.dir, '..', '..', '.github', 'workflows', 'pr-checks.yml')
  18. const PACKAGES_WORKFLOW_PATH = join(import.meta.dir, '..', '..', '.github', 'workflows', 'packages-checks.yml')
  19. type CliResult = {
  20. exitCode: number
  21. stderr: string
  22. stdout: string
  23. }
  24. async function runCli(input: string, outputPath?: string): Promise<CliResult> {
  25. const env = { ...process.env }
  26. if (outputPath === undefined) delete env.GITHUB_OUTPUT
  27. else env.GITHUB_OUTPUT = outputPath
  28. const subprocess = Bun.spawn([process.execPath, 'run', SCRIPT_PATH], {
  29. env,
  30. stderr: 'pipe',
  31. stdin: new Blob([input]),
  32. stdout: 'pipe',
  33. })
  34. const [exitCode, stderr, stdout] = await Promise.all([
  35. subprocess.exited,
  36. new Response(subprocess.stderr).text(),
  37. new Response(subprocess.stdout).text(),
  38. ])
  39. return { exitCode, stderr, stdout }
  40. }
  41. async function withTempDir<T>(run: (directory: string) => Promise<T>): Promise<T> {
  42. const directory = await mkdtemp(join(tmpdir(), 'detect-pr-changes-'))
  43. try {
  44. return await run(directory)
  45. } finally {
  46. await rm(directory, { force: true, recursive: true })
  47. }
  48. }
  49. describe('classifyChangedPaths', () => {
  50. test('detects eval changes', () => {
  51. expect(classifyChangedPaths(['evals/framework/src/index.ts'])).toEqual({
  52. ...NO_CHANGES,
  53. 'has-evals': true,
  54. })
  55. })
  56. test('detects docs changes', () => {
  57. expect(classifyChangedPaths(['docs/maintenance/guide.md'])).toEqual({
  58. ...NO_CHANGES,
  59. 'has-docs': true,
  60. })
  61. })
  62. test('detects workflow changes', () => {
  63. expect(classifyChangedPaths(['.github/workflows/pr-checks.yml'])).toEqual({
  64. ...NO_CHANGES,
  65. 'has-workflows': true,
  66. })
  67. })
  68. test('detects packages changes', () => {
  69. expect(classifyChangedPaths(['packages/cli/src/index.ts'])).toEqual({
  70. ...NO_CHANGES,
  71. 'has-packages': true,
  72. })
  73. expect(classifyChangedPaths(['packages/compatibility-layer/package.json'])).toEqual({
  74. ...NO_CHANGES,
  75. 'has-packages': true,
  76. })
  77. })
  78. test('detects shared workspace dependency changes', () => {
  79. for (const path of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml']) {
  80. expect(classifyChangedPaths([path])).toEqual({
  81. ...NO_CHANGES,
  82. 'has-evals': true,
  83. 'has-packages': true,
  84. })
  85. }
  86. })
  87. test('detects package automation changes', () => {
  88. for (const path of [
  89. '.github/dependabot.yml',
  90. '.github/workflows/packages-checks.yml',
  91. 'scripts/validation/detect-pr-changes.ts',
  92. 'scripts/validation/detect-pr-changes.test.ts',
  93. ]) {
  94. expect(classifyChangedPaths([path])).toEqual({
  95. ...NO_CHANGES,
  96. 'has-packages': true,
  97. ...(path.startsWith('.github/workflows/') ? { 'has-workflows': true } : {}),
  98. })
  99. }
  100. })
  101. test('detects mixed changes', () => {
  102. expect(
  103. classifyChangedPaths([
  104. 'evals/framework/package.json',
  105. 'docs/README.md',
  106. '.github/workflows/release.yml',
  107. 'packages/cli/package.json',
  108. 'src/index.ts',
  109. ]),
  110. ).toEqual({
  111. 'has-evals': true,
  112. 'has-docs': true,
  113. 'has-workflows': true,
  114. 'has-packages': true,
  115. })
  116. })
  117. test('returns false for every category when paths do not match', () => {
  118. expect(classifyChangedPaths(['README.md', 'scripts/check.ts'])).toEqual(NO_CHANGES)
  119. })
  120. test('returns false for every category when input is empty', () => {
  121. expect(classifyChangedPaths([])).toEqual(NO_CHANGES)
  122. })
  123. test('rejects near-prefix paths', () => {
  124. expect(
  125. classifyChangedPaths([
  126. 'evals-old/test.ts',
  127. 'docs.md',
  128. '.github/workflows-old/check.yml',
  129. 'nested/evals/test.ts',
  130. 'packages-old/cli/index.ts',
  131. 'packages.json',
  132. 'nested/packages/cli/index.ts',
  133. ]),
  134. ).toEqual(NO_CHANGES)
  135. })
  136. })
  137. describe('parseChangedPaths', () => {
  138. test('preserves path identity and removes empty NUL records', () => {
  139. expect(parseChangedPaths(' evals/test.ts \0\0docs/雪\n$HOME; file.md\0')).toEqual([
  140. ' evals/test.ts ',
  141. 'docs/雪\n$HOME; file.md',
  142. ])
  143. })
  144. })
  145. describe('formatGitHubOutput', () => {
  146. test('formats newline-delimited GitHub outputs', () => {
  147. expect(
  148. formatGitHubOutput({
  149. 'has-evals': true,
  150. 'has-docs': false,
  151. 'has-workflows': true,
  152. 'has-packages': false,
  153. }),
  154. ).toBe('has-evals=true\nhas-docs=false\nhas-workflows=true\nhas-packages=false\n')
  155. })
  156. })
  157. describe('CLI', () => {
  158. test('appends outputs to GITHUB_OUTPUT', async () => {
  159. await withTempDir(async (directory) => {
  160. const outputPath = join(directory, 'github-output')
  161. await writeFile(outputPath, 'existing=value\n')
  162. const result = await runCli('evals/test.ts\0', outputPath)
  163. expect(result).toEqual({ exitCode: 0, stderr: '', stdout: '' })
  164. expect(await readFile(outputPath, 'utf8')).toBe(
  165. 'existing=value\nhas-evals=true\nhas-docs=false\nhas-workflows=false\nhas-packages=false\n',
  166. )
  167. })
  168. })
  169. test('writes false outputs for empty stdin', async () => {
  170. await withTempDir(async (directory) => {
  171. const outputPath = join(directory, 'github-output')
  172. const result = await runCli('', outputPath)
  173. expect(result.exitCode).toBe(0)
  174. expect(await readFile(outputPath, 'utf8')).toBe(
  175. 'has-evals=false\nhas-docs=false\nhas-workflows=false\nhas-packages=false\n',
  176. )
  177. })
  178. })
  179. test('fails clearly when GITHUB_OUTPUT is missing', async () => {
  180. const result = await runCli('evals/test.ts\0')
  181. expect(result.exitCode).not.toBe(0)
  182. expect(result.stderr).toContain('GITHUB_OUTPUT is required but was not set')
  183. })
  184. test('writes an error to stderr and exits nonzero for an unwritable target', async () => {
  185. await withTempDir(async (directory) => {
  186. const outputPath = join(directory, 'output-directory')
  187. await mkdir(outputPath)
  188. const result = await runCli('docs/guide.md\0', outputPath)
  189. expect(result.exitCode).not.toBe(0)
  190. expect(result.stderr).toContain('Unable to append change detection outputs to GITHUB_OUTPUT')
  191. })
  192. })
  193. test('handles NUL-delimited Unicode and metacharacter filenames without changing identity', async () => {
  194. await withTempDir(async (directory) => {
  195. const outputPath = join(directory, 'github-output')
  196. const paths = [
  197. 'evals/ leading and trailing .ts ',
  198. 'docs/雪\n$HOME;$(touch never).md',
  199. '.github/workflows/[check]& weird.yml',
  200. 'packages/cli/src/ spaced 雪.ts',
  201. ]
  202. const result = await runCli(`${paths.join('\0')}\0`, outputPath)
  203. expect(result.exitCode).toBe(0)
  204. expect(await readFile(outputPath, 'utf8')).toBe(
  205. 'has-evals=true\nhas-docs=true\nhas-workflows=true\nhas-packages=true\n',
  206. )
  207. })
  208. })
  209. test('does not trim leading whitespace into a matching path', async () => {
  210. await withTempDir(async (directory) => {
  211. const outputPath = join(directory, 'github-output')
  212. const result = await runCli(' evals/not-under-evals.ts\0', outputPath)
  213. expect(result.exitCode).toBe(0)
  214. expect(await readFile(outputPath, 'utf8')).toContain('has-evals=false\n')
  215. })
  216. })
  217. })
  218. describe('PR checks workflow contract', () => {
  219. test('uses the NUL-delimited detector and exact output names', async () => {
  220. const workflow = await readFile(WORKFLOW_PATH, 'utf8')
  221. expect(workflow).toContain('git diff --name-only -z')
  222. expect(workflow).toMatch(/git diff --name-only -z[^\n]*\|[\s\S]*bun run scripts\/validation\/detect-pr-changes\.ts/)
  223. expect(workflow).toContain('has-evals: ${{ steps.filter.outputs.has-evals }}')
  224. expect(workflow).toContain('has-docs: ${{ steps.filter.outputs.has-docs }}')
  225. expect(workflow).toContain('has-workflows: ${{ steps.filter.outputs.has-workflows }}')
  226. expect(workflow).not.toMatch(/steps\.filter\.outputs\.(evals|docs|workflows)(?:\s|})/)
  227. expect(workflow).toContain('oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6')
  228. expect(workflow).toContain('bun-version: 1.3.14')
  229. })
  230. test('requires successful change detection before reporting overall success', async () => {
  231. const workflow = await readFile(WORKFLOW_PATH, 'utf8')
  232. const overallStatus = workflow.slice(workflow.indexOf('# Overall status'))
  233. expect(overallStatus).toContain('needs.check-changes.result }}" == "success"')
  234. expect(overallStatus).toContain('needs.check-changes.outputs.has-evals }}" != "true"')
  235. expect(overallStatus).toContain('exit 1')
  236. })
  237. })
  238. describe('Packages checks workflow contract', () => {
  239. test('uses the NUL-delimited detector and the has-packages output', async () => {
  240. const workflow = await readFile(PACKAGES_WORKFLOW_PATH, 'utf8')
  241. expect(workflow).toContain('git diff --name-only -z')
  242. expect(workflow).toMatch(/git diff --name-only -z[^\n]*\|[\s\S]*bun run scripts\/validation\/detect-pr-changes\.ts/)
  243. expect(workflow).toContain('has-packages: ${{ steps.filter.outputs.has-packages }}')
  244. expect(workflow).toContain('oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6')
  245. expect(workflow).toContain('bun-version: 1.3.14')
  246. })
  247. test('gates every package check job on the has-packages flag', async () => {
  248. const workflow = await readFile(PACKAGES_WORKFLOW_PATH, 'utf8')
  249. expect(workflow).toContain('cli-checks:')
  250. expect(workflow).toContain('compatibility-layer-checks:')
  251. const gates = workflow.match(/needs\.check-changes\.outputs\.has-packages == 'true'/g) ?? []
  252. expect(gates.length).toBeGreaterThanOrEqual(2)
  253. })
  254. test('triggers on packages/** pull request changes', async () => {
  255. const workflow = await readFile(PACKAGES_WORKFLOW_PATH, 'utf8')
  256. expect(workflow).toContain('pull_request:')
  257. expect(workflow).toContain("- 'packages/**'")
  258. })
  259. })