): string };
+ const specifier: string = "diff2html";
+ let mod: Diff2Html;
+ try {
+ mod = (await import(specifier)) as unknown as Diff2Html;
+ } catch {
+ throw new Error(
+ "Rendering --html requires the 'diff2html' package. Install it in eng/emitter-diff " +
+ "(it is declared as a dependency) or run with `pnpm` so it is available.",
+ );
+ }
+ const body = mod.html(diff.patch, {
+ drawFileList: true,
+ matching: "lines",
+ outputFormat: "side-by-side",
+ });
+ const doc = `
+
+
+
+Emitter diff
+
+
+
+
+Emitter diff β ${diff.filesChanged} file(s), +${diff.insertions} / -${diff.deletions}
+${body}
+
+`;
+ writeFileSync(outFile, doc, "utf8");
+ const abs = resolve(outFile);
+ log.success(`Wrote HTML diff to ${abs}`);
+ log.info(`${color.bold("Open it:")} ${pathToFileURL(abs).href}`);
+}
+
+/**
+ * Open a native side-by-side diff of the two generated trees in VS Code.
+ *
+ * VS Code has no CLI to diff two folders (`code --diff` only compares two
+ * files), so we materialize the comparison as a throwaway git working-tree
+ * change: commit the baseline tree, then overlay the head tree on top and leave
+ * it unstaged. Opening that folder surfaces every changed generated file in the
+ * Source Control view with red/green side-by-side diffs.
+ */
+export async function openInVsCode(
+ baselineDir: string,
+ headDir: string,
+ workDir: string,
+ log: Logger,
+): Promise {
+ log.step("Preparing VS Code diff");
+ const repo = join(workDir, "vscode-diff");
+ rmSync(repo, { recursive: true, force: true });
+ mkdirSync(repo, { recursive: true });
+
+ const git = (args: string[]) =>
+ runChecked("git", [
+ "-C",
+ repo,
+ "-c",
+ "user.email=emitter-diff@local",
+ "-c",
+ "user.name=emitter-diff",
+ "-c",
+ "commit.gpgsign=false",
+ "-c",
+ "core.autocrlf=false",
+ ...args,
+ ]);
+
+ await git(["init", "-q"]);
+ // Commit the baseline tree as the starting point.
+ cpSync(baselineDir, repo, { recursive: true });
+ await git(["add", "-A"]);
+ await git(["commit", "-q", "-m", "baseline", "--allow-empty"]);
+
+ // Overlay the head tree (keeping .git), then stage so VS Code shows the diff.
+ for (const entry of readdirSync(repo)) {
+ if (entry === ".git") continue;
+ rmSync(join(repo, entry), { recursive: true, force: true });
+ }
+ cpSync(headDir, repo, { recursive: true });
+ // Drop all index entries first, then re-add. A plain `git add -A` decides a
+ // file is unchanged from (size, mtime) and skips re-hashing it; because the
+ // baseline commit and the head overlay are written within the same second,
+ // a same-size content edit would be treated as clean and never staged (so it
+ // would silently not appear in VS Code). Clearing the index forces git to
+ // re-hash every file's content, surfacing every real modification.
+ await git(["rm", "-r", "--cached", "-q", "--", "."]);
+ await git(["add", "-A"]);
+
+ const result = await run("code", [repo]);
+ if (result.code !== 0) {
+ log.warn(
+ "Could not launch VS Code (`code` not on PATH?). Open the folder manually " +
+ `and use the Source Control view to browse the diff: ${repo}`,
+ );
+ return;
+ }
+ log.success(
+ `Opened ${repo} in VS Code β use the Source Control panel to browse the diff ` +
+ "(baseline = last commit, head = working tree).",
+ );
+}
diff --git a/eng/emitter-diff/src/registry.ts b/eng/emitter-diff/src/registry.ts
new file mode 100644
index 00000000000..6b7bd59db55
--- /dev/null
+++ b/eng/emitter-diff/src/registry.ts
@@ -0,0 +1,20 @@
+/** Adapter registry. New languages register here; the core is otherwise agnostic. */
+import { pythonAdapter } from "./adapters/python.js";
+import type { EmitterAdapter } from "./types.js";
+
+const adapters: Record = {
+ [pythonAdapter.name]: pythonAdapter,
+ // Future: ts, rust, java, go ... each wraps its own generate/test command.
+};
+
+export function getAdapter(name: string): EmitterAdapter {
+ const adapter = adapters[name];
+ if (!adapter) {
+ throw new Error(`Unknown emitter '${name}'. Available: ${Object.keys(adapters).join(", ")}`);
+ }
+ return adapter;
+}
+
+export function listAdapters(): string[] {
+ return Object.keys(adapters);
+}
diff --git a/eng/emitter-diff/src/resolver.ts b/eng/emitter-diff/src/resolver.ts
new file mode 100644
index 00000000000..6f77a4fba07
--- /dev/null
+++ b/eng/emitter-diff/src/resolver.ts
@@ -0,0 +1,170 @@
+/**
+ * Language-agnostic ref resolver.
+ *
+ * Classifies a user-provided ref string into npm / local / github and
+ * materializes it into a local directory the adapter can consume. Building a
+ * source checkout into a usable emitter is intentionally NOT done here β that
+ * is language-specific and belongs to the adapter's `prepareEmitter`.
+ */
+import { existsSync, mkdtempSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { isAbsolute, join, resolve } from "node:path";
+
+import type { ClassifiedRef, Logger } from "./types.js";
+import { ensureDir, runChecked } from "./util.js";
+
+/**
+ * Classify a ref string. Explicit prefixes (`npm:`, `local:`, `github:`,
+ * `gh:`) are honored first, then a few heuristics:
+ * - an `https://github.com/...` url β github
+ * - an existing filesystem path β local
+ * - a bare `pkg@version` or semver-ish string β npm
+ */
+export function classifyRef(raw: string, repoRoot: string): ClassifiedRef {
+ const trimmed = raw.trim();
+
+ if (trimmed.startsWith("npm:")) {
+ return { kind: "npm", raw, version: trimmed.slice(4) };
+ }
+ if (trimmed.startsWith("local:")) {
+ const p = trimmed.slice(6);
+ return { kind: "local", raw, path: isAbsolute(p) ? p : resolve(repoRoot, p) };
+ }
+ if (trimmed.startsWith("github:")) {
+ return parseGithub(trimmed.slice(7), raw);
+ }
+ if (trimmed.startsWith("gh:")) {
+ // gh:[ => current repo at ][
+ return { kind: "github", raw, gitRef: trimmed.slice(3) };
+ }
+ if (/^https?:\/\/github\.com\//i.test(trimmed)) {
+ return parseGithubUrl(trimmed, raw);
+ }
+
+ // Heuristic: existing path -> local.
+ const asPath = isAbsolute(trimmed) ? trimmed : resolve(repoRoot, trimmed);
+ if (existsSync(asPath)) {
+ return { kind: "local", raw, path: asPath };
+ }
+
+ // Fallback: treat as an npm version/tag (or `@scope/pkg@version`).
+ return { kind: "npm", raw, version: extractNpmVersion(trimmed) };
+}
+
+function extractNpmVersion(spec: string): string {
+ // `@scope/pkg@1.2.3` -> `1.2.3`; `pkg@1.2.3` -> `1.2.3`; `1.2.3` -> `1.2.3`.
+ const at = spec.lastIndexOf("@");
+ if (at > 0) return spec.slice(at + 1);
+ return spec;
+}
+
+function parseGithub(rest: string, raw: string): ClassifiedRef {
+ // owner/repo@ref OR owner/repo
+ const at = rest.lastIndexOf("@");
+ if (at > 0) {
+ return { kind: "github", raw, repo: rest.slice(0, at), gitRef: rest.slice(at + 1) };
+ }
+ return { kind: "github", raw, repo: rest };
+}
+
+function parseGithubUrl(url: string, raw: string): ClassifiedRef {
+ // https://github.com/owner/repo/tree/][[/...] or .../commit/
+ const m = url.match(/github\.com\/([^/]+)\/([^/]+)(?:\/(?:tree|commit|blob)\/([^/]+))?/i);
+ if (!m) return { kind: "github", raw };
+ const repo = `${m[1]}/${m[2].replace(/\.git$/, "")}`;
+ return { kind: "github", raw, repo, gitRef: m[3] };
+}
+
+export function describeRef(ref: ClassifiedRef, packageName: string): string {
+ switch (ref.kind) {
+ case "npm":
+ return `npm ${packageName}@${ref.version}`;
+ case "local":
+ return `local ${ref.path}`;
+ case "github":
+ return `github ${ref.repo ?? ""}@${ref.gitRef ?? ""}`;
+ }
+}
+
+const DEFAULT_REPO = "microsoft/typespec";
+
+/**
+ * Materialize a local-or-github ref into a source directory. npm refs are
+ * handled by {@link installNpmPackage} (the package name is adapter-specific).
+ */
+export async function resolveSource(
+ ref: ClassifiedRef,
+ workDir: string,
+ log: Logger,
+): Promise {
+ if (ref.kind === "local") {
+ if (!ref.path || !existsSync(ref.path)) {
+ throw new Error(`Local ref path does not exist: ${ref.path}`);
+ }
+ return ref.path;
+ }
+ if (ref.kind === "github") {
+ return cloneGithub(ref, workDir, log);
+ }
+ throw new Error(`resolveSource cannot handle npm refs directly (ref: ${ref.raw})`);
+}
+
+async function cloneGithub(ref: ClassifiedRef, workDir: string, log: Logger): Promise {
+ const repo = ref.repo ?? DEFAULT_REPO;
+ const gitRef = ref.gitRef ?? "main";
+ const dest = ensureDir(join(workDir, `github-${repo.replace(/[/]/g, "_")}-${sanitize(gitRef)}`));
+ const cloneUrl = `https://github.com/${repo}.git`;
+
+ log.step(`Fetching ${repo}@${gitRef}`);
+ // Shallow-clone then fetch the exact ref so both branches and SHAs work.
+ await runChecked("git", ["init", "-q"], { cwd: dest });
+ await runChecked("git", ["remote", "add", "origin", cloneUrl], { cwd: dest }).catch(() => {});
+ const fetched = await runChecked("git", ["fetch", "--depth", "1", "origin", gitRef], {
+ cwd: dest,
+ }).catch(() => undefined);
+ if (!fetched) {
+ // SHA not directly fetchable on some servers; fall back to a full fetch.
+ await runChecked("git", ["fetch", "origin"], { cwd: dest });
+ }
+ await runChecked("git", ["checkout", "-q", "FETCH_HEAD"], { cwd: dest }).catch(async () => {
+ await runChecked("git", ["checkout", "-q", gitRef], { cwd: dest });
+ });
+ return dest;
+}
+
+/**
+ * Install a published npm package version into an isolated dir and return the
+ * path to the installed package (which ships a prebuilt `dist`).
+ */
+export async function installNpmPackage(
+ packageName: string,
+ version: string,
+ workDir: string,
+ log: Logger,
+): Promise {
+ const dir = ensureDir(
+ join(workDir, `npm-${packageName.replace(/[@/]/g, "_")}-${sanitize(version)}`),
+ );
+ log.step(`Installing ${packageName}@${version}`);
+ // Create a throwaway package root and install just the one package there.
+ await runChecked("npm", ["init", "-y"], { cwd: dir });
+ await runChecked(
+ "npm",
+ ["install", `${packageName}@${version}`, "--no-audit", "--no-fund", "--no-save"],
+ { cwd: dir },
+ );
+ const pkgDir = join(dir, "node_modules", packageName);
+ if (!existsSync(pkgDir)) {
+ throw new Error(`Installed ${packageName}@${version} but ${pkgDir} not found`);
+ }
+ return pkgDir;
+}
+
+function sanitize(s: string): string {
+ return s.replace(/[^a-z0-9._-]/gi, "-").slice(0, 40);
+}
+
+/** Create a fresh scratch dir under the OS temp dir when `--work-dir` is omitted. */
+export function defaultWorkDir(): string {
+ return mkdtempSync(join(tmpdir(), "emitter-diff-"));
+}
diff --git a/eng/emitter-diff/src/types.ts b/eng/emitter-diff/src/types.ts
new file mode 100644
index 00000000000..d89a00582cc
--- /dev/null
+++ b/eng/emitter-diff/src/types.ts
@@ -0,0 +1,122 @@
+/**
+ * Core, language-agnostic types for the emitter-diff tool.
+ *
+ * The orchestrator, ref resolver and diff engine depend only on the generic
+ * {@link EmitterAdapter} contract defined here. Nothing in this file (or in the
+ * core) knows anything about a specific language's tooling β all language
+ * details live behind an adapter.
+ */
+
+/** The three kinds of source a ref can point at. */
+export type RefKind = "npm" | "local" | "github";
+
+/**
+ * A classified reference to either an emitter version or a specs source.
+ *
+ * Accepted user syntaxes (see {@link classifyRef}):
+ * - npm: `npm:1.2.3`, `1.2.3`, `@scope/pkg@1.2.3`
+ * - local: `local:/abs/or/rel/path`, or any existing filesystem path
+ * - github: `github:owner/repo@][`, `gh:][` (this repo), or an `https://github.com/...` url
+ */
+export interface ClassifiedRef {
+ kind: RefKind;
+ /** The original, unparsed ref string. */
+ raw: string;
+ /** npm: the version/tag (e.g. `1.2.3`, `latest`). */
+ version?: string;
+ /** local: the absolute path on disk. */
+ path?: string;
+ /** github: `owner/repo` (defaults to the current repo when omitted). */
+ repo?: string;
+ /** github: branch, tag or sha. */
+ gitRef?: string;
+}
+
+/** A built/usable emitter, ready to be pointed at by the adapter's generate step. */
+export interface ResolvedEmitter {
+ /** Directory containing the usable emitter build. */
+ dir: string;
+ /** Human-readable label for logs (e.g. `npm @typespec/http-client-python@0.34.0`). */
+ label: string;
+}
+
+/** Shared context handed to every adapter call. */
+export interface AdapterContext {
+ /** Repo root (the git working tree the tool was invoked from). */
+ repoRoot: string;
+ /** Scratch directory the adapter may use for builds/installs. */
+ workDir: string;
+ /** Structured logger. */
+ log: Logger;
+ /**
+ * Core helper that materializes a {@link ClassifiedRef} into a local source
+ * directory (handles `local` passthrough and `github` fetch). For `npm`, the
+ * adapter typically resolves the package itself via {@link installNpmPackage}.
+ */
+ resolveSource(ref: ClassifiedRef, packageName: string): Promise;
+ /** Core helper that installs an npm package version and returns its dir. */
+ installNpmPackage(packageName: string, version: string): Promise;
+}
+
+export interface GenerateRequest {
+ /** Resolved emitter build to generate with. */
+ emitter: ResolvedEmitter;
+ /** Resolved specs directory, or undefined to use the adapter's repo default. */
+ specsDir?: string;
+ /** Directory the generated code must be written to. */
+ outputDir: string;
+ /** Optional name/pattern filter limiting which specs/packages are generated. */
+ nameFilter?: string;
+ /** Adapter-specific options collected from repeatable `--opt key=value`. */
+ options: Record;
+ /** Everything after a `--` on the command line, forwarded verbatim. */
+ passthrough: string[];
+ /**
+ * Optional prefix to tag each line of this generation's output with. Set when
+ * baseline and head generate concurrently so their interleaved logs stay
+ * attributable; when unset, output streams straight to the terminal.
+ */
+ logPrefix?: string;
+}
+
+export interface RunTestsRequest {
+ /** The generated output tree to run suites against. */
+ outputDir: string;
+ /** Adapter-defined suite/environment names (e.g. `test`, `lint`, `mypy`). */
+ envs?: string[];
+ nameFilter?: string;
+ options: Record;
+ passthrough: string[];
+}
+
+/**
+ * Per-language plugin. A thin wrapper over an emitter's own generate and test
+ * commands. The core never reaches around this contract.
+ */
+export interface EmitterAdapter {
+ /** Stable id used by `--emitter` (e.g. `python`). */
+ readonly name: string;
+ /** npm package name, used when a ref is an npm version. */
+ readonly packageName: string;
+
+ /**
+ * Turn a classified ref (or the special `current` checkout) into a usable,
+ * built emitter. `npm` versions ship prebuilt; `local`/`github`/`current`
+ * may need a build, which is the adapter's responsibility.
+ */
+ prepareEmitter(ref: ClassifiedRef | "current", ctx: AdapterContext): Promise;
+
+ /** Generate code into `request.outputDir` using `request.emitter`. */
+ generate(request: GenerateRequest, ctx: AdapterContext): Promise;
+
+ /** Optional: run the emitter's test suites against an output tree. */
+ runTests?(request: RunTestsRequest, ctx: AdapterContext): Promise;
+}
+
+export interface Logger {
+ info(msg: string): void;
+ warn(msg: string): void;
+ error(msg: string): void;
+ step(msg: string): void;
+ success(msg: string): void;
+}
diff --git a/eng/emitter-diff/src/util.ts b/eng/emitter-diff/src/util.ts
new file mode 100644
index 00000000000..3ef50e4c7d2
--- /dev/null
+++ b/eng/emitter-diff/src/util.ts
@@ -0,0 +1,167 @@
+/**
+ * Small shared utilities with zero external dependencies so the tool can run
+ * via `node`/`tsx` without a workspace install.
+ */
+import { spawn, type SpawnOptions } from "node:child_process";
+import { mkdirSync } from "node:fs";
+
+import type { Logger } from "./types.js";
+
+// ---- Minimal ANSI colors (no picocolors dependency) ----
+
+const useColor = process.stdout.isTTY && process.env.NO_COLOR === undefined;
+function wrap(open: number, close: number): (s: string) => string {
+ return (s) => (useColor ? `\x1b[${open}m${s}\x1b[${close}m` : s);
+}
+export const color = {
+ bold: wrap(1, 22),
+ dim: wrap(2, 22),
+ red: wrap(31, 39),
+ green: wrap(32, 39),
+ yellow: wrap(33, 39),
+ blue: wrap(34, 39),
+ cyan: wrap(36, 39),
+ gray: wrap(90, 39),
+};
+
+export function createLogger(): Logger {
+ /* eslint-disable no-console */
+ return {
+ info: (m) => console.log(m),
+ warn: (m) => console.warn(`${color.yellow("warn")} ${m}`),
+ error: (m) => console.error(`${color.red("error")} ${m}`),
+ step: (m) => console.log(`${color.cyan("βΊ")} ${color.bold(m)}`),
+ success: (m) => console.log(`${color.green("β")} ${m}`),
+ };
+ /* eslint-enable no-console */
+}
+
+export function ensureDir(dir: string): string {
+ mkdirSync(dir, { recursive: true });
+ return dir;
+}
+
+export interface RunResult {
+ code: number;
+ stdout: string;
+ stderr: string;
+}
+
+/**
+ * Spawn a command and resolve with its captured output. Never rejects on a
+ * non-zero exit; inspect {@link RunResult.code}. Set `inherit` to stream
+ * output straight to the terminal (used for long generation/test runs). Set
+ * `prefix` to stream each output line tagged with that prefix instead β useful
+ * when several children run concurrently and their logs would otherwise
+ * interleave unintelligibly. `prefix` is ignored when `inherit` is set.
+ */
+export function run(
+ cmd: string,
+ args: string[],
+ opts: { cwd?: string; env?: NodeJS.ProcessEnv; inherit?: boolean; prefix?: string } = {},
+): Promise {
+ return new Promise((resolve, reject) => {
+ // Only route through a shell for Windows .cmd shims (npm/pnpm/npx/code/yarn).
+ // Native binaries like git/node are spawned directly to avoid the shell
+ // argument-escaping deprecation and quoting pitfalls.
+ const needsShell = process.platform === "win32" && /^(npm|pnpm|npx|yarn|code)$/.test(cmd);
+ const spawnOpts: SpawnOptions = {
+ cwd: opts.cwd,
+ env: opts.env ?? process.env,
+ stdio: opts.inherit ? "inherit" : "pipe",
+ shell: needsShell,
+ };
+ // With `shell: true`, passing an args array triggers a Node deprecation
+ // (DEP0190). Build a single quoted command line instead; spawn directly
+ // with the args array when no shell is involved.
+ const child = needsShell
+ ? spawn([cmd, ...args.map(quoteForShell)].join(" "), spawnOpts)
+ : spawn(cmd, args, spawnOpts);
+ let stdout = "";
+ let stderr = "";
+
+ // When a prefix is requested, tee complete lines to our own stdout/stderr
+ // tagged with the prefix while still capturing the raw output for the
+ // returned RunResult. A small line buffer holds partial trailing lines
+ // until the next chunk (or close) completes them.
+ const tee = !opts.inherit && opts.prefix !== undefined ? makeLineTee(opts.prefix) : undefined;
+
+ child.stdout?.on("data", (d) => {
+ const s = d.toString();
+ stdout += s;
+ tee?.stdout(s);
+ });
+ child.stderr?.on("data", (d) => {
+ const s = d.toString();
+ stderr += s;
+ tee?.stderr(s);
+ });
+ child.on("error", reject);
+ child.on("close", (code) => {
+ tee?.flush();
+ resolve({ code: code ?? 0, stdout, stderr });
+ });
+ });
+}
+
+/**
+ * Build a pair of line-buffering writers that emit `${prefix}${line}` to the
+ * parent process's stdout/stderr as complete lines arrive, plus a `flush` to
+ * drain any partial trailing line when the child closes.
+ */
+function makeLineTee(prefix: string): {
+ stdout: (s: string) => void;
+ stderr: (s: string) => void;
+ flush: () => void;
+} {
+ function writer(out: NodeJS.WriteStream): { write: (s: string) => void; rest: () => string } {
+ let buf = "";
+ return {
+ write(s: string) {
+ buf += s;
+ let nl: number;
+ while ((nl = buf.indexOf("\n")) >= 0) {
+ out.write(`${prefix}${buf.slice(0, nl)}\n`);
+ buf = buf.slice(nl + 1);
+ }
+ },
+ rest() {
+ const r = buf;
+ buf = "";
+ return r;
+ },
+ };
+ }
+ const o = writer(process.stdout);
+ const e = writer(process.stderr);
+ return {
+ stdout: o.write,
+ stderr: e.write,
+ flush() {
+ const ro = o.rest();
+ if (ro) process.stdout.write(`${prefix}${ro}\n`);
+ const re = e.rest();
+ if (re) process.stderr.write(`${prefix}${re}\n`);
+ },
+ };
+}
+
+/** Quote an argument for cmd.exe when running through a shell. */
+function quoteForShell(s: string): string {
+ if (s.length > 0 && /^[A-Za-z0-9_.:\\/=@^-]+$/.test(s)) return s;
+ return `"${s.replace(/"/g, '""')}"`;
+}
+
+/** Run a command and throw if it exits non-zero. */
+export async function runChecked(
+ cmd: string,
+ args: string[],
+ opts: { cwd?: string; env?: NodeJS.ProcessEnv; inherit?: boolean; prefix?: string } = {},
+): Promise {
+ const result = await run(cmd, args, opts);
+ if (result.code !== 0) {
+ const detail = opts.inherit ? "" : `\n${result.stderr || result.stdout}`;
+ throw new Error(`Command failed (${result.code}): ${cmd} ${args.join(" ")}${detail}`);
+ }
+ return result;
+}
diff --git a/eng/emitter-diff/tsconfig.json b/eng/emitter-diff/tsconfig.json
new file mode 100644
index 00000000000..f51bfa6da96
--- /dev/null
+++ b/eng/emitter-diff/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "target": "es2022",
+ "lib": ["es2023"],
+ "strict": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "verbatimModuleSyntax": true,
+ "esModuleInterop": true,
+ "forceConsistentCasingInFileNames": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/http-client-python/eng/scripts/ci/regenerate.ts b/packages/http-client-python/eng/scripts/ci/regenerate.ts
index e6c8cee1110..9fdc12b8b52 100644
--- a/packages/http-client-python/eng/scripts/ci/regenerate.ts
+++ b/packages/http-client-python/eng/scripts/ci/regenerate.ts
@@ -40,6 +40,9 @@ const argv = parseArgs({
pluginDir: { type: "string" },
emitterName: { type: "string" },
generatedFolder: { type: "string" },
+ httpSpecsDir: { type: "string" },
+ azureSpecsDir: { type: "string" },
+ "no-baseline": { type: "boolean" },
jobs: { type: "string", short: "j" },
help: { type: "boolean", short: "h" },
},
@@ -70,6 +73,15 @@ ${pc.bold("Options:")}
${pc.cyan("-j, --jobs ")}
Number of parallel compilation tasks (default: 30 on Linux/Mac, 10 on Windows).
+ ${pc.cyan("--httpSpecsDir ")}
+ Override the @typespec/http-specs specs directory (used by emitter-diff).
+
+ ${pc.cyan("--azureSpecsDir ")}
+ Override the @azure-tools/azure-http-specs specs directory (used by emitter-diff).
+
+ ${pc.cyan("--no-baseline")}
+ Skip cloning the published-package baseline tree (used by emitter-diff).
+
${pc.cyan("-h, --help")}
Show this help message.
@@ -94,11 +106,19 @@ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const PLUGIN_DIR = argv.values.pluginDir
? resolve(argv.values.pluginDir)
: resolve(SCRIPT_DIR, "../../../");
-const AZURE_HTTP_SPECS = resolve(PLUGIN_DIR, "node_modules/@azure-tools/azure-http-specs/specs");
-const HTTP_SPECS = resolve(PLUGIN_DIR, "node_modules/@typespec/http-specs/specs");
+const AZURE_HTTP_SPECS = argv.values.azureSpecsDir
+ ? resolve(argv.values.azureSpecsDir)
+ : resolve(PLUGIN_DIR, "node_modules/@azure-tools/azure-http-specs/specs");
+const HTTP_SPECS = argv.values.httpSpecsDir
+ ? resolve(argv.values.httpSpecsDir)
+ : resolve(PLUGIN_DIR, "node_modules/@typespec/http-specs/specs");
const GENERATED_FOLDER = argv.values.generatedFolder
? resolve(argv.values.generatedFolder)
: resolve(PLUGIN_DIR, "generator");
+// Directory that contains `tests/generated//`. Defaults to PLUGIN_DIR (since the
+// default GENERATED_FOLDER is PLUGIN_DIR/generator), but tracks a custom --generatedFolder so
+// the batch Python phase reads the same output tree the TypeScript phase wrote to.
+const GENERATED_PARENT = resolve(GENERATED_FOLDER, "..");
const EMITTER_NAME = argv.values.emitterName || "@typespec/http-client-python";
const ctx: RegenerateContext = {
@@ -152,7 +172,7 @@ function runBatchPythonProcessing(flavor: string, configCount: number, jobs: num
try {
// Pass directory and flavor instead of individual config files to avoid command line length limits on Windows
execSync(
- `"${venvPath}" "${batchScript}" --generated-dir "${PLUGIN_DIR}" --flavor ${flavor} --jobs ${jobs}`,
+ `"${venvPath}" "${batchScript}" --generated-dir "${GENERATED_PARENT}" --flavor ${flavor} --jobs ${jobs}`,
{
stdio: "inherit",
cwd: PLUGIN_DIR,
@@ -256,7 +276,11 @@ async function main() {
const startTime = performance.now();
let success: boolean;
- await prepareBaselineOfGeneratedCode(GENERATED_FOLDER);
+ // `--no-baseline` skips cloning the published-package baseline tree; the
+ // emitter-diff tool generates each side fresh, so the baseline clone is noise.
+ if (!argv.values["no-baseline"]) {
+ await prepareBaselineOfGeneratedCode(GENERATED_FOLDER);
+ }
if (flavor) {
success = await regenerateFlavor(flavor, name, debug, jobs);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0209fdfc111..2c54eb05577 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -288,6 +288,9 @@ catalogs:
decimal.js:
specifier: ^10.6.0
version: 10.6.0
+ diff2html:
+ specifier: ^3.4.48
+ version: 3.4.56
ecmarkup:
specifier: ~23.0.2
version: 23.0.2
@@ -626,6 +629,22 @@ importers:
e2e: {}
+ eng/emitter-diff:
+ dependencies:
+ diff2html:
+ specifier: 'catalog:'
+ version: 3.4.56
+ devDependencies:
+ '@types/node':
+ specifier: 'catalog:'
+ version: 26.0.0
+ tsx:
+ specifier: 'catalog:'
+ version: 4.22.4
+ typescript:
+ specifier: 'catalog:'
+ version: 6.0.3
+
packages/asset-emitter:
devDependencies:
'@types/node':
@@ -6356,6 +6375,10 @@ packages:
'@polka/url@1.0.0-next.29':
resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==}
+ '@profoundlogic/hogan@3.0.4':
+ resolution: {integrity: sha512-pmNVGuooS30Mm7YbZd5T7E5zYVO6D5Ct91sn4T39mUvMUc3sCGridcnhAufL1/Bz2QzAtzEn0agNrdk3+5yWzw==}
+ hasBin: true
+
'@reflink/reflink-darwin-arm64@0.1.19':
resolution: {integrity: sha512-ruy44Lpepdk1FqDz38vExBY/PVUsjxZA+chd9wozjUH9JjuDT/HEaQYA6wYN9mf041l0yLVar6BCZuWABJvHSA==}
engines: {node: '>= 10'}
@@ -9095,6 +9118,10 @@ packages:
devlop@1.1.0:
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
+ diff2html@3.4.56:
+ resolution: {integrity: sha512-u9gfn+BlbHcyO7vItCIC4z49LJDUt31tODzOfAuJ5R1E7IdlRL6KjugcB9zOpejD+XiR+dDZbsnHSQ3g6A/u8A==}
+ engines: {node: '>=12'}
+
diff@5.2.2:
resolution: {integrity: sha512-vtcDfH3TOjP8UekytvnHH1o1P4FcUdt4eQ1Y+Abap1tk/OB2MWQvcwS2ClCd1zuIhc3JKOx6p3kod8Vfys3E+A==}
engines: {node: '>=0.3.1'}
@@ -9906,6 +9933,10 @@ packages:
resolution: {integrity: sha512-EqYpWyTF2s8nMfttfBA2yLKPNoZCO33pLS4MnbXQ4hECf1TKujCt1Kq7QAdrio7roL4+CqsfjqwYj4tYgq0pJQ==}
engines: {node: '>=12.0.0'}
+ highlight.js@11.11.1:
+ resolution: {integrity: sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==}
+ engines: {node: '>=12.0.0'}
+
hosted-git-info@4.1.0:
resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==}
engines: {node: '>=10'}
@@ -18538,6 +18569,10 @@ snapshots:
'@polka/url@1.0.0-next.29': {}
+ '@profoundlogic/hogan@3.0.4':
+ dependencies:
+ nopt: 1.0.10
+
'@reflink/reflink-darwin-arm64@0.1.19':
optional: true
@@ -21757,6 +21792,13 @@ snapshots:
dependencies:
dequal: 2.0.3
+ diff2html@3.4.56:
+ dependencies:
+ '@profoundlogic/hogan': 3.0.4
+ diff: 8.0.4
+ optionalDependencies:
+ highlight.js: 11.11.1
+
diff@5.2.2: {}
diff@8.0.4: {}
@@ -22869,6 +22911,9 @@ snapshots:
highlight.js@11.0.1: {}
+ highlight.js@11.11.1:
+ optional: true
+
hosted-git-info@4.1.0:
dependencies:
lru-cache: 6.0.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 7aa0552c415..fbaa8589069 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -1,5 +1,6 @@
packages:
- packages/*
+ - eng/emitter-diff
- e2e
- website
- "!packages/http-client-csharp/**"
@@ -101,6 +102,7 @@ catalog:
cspell: ^10.0.0
debounce: ^3.0.0
decimal.js: ^10.6.0
+ diff2html: ^3.4.48
ecmarkup: ~23.0.2
env-paths: ^4.0.0
es-module-shims: ^2.8.0
]