-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.ts
More file actions
88 lines (77 loc) · 2.81 KB
/
Copy pathdiff.ts
File metadata and controls
88 lines (77 loc) · 2.81 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
import { preprocessOASDocument } from "@patchlogr/adapter-oas";
import {
detectVersionBump,
diffSpec,
partitionByMethod,
partitionByTag,
type PartitionedSpec,
} from "@patchlogr/core";
import { Command } from "commander";
import { type OpenAPI } from "openapi-types";
import fs from "fs/promises";
export type DiffOptions = {
partition: "tag" | "method";
output?: "stdout" | string;
skipValidation: boolean;
};
export const diffCommand = new Command("diff")
.description("Diff two OpenAPI Specification files")
.argument("<base>", "Base OpenAPI Specification file")
.argument("<head>", "Head OpenAPI Specification file")
.option("-o, --output <file>", "Output file")
.option("--skipValidation", "Skip validation", true)
.option("-p, --partition <partition>", "Partition Strategy", "tag")
.action(diffAction);
export async function diffAction(
basePath: OpenAPI.Document,
headPath: OpenAPI.Document,
options: DiffOptions,
) {
const preprocessedBase = await preprocessOASDocument(basePath, {
skipValidation: options.skipValidation,
});
const preprocessedHead = await preprocessOASDocument(headPath, {
skipValidation: options.skipValidation,
});
const baseCanonicalSpec = preprocessedBase.canonicalSpec;
const headCanonicalSpec = preprocessedHead.canonicalSpec;
if (!baseCanonicalSpec || !headCanonicalSpec) {
throw new Error("Failed to preprocess OpenAPI Specification files");
}
let partitionedBase: PartitionedSpec;
let partitionedHead: PartitionedSpec;
switch (options.partition) {
case "method":
partitionedBase = partitionByMethod(baseCanonicalSpec);
partitionedHead = partitionByMethod(headCanonicalSpec);
break;
case "tag":
default:
partitionedBase = partitionByTag(baseCanonicalSpec);
partitionedHead = partitionByTag(headCanonicalSpec);
break;
}
const specChangeSet = diffSpec(partitionedBase, partitionedHead);
const versionBump = detectVersionBump(specChangeSet);
if (options.output === "stdout" || options.output === undefined) {
console.log(JSON.stringify(specChangeSet, null, 2));
console.log(JSON.stringify(versionBump, null, 2));
} else {
try {
await fs.writeFile(
options.output.concat(".json"),
JSON.stringify(specChangeSet, null, 2),
"utf-8",
);
await fs.writeFile(
options.output.concat(".version.json"),
JSON.stringify(versionBump, null, 2),
"utf-8",
);
} catch (error) {
throw new Error(`Failed to write to file ${options.output}:`, {
cause: error,
});
}
}
}