| 1 | import { Command } from "commander"; |
| 2 | import semver from "semver"; |
| 3 | import { applySpecDiff, diffSpecs } from "@fig/autocomplete-helpers"; |
| 4 | import { importFromStringSync } from "module-from-string"; |
| 5 | import prettier from "prettier"; |
| 6 | import fs from "fs"; |
| 7 | import ts from "typescript"; |
| 8 | import { build } from "esbuild"; |
| 9 | import path from "path"; |
| 10 | |
| 11 | export const copyDirectorySync = (oldPath: string, newPath: string) => { |
| 12 | if (!fs.existsSync(newPath)) { |
| 13 | fs.mkdirSync(newPath, { recursive: true }); |
| 14 | } |
| 15 | |
| 16 | for (const dirent of fs.readdirSync(oldPath, { withFileTypes: true })) { |
| 17 | if (dirent.isDirectory()) { |
| 18 | copyDirectorySync(path.resolve(oldPath, dirent.name), path.resolve(newPath, dirent.name)); |
| 19 | } else if (dirent.isFile()) { |
| 20 | fs.writeFileSync( |
| 21 | path.resolve(newPath, dirent.name), |
| 22 | fs.readFileSync(path.resolve(oldPath, dirent.name)), |
| 23 | { encoding: "utf8" } |
| 24 | ); |
| 25 | } |
| 26 | } |
| 27 | }; |
| 28 | |
| 29 | const visitFileNodes = (source: ts.SourceFile, visitor: ts.Visitor): ts.Node => |
| 30 | ts.transform(source, [ |
| 31 | (context: ts.TransformationContext) => (rootNode: ts.Node) => { |
| 32 | const visit = (node: ts.Node): ts.VisitResult<ts.Node> => |
| 33 | visitor(ts.visitEachChild(node, visit, context)) as ts.VisitResult<ts.Node>; |
| 34 | return ts.visitNode(rootNode, visit); |
| 35 | }, |
| 36 | ]).transformed[0]; |
| 37 | |
| 38 | const findInFile = <T>(source: ts.SourceFile, predicate: (node: ts.Node) => T | null): T[] => { |
| 39 | const matches: T[] = []; |
| 40 | visitFileNodes(source, (node: ts.Node) => { |
| 41 | // Find a node like "export { versions };" |
| 42 | const match = predicate(node); |
| 43 | if (match !== null) { |
| 44 | matches.push(match); |
| 45 | } |
| 46 | return node; |
| 47 | }); |
| 48 | return matches; |
| 49 | }; |
| 50 | |
| 51 | const formatSource = (source: string | string[]) => |
| 52 | prettier.format(Array.isArray(source) ? source.join("\n") : source, { |
| 53 | parser: "typescript", |
| 54 | }); |
| 55 | |
| 56 | const loadTypescriptModule = async (modulePath: string) => { |
| 57 | const jsString = ( |
| 58 | await build({ |
| 59 | entryPoints: [modulePath], |
| 60 | bundle: true, |
| 61 | write: false, |
| 62 | sourcemap: false, |
| 63 | loader: { ".ts": "ts" }, |
| 64 | keepNames: true, |
| 65 | target: "esnext", |
| 66 | minify: false, |
| 67 | format: "esm", |
| 68 | }) |
| 69 | ).outputFiles[0].text; |
| 70 | return importFromStringSync(jsString, { |
| 71 | dirname: process.cwd(), |
| 72 | }); |
| 73 | }; |
| 74 | |
| 75 | const loadVersionedSpec = async ( |
| 76 | specPath: string, |
| 77 | defaultSpec: Fig.Subcommand |
| 78 | ): Promise<{ |
| 79 | source: string; |
| 80 | spec: Fig.Subcommand; |
| 81 | versions: Fig.VersionDiffMap; |
| 82 | }> => { |
| 83 | if (!fs.existsSync(specPath)) { |
| 84 | // TODO: change the way the spec is printed, currently it won't support js variables |
| 85 | return { |
| 86 | source: await formatSource([ |
| 87 | `const completion: Fig.Subcommand = ${JSON.stringify(defaultSpec, null, 4)}\n`, |
| 88 | `const versions: Fig.VersionDiffMap = {};\n`, |
| 89 | `export { versions };`, |
| 90 | `export default completion`, |
| 91 | ]), |
| 92 | spec: defaultSpec, |
| 93 | versions: {}, |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | const imports = await loadTypescriptModule(specPath); |
| 98 | if (!imports.versions) { |
| 99 | throw new Error("Path does not contain versioned spec"); |
| 100 | } |
| 101 | return { |
| 102 | source: fs.readFileSync(specPath).toString(), |
| 103 | spec: imports.default, |
| 104 | versions: imports.versions, |
| 105 | }; |
| 106 | }; |
| 107 | |
| 108 | async function addVersionToIndex(sourcePath: string, version: string) { |
| 109 | const source = fs.readFileSync(sourcePath).toString(); |
| 110 | let didUpdate = false; |
| 111 | const sourceFile = ts.createSourceFile(sourcePath, source, ts.ScriptTarget.ES2015, true); |
| 112 | const newSource = visitFileNodes(sourceFile, (node: ts.Node): ts.Node => { |
| 113 | if ( |
| 114 | ts.isArrayLiteralExpression(node) && |
| 115 | ts.isVariableDeclaration(node.parent) && |
| 116 | ts.isIdentifier(node.parent.name) && |
| 117 | node.parent.name.escapedText === "versionFiles" |
| 118 | ) { |
| 119 | didUpdate = true; |
| 120 | return ts.factory.updateArrayLiteralExpression(node, [ |
| 121 | ...node.elements, |
| 122 | ts.factory.createStringLiteral(version), |
| 123 | ]); |
| 124 | } |
| 125 | return node; |
| 126 | }); |
| 127 | |
| 128 | if (!didUpdate) { |
| 129 | throw new Error("Failed to add version to index"); |
| 130 | } |
| 131 | |
| 132 | const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); |
| 133 | const result = printer.printNode(ts.EmitHint.Unspecified, newSource, sourceFile); |
| 134 | fs.writeFileSync(sourcePath, await formatSource(result)); |
| 135 | } |
| 136 | |
| 137 | const cleanPath = (p: string) => p.replace(/[^a-zA-Z0-9_\-/.]/, ""); |
| 138 | |
| 139 | async function initVersionedSpec(specName: string, options: { cwd?: string }) { |
| 140 | const cleanedSpecName = cleanPath(specName); |
| 141 | const rootSpecPath = path.resolve(options.cwd ?? process.cwd(), specName); |
| 142 | fs.mkdirSync(rootSpecPath, { recursive: true }); |
| 143 | fs.writeFileSync( |
| 144 | `${rootSpecPath}/index.ts`, |
| 145 | await formatSource( |
| 146 | [ |
| 147 | `import { createVersionedSpec } from "@fig/autocomplete-helpers";\n`, |
| 148 | `const versionFiles = [];\n`, |
| 149 | `export default createVersionedSpec("${cleanedSpecName}", versionFiles);\n`, |
| 150 | ].join("\n") |
| 151 | ) |
| 152 | ); |
| 153 | } |
| 154 | |
| 155 | async function addDiffAction( |
| 156 | specName: string, |
| 157 | newSpecPath: string, |
| 158 | diffVersion: string, |
| 159 | options: { newPath?: string; useMinorBase?: boolean; cwd?: string } |
| 160 | ) { |
| 161 | let folderSpecPath = path.resolve(options.cwd ?? process.cwd(), specName); |
| 162 | if (options.newPath) { |
| 163 | const newPath = path.resolve(options.newPath, specName); |
| 164 | if (fs.existsSync(folderSpecPath)) { |
| 165 | // check that the new path is not a child of the old |
| 166 | const relative = path.relative(folderSpecPath, newPath); |
| 167 | const isSubdirectory = relative && !relative.startsWith("..") && !path.isAbsolute(relative); |
| 168 | if (isSubdirectory) |
| 169 | throw new Error("'--new-path' must not be a sub-directory of the old spec directory"); |
| 170 | copyDirectorySync(folderSpecPath, newPath); |
| 171 | } else { |
| 172 | await initVersionedSpec(specName, { cwd: options.newPath }); |
| 173 | } |
| 174 | folderSpecPath = newPath; |
| 175 | } else if (!fs.existsSync(folderSpecPath)) { |
| 176 | await initVersionedSpec(specName, { cwd: options.cwd }); |
| 177 | } |
| 178 | |
| 179 | const version = semver.parse(diffVersion); |
| 180 | let versionFileName: string; |
| 181 | if (version === null) { |
| 182 | versionFileName = diffVersion; |
| 183 | } else { |
| 184 | versionFileName = options.useMinorBase |
| 185 | ? `${version.major}.${version.minor}.0` |
| 186 | : `${version.major}.0.0`; |
| 187 | } |
| 188 | |
| 189 | const currentSpecPath = path.resolve(folderSpecPath, `${versionFileName}.ts`); |
| 190 | const newSpec = (await loadTypescriptModule(newSpecPath)).default as Fig.Subcommand; |
| 191 | const { source, spec, versions } = await loadVersionedSpec(currentSpecPath, newSpec); |
| 192 | const versionNames = Object.keys(versions).sort(semver.compare); |
| 193 | const lastVersion = versionNames[versionNames.length - 1]; |
| 194 | if (lastVersion && semver.compare(diffVersion, lastVersion) <= 0) { |
| 195 | throw new Error( |
| 196 | `Cannot publish version ${diffVersion}, later version ${lastVersion} already exists` |
| 197 | ); |
| 198 | } |
| 199 | const latestSpec = versionNames.map((name) => versions[name]).reduce(applySpecDiff, spec); |
| 200 | const diff = diffSpecs(latestSpec, newSpec) ?? {}; |
| 201 | |
| 202 | const versionExports = findInFile( |
| 203 | ts.createSourceFile(currentSpecPath, source, ts.ScriptTarget.ES2015, true), |
| 204 | (node: ts.Node) => { |
| 205 | if (ts.isExportSpecifier(node) && node.name.escapedText === "versions") { |
| 206 | return node.parent.parent; |
| 207 | } |
| 208 | return null; |
| 209 | } |
| 210 | ); |
| 211 | if (versionExports.length === 0) { |
| 212 | throw new Error("No version export found"); |
| 213 | } |
| 214 | const insertIdx = versionExports[versionExports.length - 1].getStart(); |
| 215 | if (!fs.existsSync(currentSpecPath)) { |
| 216 | addVersionToIndex(path.resolve(folderSpecPath, "index.ts"), versionFileName); |
| 217 | } |
| 218 | fs.writeFileSync( |
| 219 | currentSpecPath, |
| 220 | await formatSource([ |
| 221 | source.slice(0, insertIdx), |
| 222 | `\nversions["${diffVersion}"] = ${JSON.stringify(diff, null, 4)}\n`, |
| 223 | source.slice(insertIdx), |
| 224 | ]) |
| 225 | ); |
| 226 | } |
| 227 | |
| 228 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 229 | async function precomputeAction(files: string[]) { |
| 230 | /* |
| 231 | for (let file in files) { |
| 232 | // For each spec file, check if it is versioned and if so precompute |
| 233 | // spec files for each version. |
| 234 | } |
| 235 | */ |
| 236 | throw new Error("Unimplemented"); |
| 237 | } |
| 238 | |
| 239 | export default new Command("version") |
| 240 | .addCommand( |
| 241 | new Command("add-diff") |
| 242 | .arguments("<specName> <newSpecFilePath> <diffVersion>") |
| 243 | .description("generate version diff from new spec and add into old spec") |
| 244 | .option( |
| 245 | "-n, --new-path <path>", |
| 246 | "The root folder where the updated spec will be saved. Note: this must NOT include the folder spec name" |
| 247 | ) |
| 248 | .option("--cwd <path>", "Resolve the spec name relative to this directory") |
| 249 | .option("--use-minor-base", "Create a new version file per minor version") |
| 250 | .action(addDiffAction) |
| 251 | ) |
| 252 | .addCommand( |
| 253 | new Command("init-spec") |
| 254 | .arguments("<name>") |
| 255 | .option("--cwd <path>", "Generate the spec relative to this directory") |
| 256 | .description("Generate versioned spec in folder specified by path") |
| 257 | .action(initVersionedSpec) |
| 258 | ) |
| 259 | .addCommand( |
| 260 | new Command("precompute-specs") |
| 261 | .arguments("<files...>") |
| 262 | .description( |
| 263 | "[Unimplemented] Precompute versioned specs before publishing the specs repo (unimplemented)" |
| 264 | ) |
| 265 | .action(precomputeAction) |
| 266 | ); |