GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — onicode/scripts/check-changed.test.ts at main · aislopware/onicode Expand file tree/ Copy pathcheck-changed.test.tsMore file actions 505 lines (484 loc) · 18.8 KB / Copy pathcheck-changed.test.tsFile metadata and controls505 lines (484 loc) · 18.8 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 // @effect-diagnostics nodeBuiltinImport:off import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import { expect } from "vite-plus/test"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Option from "effect/Option"; import { afterAll, assert, describe, it } from "@effect/vitest"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as TestClock from "effect/testing/TestClock"; import { comparisonBase, defaultConcurrency, gitLines, ignoredCheckInputs, runSteps, splitTests, type Step, } from "./check-changed.ts"; import { decide, readWorkspace } from "../.github/scripts/ci-changes.cjs"; const GiB = 1024 ** 3; describe("check:changed", () => { it("bounds the default concurrency by the scarcer of cores and available memory", () => { assert.strictEqual(defaultConcurrency(32, 128 * GiB), 16); assert.strictEqual(defaultConcurrency(32, 20 * GiB), 3); assert.strictEqual(defaultConcurrency(4, 15 * GiB), 2); assert.strictEqual(defaultConcurrency(4, 2 * GiB), 1); assert.strictEqual(defaultConcurrency(1, 64 * GiB), 1); }); it("leaves docs inert", () => { const packages = readWorkspace(); assert.deepStrictEqual(decide(["docs/user/install.md"], packages, false).affected, []); }); it.effect( "keeps weighted steps within the budget, in order, and serial steps one at a time", () => Effect.gen(function* () { const startedAt: Record<string, number> = {}; let active = 0; let maxActive = 0; let serialActive = 0; let maxSerial = 0; const step = ( name: string, options: { weight?: number; serial?: boolean } = {}, ): Step<never> => { const slots = Math.min(options.weight ?? 1, 3); return { name, ...options, run: Effect.gen(function* () { startedAt[name] = (yield* Clock.currentTimeMillis) / 1000; active += slots; maxActive = Math.max(maxActive, active); if (options.serial) maxSerial = Math.max(maxSerial, ++serialActive); yield* Effect.sleep("1 second"); active -= slots; if (options.serial) serialActive--; return { ok: true, output: "" }; }), }; }; const fiber = yield* runSteps( [ step("light 1"), // Above the budget, so it holds every slot rather than never starting. step("heavy", { weight: 5 }), step("pair", { weight: 2 }), step("light 2"), step("test 1", { serial: true }), step("test 2", { serial: true }), ], { concurrency: 3, timeoutSeconds: 60 }, ).pipe(Effect.forkChild); yield* TestClock.adjust("10 seconds"); const results = yield* Fiber.join(fiber); assert.deepStrictEqual( results.map((result) => result.outcome), ["pass", "pass", "pass", "pass", "pass", "pass"], ); assert.strictEqual(maxActive, 3); // Lighter steps queued behind the heavy one never start ahead of it. assert.deepStrictEqual(startedAt, { "light 1": 0, heavy: 1, pair: 2, "light 2": 2, "test 1": 3, "test 2": 4, }); assert.strictEqual(maxSerial, 1); }), ); it.effect("interrupts a step at its timeout and reports TIMEOUT, apart from FAIL", () => Effect.gen(function* () { let interrupted = false; const fiber = yield* runSteps( [ { name: "hangs", run: Effect.never.pipe( Effect.onInterrupt(() => Effect.sync(() => (interrupted = true))), ), }, { name: "fails", run: Effect.succeed({ ok: false, output: "error" }) }, { name: "passes", run: Effect.succeed({ ok: true, output: "" }) }, ], { concurrency: 3, timeoutSeconds: 10 }, ).pipe(Effect.forkChild); yield* TestClock.adjust("9 seconds"); assert.isFalse(interrupted); yield* TestClock.adjust("1 second"); const results = yield* Fiber.join(fiber); assert.isTrue(interrupted); assert.deepStrictEqual( results.map(({ name, outcome, time }) => [name, outcome, time]), [ ["hangs", "TIMEOUT", "killed after 10s"], ["fails", "FAIL", "0.0s"], ["passes", "pass", "0.0s"], ], ); }), ); it("runs the .github/scripts node:test files with node --test, not vitest", () => { assert.deepStrictEqual( splitTests([ "apps/server/src/ws.test.ts", ".github/scripts/ci-changes.test.cjs", ".github\\scripts\\thread-transfer-report.test.cjs", "scripts/check-changed.test.ts", ]), { vitestTests: ["apps/server/src/ws.test.ts", "scripts/check-changed.test.ts"], nodeTests: [ ".github/scripts/ci-changes.test.cjs", ".github\\scripts\\thread-transfer-report.test.cjs", ], }, ); }); it.effect("fails instead of returning an empty file list when git exits nonzero", () => { const spawner = (exitCode: number) => ChildProcessSpawner.make(() => Effect.succeed( ChildProcessSpawner.makeHandle({ pid: ChildProcessSpawner.ProcessId(1), exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)), isRunning: Effect.succeed(false), kill: () => Effect.void, unref: Effect.succeed(Effect.void), stdin: Sink.drain, stdout: Stream.encodeText(Stream.make(exitCode === 0 ? "a.ts\nb.ts\n" : "")), stderr: Stream.encodeText( Stream.make(exitCode === 0 ? "" : "fatal: index file corrupt"), ), all: Stream.empty, getInputFd: () => Sink.drain, getOutputFd: () => Stream.empty, }), ), ); return Effect.gen(function* () { const listed = yield* gitLines("/repo", ["ls-files"]).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(0)), ); assert.deepStrictEqual(listed, ["a.ts", "b.ts"]); const error = yield* gitLines("/repo", ["ls-files"]).pipe( Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner(128)), Effect.flip, ); assert.strictEqual( error, "check:changed: git ls-files exited with 128: fatal: index file corrupt", ); }); }); it.each([ "packages/shared/src/testing/longTempDir.ts", "packages/shared/src/testing/providerEnv.ts", "packages/shared/src/testing/gitEnv.ts", "packages/shared/src/testing/gitRepositoryEnv.ts", ])("tests every package when the shared test setup file %s changes", (file) => { assert.strictEqual(decide([file], readWorkspace(), false).outputs.test_packages, ""); }); }); // Hooks export GIT_DIR and GIT_INDEX_FILE, and user config or the default // ~/.config/git/ignore can ignore or sign fixture files. // Git for Windows rejects the null device as a config path, so use an empty file. const emptyConfigDir = NodeFS.mkdtempSync( NodePath.join(NodeOS.tmpdir(), "oni-check-changed-config-"), ); const emptyConfig = NodePath.join(emptyConfigDir, "empty.gitconfig"); NodeFS.writeFileSync(emptyConfig, ""); afterAll(() => NodeFS.rmSync(emptyConfigDir, { recursive: true, force: true })); const fixtureConfig = { "core.excludesFile": emptyConfig, "user.name": "Fixture", }; const env = { ...Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("GIT_"))), GIT_CONFIG_GLOBAL: emptyConfig, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_COUNT: String(Object.keys(fixtureConfig).length), ...Object.fromEntries( Object.entries(fixtureConfig).flatMap(([key, value], index) => [ [`GIT_CONFIG_KEY_${index}`, key], [`GIT_CONFIG_VALUE_${index}`, value], ]), ), }; // History A -> B -> C, with HEAD at C. Each remote's main points at A or B. function fixture(remotes: Record<string, "A" | "B">) { const root = NodeFS.realpathSync( NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "oni-check-changed-")), ); const commits: Record<string, string> = {}; try { const write = (file: string, content: string) => { const path = NodePath.join(root, file); NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true }); NodeFS.writeFileSync(path, content); }; const git = (...args: Array<string>) => NodeChildProcess.execFileSync("git", args, { cwd: root, encoding: "utf8", env }).trim(); git("init"); for (const name of ["A", "B", "C"]) { write(`${name}.txt`, name); git("add", "."); git("commit", "-m", name); commits[name] = git("rev-parse", "HEAD"); } for (const [remote, commit] of Object.entries(remotes)) { git("remote", "add", remote, NodePath.join(root, "missing")); git("update-ref", `refs/remotes/${remote}/main`, commits[commit]!); } } catch (error) { NodeFS.rmSync(root, { recursive: true, force: true }); throw error; } return { commits, root, [Symbol.dispose]() { NodeFS.rmSync(root, { recursive: true, force: true }); }, }; } const inFixture = <A, E>(effect: Effect.Effect<A, E, ChildProcessSpawner.ChildProcessSpawner>) => Effect.gen(function* () { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; return yield* effect.pipe( Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make((command) => spawner.spawn(ChildProcess.setEnv(command, env))), ), ); }).pipe(Effect.provide(NodeServices.layer), Effect.runPromise); const compare = (root: string, ref: Option.Option<string>) => inFixture(comparisonBase(root, ref)); it.each(["upstream", "team/upstream"])( "compares against %s/main when the fork's origin/main lags it", async (remote) => { using project = fixture({ origin: "A", [remote]: "B" }); const result = await compare(project.root, Option.none()); assert.strictEqual(result.base, project.commits.B); assert.strictEqual(result.ref, remote + "/main"); }, ); it("compares against an explicit ref instead of the closest remote main", async () => { using project = fixture({ origin: "A", upstream: "B" }); const result = await compare(project.root, Option.some("origin/main")); assert.strictEqual(result.base, project.commits.A); assert.strictEqual(result.ref, "origin/main"); }); it("lists the ignored inputs that main's pathspecs list, without entering node_modules", async () => { using project = fixture({}); const git = (...args: Array<string>) => NodeChildProcess.execFileSync("git", args, { cwd: project.root, encoding: "utf8", env }); const write = (file: string, content = "") => { NodeFS.mkdirSync(NodePath.dirname(NodePath.join(project.root, file)), { recursive: true }); NodeFS.writeFileSync(NodePath.join(project.root, file), content); }; write(".gitignore", "node_modules/\ndist/\n.generated/\n.env*\n*.gen.d.ts\nreplaced/\nskipped/"); for (const file of ["replaced", "skipped"]) write(file); git("add", "."); git("commit", "-m", "files that directories replace"); git("update-index", "--skip-worktree", "skipped"); for (const file of ["replaced", "skipped"]) NodeFS.rmSync(NodePath.join(project.root, file)); for (const file of [ ".env.local", "src/types.gen.d.ts", "src/.generated/routes.ts", "dist/index.d.ts", "dist/node_modules/pkg/index.d.ts", "node_modules/pkg/index.d.ts", // A package folder left behind by a branch switch. "old/dist/a.d.ts", "old/node_modules/pkg/index.d.ts", "replaced/sub/a.d.ts", "skipped/a.d.ts", ]) write(file); const command = "ls-files -o -i --exclude-standard -- :(glob)**/.generated/** :(glob)**/.astro/** :(glob)**/*.d.ts :(glob)**/.env* :(exclude,glob)**/node_modules/**"; const old = git(...command.split(" ")) .split("\n") .filter(Boolean) .sort(); assert.includeMembers(old, ["old/dist/a.d.ts", "replaced/sub/a.d.ts", "skipped/a.d.ts"]); assert.deepStrictEqual(await inFixture(ignoredCheckInputs(project.root)), old); }); function launcherFixture() { const root = NodeFS.realpathSync( NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "onicode checks & (fixture) ")), ); const write = (file: string, content: string) => { const path = NodePath.join(root, file); NodeFS.mkdirSync(NodePath.dirname(path), { recursive: true }); NodeFS.writeFileSync(path, content); }; for (const file of [ "scripts/check-changed.ts", "scripts/check-changed-command.ts", ".github/scripts/ci-changes.cjs", ]) { write(file, NodeFS.readFileSync(NodePath.join(import.meta.dirname, "..", file), "utf8")); } write(".gitignore", "node_modules/\nrecords/\n"); write( "pnpm-workspace.yaml", "packages:\n - packages/*\nstrictPeerDependencies: true # strict\n", ); write( "package.json", JSON.stringify({ type: "module", scripts: { "knip:check:files": "knip --include files", "knip:check:exports": "knip --exports", }, }), ); write("packages/example/package.json", JSON.stringify({ name: "example" })); const source = "packages/example/space & (draft) %PATH% ! 研究.ts"; write(source, "export const value = 1;\n"); write( "node_modules/vite-plus/package.json", JSON.stringify({ type: "module", exports: { "./bin": "./cli.js" } }), ); write( "node_modules/vite-plus/cli.js", ` import fs from 'node:fs'; import path from 'node:path'; const args = process.argv.slice(2); const workspace = args[0] === 'install' ? { workspace: fs.readFileSync('pnpm-workspace.yaml', 'utf8') } : {}; fs.writeFileSync(path.join(process.env.RECORDS, process.pid + '.json'), JSON.stringify({ args, cwd: process.cwd(), ...workspace })); console.log('fixture stdout: ' + args[0]); console.error('fixture stderr: ' + args[0]); process.exit(args[0] === process.env.FAIL_STEP ? 23 : 0); `, ); // Select the Windows launcher without changing the Effect runtime's host platform. write( "scripts/check-changed.ts", NodeFS.readFileSync(NodePath.join(import.meta.dirname, "check-changed.ts"), "utf8").replace( "vitePlusCommand(args, platform)", 'vitePlusCommand(args, "win32")', ), ); for (const name of ["effect", "@effect/platform-node", "@onicode/shared"]) { const dest = NodePath.join(root, "node_modules", name); NodeFS.mkdirSync(NodePath.dirname(dest), { recursive: true }); NodeFS.symlinkSync( NodeFS.realpathSync(NodePath.join(import.meta.dirname, "node_modules", name)), dest, "junction", ); } const git = (...args: Array<string>) => NodeChildProcess.execFileSync("git", args, { cwd: root, stdio: "pipe", env }); git("init"); git("add", "."); git( "-c", "user.name=Fixture", "-c", "-c", "commit.gpgsign=false", "-c", "core.hooksPath=", "commit", "-m", "fixture", ); const records = NodePath.join(root, "records"); NodeFS.mkdirSync(records); return { root, source, write, run(failStep = "") { return NodeChildProcess.spawnSync(process.execPath, ["scripts/check-changed.ts", "HEAD"], { cwd: root, encoding: "utf8", env: { ...env, TEMP: NodeOS.tmpdir(), RECORDS: records, FAIL_STEP: failStep }, }); }, calls: (): Array<{ args: Array<string>; cwd: string; workspace?: string }> => NodeFS.readdirSync(records).map((file) => JSON.parse(NodeFS.readFileSync(NodePath.join(records, file), "utf8")), ), [Symbol.dispose]() { NodeFS.rmSync(root, { recursive: true, force: true }); }, }; } it("checks changed source paths through the Windows launcher", () => { using project = launcherFixture(); project.write(project.source, "export const value = 2;\n"); const result = project.run(); expect(result.status, result.stdout + result.stderr).toBe(0); const calls = project.calls(); expect(calls.find(({ args }) => args[0] === "lint")).toEqual({ args: ["lint", "--no-error-on-unmatched-pattern", project.source], cwd: project.root, }); expect(calls.some(({ args }) => args[0] === "fmt" && args.includes(project.source))).toBe(true); expect(calls.some(({ args }) => args[0] === "run" && args.includes("typecheck"))).toBe(true); expect(calls.some(({ args }) => args[0] === "install")).toBe(false); expect(result.stdout).toContain("fixture stdout: lint"); expect(result.stdout).toContain("fixture stderr: lint"); }); it("lints an Astro component and runs knip when only it changed", () => { using project = launcherFixture(); const page = "packages/example/Page.astro"; project.write(page, "---\nconst title = 1;\n---\n<h1>{title}</h1>\n"); const result = project.run(); expect(result.status, result.stdout + result.stderr).toBe(0); const calls = project.calls(); expect(calls.find(({ args }) => args[0] === "lint")?.args).toEqual([ "lint", "--no-error-on-unmatched-pattern", page, ]); const commands = calls.map(({ args }) => args); expect(commands).toContainEqual(["exec", "knip", "--include", "files"]); expect(commands).toContainEqual(["exec", "knip", "--exports"]); }); it.each(["install", "lint"])("reports a failing %s step with its output", (step) => { using project = launcherFixture(); project.write(project.source, "export const value = 2;\n"); project.write( "packages/example/package.json", JSON.stringify({ name: "example", version: "1.0.1" }), ); const result = project.run(step); expect(result.status, result.stdout + result.stderr).toBe(1); const install = project.calls().find(({ args }) => args[0] === "install"); expect(install?.args, result.stdout + result.stderr).toEqual([ "install", "--lockfile-only", "--ignore-scripts", ]); expect(install?.cwd).not.toBe(project.root); // Registry drift in peers must not fail a check that is only about patches. expect(install?.workspace).toContain("strictPeerDependencies: false"); expect(install?.workspace).not.toContain("strictPeerDependencies: true"); expect(result.stdout + result.stderr).toContain(`fixture stdout: ${step}`); expect(result.stdout + result.stderr).toContain(`fixture stderr: ${step}`); expect(result.stdout).toContain(step === "install" ? "FAIL unused patches" : "FAIL lint"); if (step === "lint") expect(result.stdout).toContain("pass unused patches"); expect( NodeFS.existsSync(NodePath.join(project.root, "node_modules/.cache/check-changed.json")), ).toBe(false); }); |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |