@ohos-ports/withfig-autocomplete-tools 0.0.0-stage → 2.11.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/build/bin.js +59 -0
- package/build/index.d.ts +4 -0
- package/build/index.js +20 -0
- package/build/scripts/compile.d.ts +7 -0
- package/build/scripts/compile.js +100 -0
- package/build/scripts/create-spec.d.ts +3 -0
- package/build/scripts/create-spec.js +33 -0
- package/build/scripts/dev.d.ts +3 -0
- package/build/scripts/dev.js +68 -0
- package/build/scripts/init.d.ts +3 -0
- package/build/scripts/init.js +6 -0
- package/build/scripts/log.d.ts +15 -0
- package/build/scripts/log.js +22 -0
- package/build/scripts/merge.d.ts +3 -0
- package/build/scripts/merge.js +28 -0
- package/build/scripts/settings.d.ts +5 -0
- package/build/scripts/settings.js +42 -0
- package/build/scripts/transformer.d.ts +8 -0
- package/build/scripts/transformer.js +33 -0
- package/build/scripts/version.d.ts +4 -0
- package/build/scripts/version.js +204 -0
- package/package.json +63 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Hercules Labs Inc. (Fig)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@withfig/autocomplete-tools`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `@withfig/autocomplete-tools` is a CLI used to build and manage the withfig/autocomplete repo.
|
package/build/bin.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{Command as qe}from"commander";import O from"node:fs";import{Command as re,Option as ie}from"commander";import{merge as se,presets as ae}from"@fig/autocomplete-merge";async function ce(e,o,t){let{ignoreProps:n=[],ignoreCommandProps:r=[],ignoreOptionProps:s=[],ignoreArgProps:i=[],newFile:m,preset:l}=t,b=await se(O.readFileSync(e,{encoding:"utf8"}),O.readFileSync(o,{encoding:"utf8"}),{preset:l,ignore:{commonProps:n,commandProps:r,optionProps:s,argProps:i}});O.writeFileSync(m||e,b)}var T=new re("merge").arguments("<oldspec> <newspec>").description("deep merge new spec into old spec").option("-n, --new-file <path>","Create a new spec file instead of updating the old one").option("-i, --ignore-props <props>","The props that should always be overridden.",e=>e.split(",")).option("--ignore-command-props <props>","The command props that should always be overridden.",e=>e.split(",")).option("--ignore-option-props <props>","The option props that should always be overridden.",e=>e.split(",")).option("--ignore-arg-props <props>","The arg props that should always be overridden.",e=>e.split(",")),pe=new ie("-p, --preset <name>","Use a preset").choices(Object.keys(ae));T.addOption(pe);T.action(ce);var U=T;import N from"node:os";import f from"node:fs";import F from"node:path";import a from"chalk";import{Command as Ne}from"commander";import h from"node:fs/promises";import ue from"node:fs";import y from"node:path";import{build as ge}from"@ohos-ports/esbuild";import{NodeModulesPolyfillPlugin as we}from"@esbuild-plugins/node-modules-polyfill";import ye from"chokidar";import{Command as he}from"commander";import Se from"fast-glob";import le from"chalk";var S=class{static log(o,t="blue"){console.log(le[t](o))}};import{execFileSync as de}from"node:child_process";function v(e,o){try{return de(e,o),!0}catch{return!1}}var L;function me(){return L===void 0&&(L=v("fig",["--version"])),L}var j;function fe(){return j===void 0&&(j=v("cw",["--version"])),j}var M;function D(){return M===void 0&&(M=v("q",["--version"])),M}function w(e,o){D()?v("q",["settings",e,JSON.stringify(o)]):fe()?v("cw",["settings",e,JSON.stringify(o)]):me()&&v("fig",["settings",e,JSON.stringify(o)])}var ve="src",J="build";function Fe(){w("autocomplete.developerModeNPMInvalidateCache",!0)}async function xe(e,o){let t=o.map(y.parse),n=t.filter(({base:i})=>i==="index.ts").map(({dir:i})=>i.replace(/^src\//,""));n.sort();let r=t.filter(({base:i,ext:m})=>i!=="index.ts"&&m===".ts").map(i=>`${i.dir}/${i.name}`.replace(/^src\//,"")).concat(n);r.sort();let s=o.filter(i=>ue.statSync(i).isFile()).map(y.parse).map(i=>`${i.dir}/${i.name}`.replace(/^src\//,""));await h.mkdir(e,{recursive:!0}),await h.mkdir(y.join(e,"dynamic"),{recursive:!0}),await h.writeFile(y.join(e,"index.js"),`var e=${JSON.stringify(r)},diffVersionedCompletions=${JSON.stringify(n)};export{e as default,diffVersionedCompletions};`),await h.writeFile(y.join(e,"index.json"),JSON.stringify({completions:r,diffVersionedCompletions:n})),await h.writeFile(y.join(e,"index.d.ts"),`declare const completions: string[]
|
|
3
|
+
declare const diffVersionedCompletions: string[]
|
|
4
|
+
export { completions as default, diffVersionedCompletions }
|
|
5
|
+
`),await h.writeFile(y.join(e,"dynamic/index.js"),`var e={${s.map(i=>`${JSON.stringify(i)}:()=>import(${JSON.stringify(`../${i}.js`)})`).join(",")}};export{e as default};`),await h.writeFile(y.join(e,"dynamic/index.d.ts"),`declare const completions: {
|
|
6
|
+
[key: string]: () => Promise<{
|
|
7
|
+
default: any;
|
|
8
|
+
}>
|
|
9
|
+
}
|
|
10
|
+
export { completions as default }
|
|
11
|
+
`)}async function R(e,o,t){let n=e.length===1?e[0]:`${e.length} specs`;await Promise.all([ge({entryPoints:e,outdir:t??J,bundle:!0,outbase:"src",format:"esm",minify:!0,plugins:[we()],...o&&{sourcemap:"inline"}}).catch(r=>S.log(`Error building ${n}: ${r.message}`,"red")),xe(t??J,e)]),S.log(`Built ${n}`),Fe()}async function _({watch:e,outdir:o}){let t=`${ve}/**/*.ts`,n=await Se(t);if(await R(n,void 0,o),e){let r=ye.watch(t,{ignoreInitial:!0});r.on("change",s=>R([s],!0,o)),r.on("add",s=>R([s],!0,o))}}var be=new he("compile").description("compile specs in the current directory").option("-w, --watch","Watch files and re-compile on change").option("-o, --outdir <dir>","Output directory").action(_),W=be;var x=F.join(N.homedir(),".fig","logs","specs.log");function Ce(){console.log(`
|
|
12
|
+
|
|
13
|
+
Fig dev mode disabled
|
|
14
|
+
`),w("autocomplete.developerMode",!1),w("autocomplete.developerModeNPM",!1),w("autocomplete.developerModeNPMInvalidateCache",!0),process.exit(0)}function k(){Ce(),f.unwatchFile(x)}async function Ae({outdir:e}){if(console.clear(),N.type()==="Darwin"){let t="/Applications/Fig.app",n=F.join(N.homedir(),"Applications/Fig.app"),r="/Applications/Amazon Q.app",s=F.join(N.homedir(),"Applications/Amazon Q.app");!f.existsSync(t)&&!f.existsSync(n)&&!f.existsSync(r)&&!f.existsSync(s)&&console.log(`
|
|
15
|
+
******
|
|
16
|
+
|
|
17
|
+
`,a.bold(a.yellow(" WARNING: Amazon Q for command line app is not installed")),`
|
|
18
|
+
|
|
19
|
+
`,a.bold(a.cyan(" Download Amazon Q for command line at:")),`
|
|
20
|
+
https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-getting-started-installing.html`,`
|
|
21
|
+
|
|
22
|
+
******
|
|
23
|
+
`)}else N.type()==="Linux"?console.log(`
|
|
24
|
+
******
|
|
25
|
+
|
|
26
|
+
`,a.bold(a.yellow(" WARNING: Amazon Q for command line on Linux is not supported yet")),`
|
|
27
|
+
|
|
28
|
+
`):D()||console.log(`
|
|
29
|
+
******
|
|
30
|
+
|
|
31
|
+
`,a.bold(a.yellow(" WARNING: Amazon Q for command line is not installed")),`
|
|
32
|
+
|
|
33
|
+
`,a.bold(a.cyan(" Download Amazon Q for command line at:")),`
|
|
34
|
+
https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-getting-started-installing.html`,`
|
|
35
|
+
|
|
36
|
+
******
|
|
37
|
+
`);console.log(`Welcome to ${a.magenta("Fig Dev Mode")}!
|
|
38
|
+
|
|
39
|
+
`,`All completions will be loaded from ${a.bold(`${process.cwd()}/${e??"build"}`)}. (Note: other completions won't work while in dev mode).
|
|
40
|
+
|
|
41
|
+
`,`1. Edit your spec(s) in the ${a.bold("src/")} directory.
|
|
42
|
+
`,`2. Test changes ${a.bold("instantly")} on save in your terminal.
|
|
43
|
+
`,`3. Exit developer mode with ${a.bold("ctrl + c")}.
|
|
44
|
+
|
|
45
|
+
`,`${a.bold("Other Notes:")}
|
|
46
|
+
`,`- Generators run on every keystroke
|
|
47
|
+
`),process.addListener("SIGTERM",k),process.addListener("SIGINT",k),process.addListener("SIGQUIT",k),w("autocomplete.developerModeNPM",!0),w("autocomplete.devCompletionsFolder",F.join(process.cwd(),e??"build").replace(/(\s)/g,"\\$1")),f.existsSync(F.dirname(x))||f.mkdirSync(F.dirname(x),{recursive:!0}),f.writeFileSync(x,"",{encoding:"utf8"});let o="";f.watch(x,t=>{if(t==="change"){let n=f.readFileSync(x,{encoding:"utf8"}).trim(),r=o?n.split(`
|
|
48
|
+
`).slice(o.split(`
|
|
49
|
+
`).length).join(`
|
|
50
|
+
`):n;console.log(a.yellow(r)),o=n}}),await _({watch:!0,outdir:e})}var Ee=new Ne("dev").description("watch for changes and compile specs").option("-o, --outdir <dir>","Output directory").action(Ae),q=Ee;import Ie from"node:path";import Pe from"node:readline";import{createCompletionSpec as B}from"create-completion-spec";import{Command as $e}from"commander";import Oe from"chalk";var Te=new $e("create-spec").description("create spec with given name").arguments("[name]").action(e=>{let o=Ie.resolve(process.cwd(),"src");if(e)B(e,o);else{let t=Pe.createInterface({input:process.stdin,output:process.stdout});t.question("What's the name of the CLI tool you want to create an autocomplete spec for: ",async n=>{try{B(n,o)}catch(r){console.log(Oe.red(r.message)),process.exit(1)}finally{t.close()}})}}),H=Te;import{createBoilerplateFolder as Le}from"create-completion-spec";import{Command as je}from"commander";var Me=new je("init").description("initialize fig custom spec boilerplate in current directory").action(Le),K=Me;import p from"node:fs";import d from"node:path";import{Command as C}from"commander";import V from"semver";import{applySpecDiff as De,diffSpecs as Re}from"@fig/autocomplete-helpers";import{importFromStringSync as _e}from"@ohos-ports/module-from-string";import ke from"prettier";import c from"@ohos-ports/typescript";import{build as Ve}from"@ohos-ports/esbuild";var Z=(e,o)=>{p.existsSync(o)||p.mkdirSync(o,{recursive:!0});for(let t of p.readdirSync(e,{withFileTypes:!0}))t.isDirectory()?Z(d.resolve(e,t.name),d.resolve(o,t.name)):t.isFile()&&p.writeFileSync(d.resolve(o,t.name),p.readFileSync(d.resolve(e,t.name)),{encoding:"utf8"})},X=(e,o)=>c.transform(e,[t=>n=>{let r=s=>o(c.visitEachChild(s,r,t));return c.visitNode(n,r)}]).transformed[0],ze=(e,o)=>{let t=[];return X(e,n=>{let r=o(n);return r!==null&&t.push(r),n}),t},A=e=>ke.format(Array.isArray(e)?e.join(`
|
|
51
|
+
`):e,{parser:"typescript"}),Y=async e=>{let o=(await Ve({entryPoints:[e],bundle:!0,write:!1,sourcemap:!1,loader:{".ts":"ts"},keepNames:!0,target:"esnext",minify:!1,format:"esm"})).outputFiles[0].text;return _e(o,{dirname:process.cwd()})},Qe=async(e,o)=>{if(!p.existsSync(e))return{source:await A([`const completion: Fig.Subcommand = ${JSON.stringify(o,null,4)}
|
|
52
|
+
`,`const versions: Fig.VersionDiffMap = {};
|
|
53
|
+
`,"export { versions };","export default completion"]),spec:o,versions:{}};let t=await Y(e);if(!t.versions)throw new Error("Path does not contain versioned spec");return{source:p.readFileSync(e).toString(),spec:t.default,versions:t.versions}};async function Ge(e,o){let t=p.readFileSync(e).toString(),n=!1,r=c.createSourceFile(e,t,c.ScriptTarget.ES2015,!0),s=X(r,l=>c.isArrayLiteralExpression(l)&&c.isVariableDeclaration(l.parent)&&c.isIdentifier(l.parent.name)&&l.parent.name.escapedText==="versionFiles"?(n=!0,c.factory.updateArrayLiteralExpression(l,[...l.elements,c.factory.createStringLiteral(o)])):l);if(!n)throw new Error("Failed to add version to index");let m=c.createPrinter({newLine:c.NewLineKind.LineFeed}).printNode(c.EmitHint.Unspecified,s,r);p.writeFileSync(e,await A(m))}var Ue=e=>e.replace(/[^a-zA-Z0-9_\-/.]/,"");async function z(e,o){let t=Ue(e),n=d.resolve(o.cwd??process.cwd(),e);p.mkdirSync(n,{recursive:!0}),p.writeFileSync(`${n}/index.ts`,await A([`import { createVersionedSpec } from "@fig/autocomplete-helpers";
|
|
54
|
+
`,`const versionFiles = [];
|
|
55
|
+
`,`export default createVersionedSpec("${t}", versionFiles);
|
|
56
|
+
`].join(`
|
|
57
|
+
`)))}async function Je(e,o,t,n){let r=d.resolve(n.cwd??process.cwd(),e);if(n.newPath){let u=d.resolve(n.newPath,e);if(p.existsSync(r)){let $=d.relative(r,u);if($&&!$.startsWith("..")&&!d.isAbsolute($))throw new Error("'--new-path' must not be a sub-directory of the old spec directory");Z(r,u)}else await z(e,{cwd:n.newPath});r=u}else p.existsSync(r)||await z(e,{cwd:n.cwd});let s=V.parse(t),i;s===null?i=t:i=n.useMinorBase?`${s.major}.${s.minor}.0`:`${s.major}.0.0`;let m=d.resolve(r,`${i}.ts`),l=(await Y(o)).default,{source:b,spec:oe,versions:Q}=await Qe(m,l),E=Object.keys(Q).sort(V.compare),I=E[E.length-1];if(I&&V.compare(t,I)<=0)throw new Error(`Cannot publish version ${t}, later version ${I} already exists`);let te=E.map(u=>Q[u]).reduce(De,oe),ne=Re(te,l)??{},P=ze(c.createSourceFile(m,b,c.ScriptTarget.ES2015,!0),u=>c.isExportSpecifier(u)&&u.name.getText()==="versions"?u.parent.parent:null);if(P.length===0)throw new Error("No version export found");let G=P[P.length-1].getStart();p.existsSync(m)||Ge(d.resolve(r,"index.ts"),i),p.writeFileSync(m,await A([b.slice(0,G),`
|
|
58
|
+
versions["${t}"] = ${JSON.stringify(ne,null,4)}
|
|
59
|
+
`,b.slice(G)]))}async function We(e){throw new Error("Unimplemented")}var ee=new C("version").addCommand(new C("add-diff").arguments("<specName> <newSpecFilePath> <diffVersion>").description("generate version diff from new spec and add into old spec").option("-n, --new-path <path>","The root folder where the updated spec will be saved. Note: this must NOT include the folder spec name").option("--cwd <path>","Resolve the spec name relative to this directory").option("--use-minor-base","Create a new version file per minor version").action(Je)).addCommand(new C("init-spec").arguments("<name>").option("--cwd <path>","Generate the spec relative to this directory").description("Generate versioned spec in folder specified by path").action(z)).addCommand(new C("precompute-specs").arguments("<files...>").description("[Unimplemented] Precompute versioned specs before publishing the specs repo (unimplemented)").action(We));var g=new qe;g.name("@withfig/autocomplete-tools").description("Dev tools for fig's autocomplete").version("1.0.0");g.addCommand(K);g.addCommand(H);g.addCommand(W);g.addCommand(q);g.addCommand(U);g.addCommand(ee);g.parse(process.argv);
|
package/build/index.d.ts
ADDED
package/build/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import merge from "./scripts/merge";
|
|
4
|
+
import dev from "./scripts/dev";
|
|
5
|
+
import createSpec from "./scripts/create-spec";
|
|
6
|
+
import compile from "./scripts/compile";
|
|
7
|
+
import init from "./scripts/init";
|
|
8
|
+
import version from "./scripts/version";
|
|
9
|
+
const program = new Command();
|
|
10
|
+
program
|
|
11
|
+
.name("@withfig/autocomplete-tools")
|
|
12
|
+
.description("Dev tools for fig's autocomplete")
|
|
13
|
+
.version("1.0.0");
|
|
14
|
+
program.addCommand(init);
|
|
15
|
+
program.addCommand(createSpec);
|
|
16
|
+
program.addCommand(compile);
|
|
17
|
+
program.addCommand(dev);
|
|
18
|
+
program.addCommand(merge);
|
|
19
|
+
program.addCommand(version);
|
|
20
|
+
export { program };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import fsSync from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { build } from "@ohos-ports/esbuild";
|
|
5
|
+
import { NodeModulesPolyfillPlugin } from "@esbuild-plugins/node-modules-polyfill";
|
|
6
|
+
import chokidar from "chokidar";
|
|
7
|
+
import { Command } from "commander";
|
|
8
|
+
import glob from "fast-glob";
|
|
9
|
+
import SpecLogger, { Level } from "./log";
|
|
10
|
+
import { setSetting } from "./settings";
|
|
11
|
+
// Folder names
|
|
12
|
+
const SOURCE_FOLDER_NAME = "src";
|
|
13
|
+
const DEFAULT_DESTINATION_FOLDER_NAME = "build";
|
|
14
|
+
function invalidateCache() {
|
|
15
|
+
setSetting("autocomplete.developerModeNPMInvalidateCache", true);
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Generate index files for spec build
|
|
19
|
+
*/
|
|
20
|
+
async function generateIndex(outdir, files) {
|
|
21
|
+
const parsedFiles = files.map(path.parse);
|
|
22
|
+
const diffVersionedSpecNames = parsedFiles
|
|
23
|
+
.filter(({ base }) => base === "index.ts")
|
|
24
|
+
.map(({ dir }) => dir.replace(/^src\//, ""));
|
|
25
|
+
diffVersionedSpecNames.sort();
|
|
26
|
+
const specNames = parsedFiles
|
|
27
|
+
.filter(({ base, ext }) => base !== "index.ts" && ext === ".ts")
|
|
28
|
+
.map((p) => `${p.dir}/${p.name}`.replace(/^src\//, ""))
|
|
29
|
+
.concat(diffVersionedSpecNames);
|
|
30
|
+
specNames.sort();
|
|
31
|
+
const modules = files
|
|
32
|
+
.filter((p) => fsSync.statSync(p).isFile())
|
|
33
|
+
.map(path.parse)
|
|
34
|
+
.map((p) => `${p.dir}/${p.name}`.replace(/^src\//, ""));
|
|
35
|
+
await fs.mkdir(outdir, { recursive: true });
|
|
36
|
+
await fs.mkdir(path.join(outdir, "dynamic"), { recursive: true });
|
|
37
|
+
// index.js
|
|
38
|
+
await fs.writeFile(path.join(outdir, "index.js"), `var e=${JSON.stringify(specNames)},diffVersionedCompletions=${JSON.stringify(diffVersionedSpecNames)};export{e as default,diffVersionedCompletions};`);
|
|
39
|
+
// index.json
|
|
40
|
+
await fs.writeFile(path.join(outdir, "index.json"), JSON.stringify({
|
|
41
|
+
completions: specNames,
|
|
42
|
+
diffVersionedCompletions: diffVersionedSpecNames,
|
|
43
|
+
}));
|
|
44
|
+
// index.d.ts
|
|
45
|
+
await fs.writeFile(path.join(outdir, "index.d.ts"), `declare const completions: string[]
|
|
46
|
+
declare const diffVersionedCompletions: string[]
|
|
47
|
+
export { completions as default, diffVersionedCompletions }
|
|
48
|
+
`);
|
|
49
|
+
// dynamic/index.js
|
|
50
|
+
await fs.writeFile(path.join(outdir, "dynamic/index.js"), `var e={${modules
|
|
51
|
+
.map((mod) => `${JSON.stringify(mod)}:()=>import(${JSON.stringify(`../${mod}.js`)})`)
|
|
52
|
+
.join(",")}};export{e as default};`);
|
|
53
|
+
// dynamic/index.d.ts
|
|
54
|
+
await fs.writeFile(path.join(outdir, "dynamic/index.d.ts"), `declare const completions: {
|
|
55
|
+
[key: string]: () => Promise<{
|
|
56
|
+
default: any;
|
|
57
|
+
}>
|
|
58
|
+
}
|
|
59
|
+
export { completions as default }
|
|
60
|
+
`);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Transpiles all passed files and prints the progress
|
|
64
|
+
* @param specs Array of filepaths
|
|
65
|
+
*/
|
|
66
|
+
async function processFiles(files, isDev, outdir) {
|
|
67
|
+
const fileName = files.length === 1 ? files[0] : `${files.length} specs`;
|
|
68
|
+
await Promise.all([
|
|
69
|
+
build({
|
|
70
|
+
entryPoints: files,
|
|
71
|
+
outdir: outdir ?? DEFAULT_DESTINATION_FOLDER_NAME,
|
|
72
|
+
bundle: true,
|
|
73
|
+
outbase: "src",
|
|
74
|
+
format: "esm",
|
|
75
|
+
minify: true,
|
|
76
|
+
plugins: [NodeModulesPolyfillPlugin()],
|
|
77
|
+
...(isDev && { sourcemap: "inline" }),
|
|
78
|
+
}).catch((e) => SpecLogger.log(`Error building ${fileName}: ${e.message}`, Level.ERROR)),
|
|
79
|
+
generateIndex(outdir ?? DEFAULT_DESTINATION_FOLDER_NAME, files),
|
|
80
|
+
]);
|
|
81
|
+
SpecLogger.log(`Built ${fileName}`);
|
|
82
|
+
invalidateCache();
|
|
83
|
+
}
|
|
84
|
+
export async function runCompiler({ watch, outdir }) {
|
|
85
|
+
const SOURCE_FILE_GLOB = `${SOURCE_FOLDER_NAME}/**/*.ts`;
|
|
86
|
+
const files = await glob(SOURCE_FILE_GLOB);
|
|
87
|
+
await processFiles(files, undefined, outdir);
|
|
88
|
+
if (watch) {
|
|
89
|
+
const watcher = chokidar.watch(SOURCE_FILE_GLOB, { ignoreInitial: true });
|
|
90
|
+
// Process the changed file
|
|
91
|
+
watcher.on("change", (file) => processFiles([file], true, outdir));
|
|
92
|
+
watcher.on("add", (file) => processFiles([file], true, outdir));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const program = new Command("compile")
|
|
96
|
+
.description("compile specs in the current directory")
|
|
97
|
+
.option("-w, --watch", "Watch files and re-compile on change")
|
|
98
|
+
.option("-o, --outdir <dir>", "Output directory")
|
|
99
|
+
.action(runCompiler);
|
|
100
|
+
export default program;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import readline from "node:readline";
|
|
3
|
+
import { createCompletionSpec } from "create-completion-spec";
|
|
4
|
+
import { Command } from "commander";
|
|
5
|
+
import chalk from "chalk";
|
|
6
|
+
const program = new Command("create-spec")
|
|
7
|
+
.description("create spec with given name")
|
|
8
|
+
.arguments("[name]")
|
|
9
|
+
.action((specName) => {
|
|
10
|
+
const autocompleteFolder = path.resolve(process.cwd(), "src");
|
|
11
|
+
if (!specName) {
|
|
12
|
+
const rInterface = readline.createInterface({
|
|
13
|
+
input: process.stdin,
|
|
14
|
+
output: process.stdout,
|
|
15
|
+
});
|
|
16
|
+
rInterface.question("What's the name of the CLI tool you want to create an autocomplete spec for: ", async (answer) => {
|
|
17
|
+
try {
|
|
18
|
+
createCompletionSpec(answer, autocompleteFolder);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
console.log(chalk.red(error.message));
|
|
22
|
+
process.exit(1);
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
rInterface.close();
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
createCompletionSpec(specName, autocompleteFolder);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
export default program;
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import os from "node:os";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import chalk from "chalk";
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import { runCompiler } from "./compile";
|
|
7
|
+
import { isQInstalled, setSetting } from "./settings";
|
|
8
|
+
const AUTOCOMPLETE_LOG_FILE = path.join(os.homedir(), ".fig", "logs", "specs.log");
|
|
9
|
+
function disableDevMode() {
|
|
10
|
+
console.log("\n\nFig dev mode disabled\n");
|
|
11
|
+
setSetting("autocomplete.developerMode", false);
|
|
12
|
+
setSetting("autocomplete.developerModeNPM", false);
|
|
13
|
+
setSetting("autocomplete.developerModeNPMInvalidateCache", true);
|
|
14
|
+
process.exit(0);
|
|
15
|
+
}
|
|
16
|
+
function cleanup() {
|
|
17
|
+
disableDevMode();
|
|
18
|
+
fs.unwatchFile(AUTOCOMPLETE_LOG_FILE);
|
|
19
|
+
}
|
|
20
|
+
async function runProgram({ outdir }) {
|
|
21
|
+
console.clear();
|
|
22
|
+
if (os.type() === "Darwin") {
|
|
23
|
+
const globalFigAppPath = "/Applications/Fig.app";
|
|
24
|
+
const localFigAppPath = path.join(os.homedir(), "Applications/Fig.app");
|
|
25
|
+
const globalQAppPath = "/Applications/Amazon Q.app";
|
|
26
|
+
const localQAppPath = path.join(os.homedir(), "Applications/Amazon Q.app");
|
|
27
|
+
if (!fs.existsSync(globalFigAppPath) &&
|
|
28
|
+
!fs.existsSync(localFigAppPath) &&
|
|
29
|
+
!fs.existsSync(globalQAppPath) &&
|
|
30
|
+
!fs.existsSync(localQAppPath)) {
|
|
31
|
+
console.log("\n******\n\n", chalk.bold(chalk.yellow(" WARNING: Amazon Q for command line app is not installed")), "\n\n", chalk.bold(chalk.cyan(" Download Amazon Q for command line at:")), "\n https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-getting-started-installing.html", "\n\n******\n");
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
else if (os.type() === "Linux") {
|
|
35
|
+
console.log("\n******\n\n", chalk.bold(chalk.yellow(" WARNING: Amazon Q for command line on Linux is not supported yet")), "\n\n");
|
|
36
|
+
}
|
|
37
|
+
else if (!isQInstalled()) {
|
|
38
|
+
console.log("\n******\n\n", chalk.bold(chalk.yellow(" WARNING: Amazon Q for command line is not installed")), "\n\n", chalk.bold(chalk.cyan(" Download Amazon Q for command line at:")), "\n https://docs.aws.amazon.com/amazonq/latest/qdeveloper-ug/command-line-getting-started-installing.html", "\n\n******\n");
|
|
39
|
+
}
|
|
40
|
+
console.log(`Welcome to ${chalk.magenta("Fig Dev Mode")}!\n\n`, `All completions will be loaded from ${chalk.bold(`${process.cwd()}/${outdir ?? "build"}`)}. (Note: other completions won't work while in dev mode).\n\n`, `1. Edit your spec(s) in the ${chalk.bold("src/")} directory.\n`, `2. Test changes ${chalk.bold("instantly")} on save in your terminal.\n`, `3. Exit developer mode with ${chalk.bold("ctrl + c")}.\n\n`, `${chalk.bold("Other Notes:")}\n`, `- Generators run on every keystroke\n`);
|
|
41
|
+
// We are on macos and the fig script exists
|
|
42
|
+
process.addListener("SIGTERM", cleanup);
|
|
43
|
+
process.addListener("SIGINT", cleanup);
|
|
44
|
+
process.addListener("SIGQUIT", cleanup);
|
|
45
|
+
setSetting("autocomplete.developerModeNPM", true);
|
|
46
|
+
setSetting("autocomplete.devCompletionsFolder", path.join(process.cwd(), outdir ?? "build").replace(/(\s)/g, "\\$1"));
|
|
47
|
+
if (!fs.existsSync(path.dirname(AUTOCOMPLETE_LOG_FILE))) {
|
|
48
|
+
fs.mkdirSync(path.dirname(AUTOCOMPLETE_LOG_FILE), { recursive: true });
|
|
49
|
+
}
|
|
50
|
+
fs.writeFileSync(AUTOCOMPLETE_LOG_FILE, "", { encoding: "utf8" });
|
|
51
|
+
let previousLogContent = "";
|
|
52
|
+
fs.watch(AUTOCOMPLETE_LOG_FILE, (event) => {
|
|
53
|
+
if (event === "change") {
|
|
54
|
+
const currentContent = fs.readFileSync(AUTOCOMPLETE_LOG_FILE, { encoding: "utf8" }).trim();
|
|
55
|
+
const message = previousLogContent
|
|
56
|
+
? currentContent.split("\n").slice(previousLogContent.split("\n").length).join("\n")
|
|
57
|
+
: currentContent;
|
|
58
|
+
console.log(chalk.yellow(message));
|
|
59
|
+
previousLogContent = currentContent;
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
await runCompiler({ watch: true, outdir });
|
|
63
|
+
}
|
|
64
|
+
const program = new Command("dev")
|
|
65
|
+
.description("watch for changes and compile specs")
|
|
66
|
+
.option("-o, --outdir <dir>", "Output directory")
|
|
67
|
+
.action(runProgram);
|
|
68
|
+
export default program;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createBoilerplateFolder } from "create-completion-spec";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
const program = new Command("init")
|
|
4
|
+
.description("initialize fig custom spec boilerplate in current directory")
|
|
5
|
+
.action(createBoilerplateFolder);
|
|
6
|
+
export default program;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export declare enum Level {
|
|
2
|
+
INFO = "blue",
|
|
3
|
+
ERROR = "red",
|
|
4
|
+
SUCCESS = "green"
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Log a message in the console. Can specify a Level, which
|
|
8
|
+
* will be INFO by default.
|
|
9
|
+
*
|
|
10
|
+
* @param message The message to log
|
|
11
|
+
* @param level The level to log
|
|
12
|
+
*/
|
|
13
|
+
export default abstract class SpecLogger {
|
|
14
|
+
static log(message: string, level?: Level): void;
|
|
15
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
// An enum representing the log level and the color to use
|
|
3
|
+
// in chalk to render this level.
|
|
4
|
+
// eslint-disable-next-line no-shadow
|
|
5
|
+
export var Level;
|
|
6
|
+
(function (Level) {
|
|
7
|
+
Level["INFO"] = "blue";
|
|
8
|
+
Level["ERROR"] = "red";
|
|
9
|
+
Level["SUCCESS"] = "green";
|
|
10
|
+
})(Level || (Level = {}));
|
|
11
|
+
/**
|
|
12
|
+
* Log a message in the console. Can specify a Level, which
|
|
13
|
+
* will be INFO by default.
|
|
14
|
+
*
|
|
15
|
+
* @param message The message to log
|
|
16
|
+
* @param level The level to log
|
|
17
|
+
*/
|
|
18
|
+
export default class SpecLogger {
|
|
19
|
+
static log(message, level = Level.INFO) {
|
|
20
|
+
console.log(chalk[level](message));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { Command, Option } from "commander";
|
|
3
|
+
import { merge, presets } from "@fig/autocomplete-merge";
|
|
4
|
+
async function runProgram(oldSpecPath, newSpecPath, options) {
|
|
5
|
+
const { ignoreProps = [], ignoreCommandProps = [], ignoreOptionProps = [], ignoreArgProps = [], newFile: updatedSpecPath, preset, } = options;
|
|
6
|
+
const output = await merge(fs.readFileSync(oldSpecPath, { encoding: "utf8" }), fs.readFileSync(newSpecPath, { encoding: "utf8" }), {
|
|
7
|
+
preset,
|
|
8
|
+
ignore: {
|
|
9
|
+
commonProps: ignoreProps,
|
|
10
|
+
commandProps: ignoreCommandProps,
|
|
11
|
+
optionProps: ignoreOptionProps,
|
|
12
|
+
argProps: ignoreArgProps,
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
fs.writeFileSync(updatedSpecPath || oldSpecPath, output);
|
|
16
|
+
}
|
|
17
|
+
const program = new Command("merge")
|
|
18
|
+
.arguments("<oldspec> <newspec>")
|
|
19
|
+
.description("deep merge new spec into old spec")
|
|
20
|
+
.option("-n, --new-file <path>", "Create a new spec file instead of updating the old one")
|
|
21
|
+
.option("-i, --ignore-props <props>", "The props that should always be overridden.", (value) => value.split(","))
|
|
22
|
+
.option("--ignore-command-props <props>", "The command props that should always be overridden.", (value) => value.split(","))
|
|
23
|
+
.option("--ignore-option-props <props>", "The option props that should always be overridden.", (value) => value.split(","))
|
|
24
|
+
.option("--ignore-arg-props <props>", "The arg props that should always be overridden.", (value) => value.split(","));
|
|
25
|
+
const presetOption = new Option("-p, --preset <name>", "Use a preset").choices(Object.keys(presets));
|
|
26
|
+
program.addOption(presetOption);
|
|
27
|
+
program.action(runProgram);
|
|
28
|
+
export default program;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare function commandStatus(command: string, args: string[]): boolean;
|
|
2
|
+
export declare function isFigInstalled(): boolean;
|
|
3
|
+
export declare function isCwInstalled(): boolean;
|
|
4
|
+
export declare function isQInstalled(): boolean;
|
|
5
|
+
export declare function setSetting(key: string, value: unknown): void;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
export function commandStatus(command, args) {
|
|
3
|
+
try {
|
|
4
|
+
execFileSync(command, args);
|
|
5
|
+
return true;
|
|
6
|
+
}
|
|
7
|
+
catch {
|
|
8
|
+
return false;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
let IS_FIG_INSTALLED;
|
|
12
|
+
export function isFigInstalled() {
|
|
13
|
+
if (IS_FIG_INSTALLED === undefined) {
|
|
14
|
+
IS_FIG_INSTALLED = commandStatus("fig", ["--version"]);
|
|
15
|
+
}
|
|
16
|
+
return IS_FIG_INSTALLED;
|
|
17
|
+
}
|
|
18
|
+
let IS_CW_INSTALLED;
|
|
19
|
+
export function isCwInstalled() {
|
|
20
|
+
if (IS_CW_INSTALLED === undefined) {
|
|
21
|
+
IS_CW_INSTALLED = commandStatus("cw", ["--version"]);
|
|
22
|
+
}
|
|
23
|
+
return IS_CW_INSTALLED;
|
|
24
|
+
}
|
|
25
|
+
let IS_Q_INSTALLED;
|
|
26
|
+
export function isQInstalled() {
|
|
27
|
+
if (IS_Q_INSTALLED === undefined) {
|
|
28
|
+
IS_Q_INSTALLED = commandStatus("q", ["--version"]);
|
|
29
|
+
}
|
|
30
|
+
return IS_Q_INSTALLED;
|
|
31
|
+
}
|
|
32
|
+
export function setSetting(key, value) {
|
|
33
|
+
if (isQInstalled()) {
|
|
34
|
+
commandStatus("q", ["settings", key, JSON.stringify(value)]);
|
|
35
|
+
}
|
|
36
|
+
else if (isCwInstalled()) {
|
|
37
|
+
commandStatus("cw", ["settings", key, JSON.stringify(value)]);
|
|
38
|
+
}
|
|
39
|
+
else if (isFigInstalled()) {
|
|
40
|
+
commandStatus("fig", ["settings", key, JSON.stringify(value)]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Node, TransformerFactory } from "@ohos-ports/typescript";
|
|
2
|
+
/**
|
|
3
|
+
* The TypeScript transformer to rename the export spec variable name to SPEC_NAME,
|
|
4
|
+
* and remove the export keyword.
|
|
5
|
+
*
|
|
6
|
+
* @param context The current context
|
|
7
|
+
*/
|
|
8
|
+
export declare const specTransformer: TransformerFactory<Node>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { factory, isVariableStatement, SyntaxKind, visitEachChild, visitNode, } from "@ohos-ports/typescript";
|
|
2
|
+
// The name of the spec variable
|
|
3
|
+
const SPEC_NAME = "completionSpec";
|
|
4
|
+
const EXPORT_KEYWORD = SyntaxKind.ExportKeyword;
|
|
5
|
+
/**
|
|
6
|
+
* The TypeScript transformer to rename the export spec variable name to SPEC_NAME,
|
|
7
|
+
* and remove the export keyword.
|
|
8
|
+
*
|
|
9
|
+
* @param context The current context
|
|
10
|
+
*/
|
|
11
|
+
export const specTransformer = (context) => (sourceFile) => {
|
|
12
|
+
let updated = false;
|
|
13
|
+
const visitor = (node) => {
|
|
14
|
+
if (!updated && isVariableStatement(node)) {
|
|
15
|
+
const { declarationList, modifiers } = node;
|
|
16
|
+
// Only process if there is a modifier, and if this modifier
|
|
17
|
+
// is an export.
|
|
18
|
+
if (modifiers && modifiers.length === 1 && modifiers[0].kind === EXPORT_KEYWORD) {
|
|
19
|
+
const variableNode = declarationList.declarations[0];
|
|
20
|
+
updated = true;
|
|
21
|
+
// Update the variable name to SPEC_NAME
|
|
22
|
+
const newVariableNode = factory.updateVariableDeclaration(variableNode, factory.createIdentifier(SPEC_NAME), variableNode.exclamationToken, variableNode.type, variableNode.initializer);
|
|
23
|
+
const newDeclarationlist = factory.updateVariableDeclarationList(declarationList, [
|
|
24
|
+
newVariableNode,
|
|
25
|
+
]);
|
|
26
|
+
// Remove the export keyword
|
|
27
|
+
return factory.updateVariableStatement(node, [], newDeclarationlist);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return visitEachChild(node, visitor, context);
|
|
31
|
+
};
|
|
32
|
+
return visitNode(sourceFile, visitor);
|
|
33
|
+
};
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Command } from "commander";
|
|
4
|
+
import semver from "semver";
|
|
5
|
+
import { applySpecDiff, diffSpecs } from "@fig/autocomplete-helpers";
|
|
6
|
+
import { importFromStringSync } from "@ohos-ports/module-from-string";
|
|
7
|
+
import prettier from "prettier";
|
|
8
|
+
import ts from "@ohos-ports/typescript";
|
|
9
|
+
import { build } from "@ohos-ports/esbuild";
|
|
10
|
+
export const copyDirectorySync = (oldPath, newPath) => {
|
|
11
|
+
if (!fs.existsSync(newPath)) {
|
|
12
|
+
fs.mkdirSync(newPath, { recursive: true });
|
|
13
|
+
}
|
|
14
|
+
for (const dirent of fs.readdirSync(oldPath, { withFileTypes: true })) {
|
|
15
|
+
if (dirent.isDirectory()) {
|
|
16
|
+
copyDirectorySync(path.resolve(oldPath, dirent.name), path.resolve(newPath, dirent.name));
|
|
17
|
+
}
|
|
18
|
+
else if (dirent.isFile()) {
|
|
19
|
+
fs.writeFileSync(path.resolve(newPath, dirent.name), fs.readFileSync(path.resolve(oldPath, dirent.name)), { encoding: "utf8" });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const visitFileNodes = (source, visitor) => ts.transform(source, [
|
|
24
|
+
(context) => (rootNode) => {
|
|
25
|
+
const visit = (node) => visitor(ts.visitEachChild(node, visit, context));
|
|
26
|
+
return ts.visitNode(rootNode, visit);
|
|
27
|
+
},
|
|
28
|
+
]).transformed[0];
|
|
29
|
+
const findInFile = (source, predicate) => {
|
|
30
|
+
const matches = [];
|
|
31
|
+
visitFileNodes(source, (node) => {
|
|
32
|
+
// Find a node like "export { versions };"
|
|
33
|
+
const match = predicate(node);
|
|
34
|
+
if (match !== null) {
|
|
35
|
+
matches.push(match);
|
|
36
|
+
}
|
|
37
|
+
return node;
|
|
38
|
+
});
|
|
39
|
+
return matches;
|
|
40
|
+
};
|
|
41
|
+
const formatSource = (source) => prettier.format(Array.isArray(source) ? source.join("\n") : source, {
|
|
42
|
+
parser: "typescript",
|
|
43
|
+
});
|
|
44
|
+
const loadTypescriptModule = async (modulePath) => {
|
|
45
|
+
const jsString = (await build({
|
|
46
|
+
entryPoints: [modulePath],
|
|
47
|
+
bundle: true,
|
|
48
|
+
write: false,
|
|
49
|
+
sourcemap: false,
|
|
50
|
+
loader: { ".ts": "ts" },
|
|
51
|
+
keepNames: true,
|
|
52
|
+
target: "esnext",
|
|
53
|
+
minify: false,
|
|
54
|
+
format: "esm",
|
|
55
|
+
})).outputFiles[0].text;
|
|
56
|
+
return importFromStringSync(jsString, {
|
|
57
|
+
dirname: process.cwd(),
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
const loadVersionedSpec = async (specPath, defaultSpec) => {
|
|
61
|
+
if (!fs.existsSync(specPath)) {
|
|
62
|
+
// TODO: change the way the spec is printed, currently it won't support js variables
|
|
63
|
+
return {
|
|
64
|
+
source: await formatSource([
|
|
65
|
+
`const completion: Fig.Subcommand = ${JSON.stringify(defaultSpec, null, 4)}\n`,
|
|
66
|
+
`const versions: Fig.VersionDiffMap = {};\n`,
|
|
67
|
+
`export { versions };`,
|
|
68
|
+
`export default completion`,
|
|
69
|
+
]),
|
|
70
|
+
spec: defaultSpec,
|
|
71
|
+
versions: {},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const imports = await loadTypescriptModule(specPath);
|
|
75
|
+
if (!imports.versions) {
|
|
76
|
+
throw new Error("Path does not contain versioned spec");
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
source: fs.readFileSync(specPath).toString(),
|
|
80
|
+
spec: imports.default,
|
|
81
|
+
versions: imports.versions,
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
async function addVersionToIndex(sourcePath, version) {
|
|
85
|
+
const source = fs.readFileSync(sourcePath).toString();
|
|
86
|
+
let didUpdate = false;
|
|
87
|
+
const sourceFile = ts.createSourceFile(sourcePath, source, ts.ScriptTarget.ES2015, true);
|
|
88
|
+
const newSource = visitFileNodes(sourceFile, (node) => {
|
|
89
|
+
if (ts.isArrayLiteralExpression(node) &&
|
|
90
|
+
ts.isVariableDeclaration(node.parent) &&
|
|
91
|
+
ts.isIdentifier(node.parent.name) &&
|
|
92
|
+
node.parent.name.escapedText === "versionFiles") {
|
|
93
|
+
didUpdate = true;
|
|
94
|
+
return ts.factory.updateArrayLiteralExpression(node, [
|
|
95
|
+
...node.elements,
|
|
96
|
+
ts.factory.createStringLiteral(version),
|
|
97
|
+
]);
|
|
98
|
+
}
|
|
99
|
+
return node;
|
|
100
|
+
});
|
|
101
|
+
if (!didUpdate) {
|
|
102
|
+
throw new Error("Failed to add version to index");
|
|
103
|
+
}
|
|
104
|
+
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
|
|
105
|
+
const result = printer.printNode(ts.EmitHint.Unspecified, newSource, sourceFile);
|
|
106
|
+
fs.writeFileSync(sourcePath, await formatSource(result));
|
|
107
|
+
}
|
|
108
|
+
const cleanPath = (p) => p.replace(/[^a-zA-Z0-9_\-/.]/, "");
|
|
109
|
+
async function initVersionedSpec(specName, options) {
|
|
110
|
+
const cleanedSpecName = cleanPath(specName);
|
|
111
|
+
const rootSpecPath = path.resolve(options.cwd ?? process.cwd(), specName);
|
|
112
|
+
fs.mkdirSync(rootSpecPath, { recursive: true });
|
|
113
|
+
fs.writeFileSync(`${rootSpecPath}/index.ts`, await formatSource([
|
|
114
|
+
`import { createVersionedSpec } from "@fig/autocomplete-helpers";\n`,
|
|
115
|
+
`const versionFiles = [];\n`,
|
|
116
|
+
`export default createVersionedSpec("${cleanedSpecName}", versionFiles);\n`,
|
|
117
|
+
].join("\n")));
|
|
118
|
+
}
|
|
119
|
+
async function addDiffAction(specName, newSpecPath, diffVersion, options) {
|
|
120
|
+
let folderSpecPath = path.resolve(options.cwd ?? process.cwd(), specName);
|
|
121
|
+
if (options.newPath) {
|
|
122
|
+
const newPath = path.resolve(options.newPath, specName);
|
|
123
|
+
if (fs.existsSync(folderSpecPath)) {
|
|
124
|
+
// check that the new path is not a child of the old
|
|
125
|
+
const relative = path.relative(folderSpecPath, newPath);
|
|
126
|
+
const isSubdirectory = relative && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
127
|
+
if (isSubdirectory)
|
|
128
|
+
throw new Error("'--new-path' must not be a sub-directory of the old spec directory");
|
|
129
|
+
copyDirectorySync(folderSpecPath, newPath);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
await initVersionedSpec(specName, { cwd: options.newPath });
|
|
133
|
+
}
|
|
134
|
+
folderSpecPath = newPath;
|
|
135
|
+
}
|
|
136
|
+
else if (!fs.existsSync(folderSpecPath)) {
|
|
137
|
+
await initVersionedSpec(specName, { cwd: options.cwd });
|
|
138
|
+
}
|
|
139
|
+
const version = semver.parse(diffVersion);
|
|
140
|
+
let versionFileName;
|
|
141
|
+
if (version === null) {
|
|
142
|
+
versionFileName = diffVersion;
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
versionFileName = options.useMinorBase
|
|
146
|
+
? `${version.major}.${version.minor}.0`
|
|
147
|
+
: `${version.major}.0.0`;
|
|
148
|
+
}
|
|
149
|
+
const currentSpecPath = path.resolve(folderSpecPath, `${versionFileName}.ts`);
|
|
150
|
+
const newSpec = (await loadTypescriptModule(newSpecPath)).default;
|
|
151
|
+
const { source, spec, versions } = await loadVersionedSpec(currentSpecPath, newSpec);
|
|
152
|
+
const versionNames = Object.keys(versions).sort(semver.compare);
|
|
153
|
+
const lastVersion = versionNames[versionNames.length - 1];
|
|
154
|
+
if (lastVersion && semver.compare(diffVersion, lastVersion) <= 0) {
|
|
155
|
+
throw new Error(`Cannot publish version ${diffVersion}, later version ${lastVersion} already exists`);
|
|
156
|
+
}
|
|
157
|
+
const latestSpec = versionNames.map((name) => versions[name]).reduce(applySpecDiff, spec);
|
|
158
|
+
const diff = diffSpecs(latestSpec, newSpec) ?? {};
|
|
159
|
+
const versionExports = findInFile(ts.createSourceFile(currentSpecPath, source, ts.ScriptTarget.ES2015, true), (node) => {
|
|
160
|
+
if (ts.isExportSpecifier(node) && node.name.getText() === "versions") {
|
|
161
|
+
return node.parent.parent;
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
});
|
|
165
|
+
if (versionExports.length === 0) {
|
|
166
|
+
throw new Error("No version export found");
|
|
167
|
+
}
|
|
168
|
+
const insertIdx = versionExports[versionExports.length - 1].getStart();
|
|
169
|
+
if (!fs.existsSync(currentSpecPath)) {
|
|
170
|
+
addVersionToIndex(path.resolve(folderSpecPath, "index.ts"), versionFileName);
|
|
171
|
+
}
|
|
172
|
+
fs.writeFileSync(currentSpecPath, await formatSource([
|
|
173
|
+
source.slice(0, insertIdx),
|
|
174
|
+
`\nversions["${diffVersion}"] = ${JSON.stringify(diff, null, 4)}\n`,
|
|
175
|
+
source.slice(insertIdx),
|
|
176
|
+
]));
|
|
177
|
+
}
|
|
178
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
179
|
+
async function precomputeAction(files) {
|
|
180
|
+
/*
|
|
181
|
+
for (let file in files) {
|
|
182
|
+
// For each spec file, check if it is versioned and if so precompute
|
|
183
|
+
// spec files for each version.
|
|
184
|
+
}
|
|
185
|
+
*/
|
|
186
|
+
throw new Error("Unimplemented");
|
|
187
|
+
}
|
|
188
|
+
export default new Command("version")
|
|
189
|
+
.addCommand(new Command("add-diff")
|
|
190
|
+
.arguments("<specName> <newSpecFilePath> <diffVersion>")
|
|
191
|
+
.description("generate version diff from new spec and add into old spec")
|
|
192
|
+
.option("-n, --new-path <path>", "The root folder where the updated spec will be saved. Note: this must NOT include the folder spec name")
|
|
193
|
+
.option("--cwd <path>", "Resolve the spec name relative to this directory")
|
|
194
|
+
.option("--use-minor-base", "Create a new version file per minor version")
|
|
195
|
+
.action(addDiffAction))
|
|
196
|
+
.addCommand(new Command("init-spec")
|
|
197
|
+
.arguments("<name>")
|
|
198
|
+
.option("--cwd <path>", "Generate the spec relative to this directory")
|
|
199
|
+
.description("Generate versioned spec in folder specified by path")
|
|
200
|
+
.action(initVersionedSpec))
|
|
201
|
+
.addCommand(new Command("precompute-specs")
|
|
202
|
+
.arguments("<files...>")
|
|
203
|
+
.description("[Unimplemented] Precompute versioned specs before publishing the specs repo (unimplemented)")
|
|
204
|
+
.action(precomputeAction));
|
package/package.json
CHANGED
|
@@ -1,6 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ohos-ports/withfig-autocomplete-tools",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.11.0-beta.1",
|
|
4
|
+
"description": "Command line tools for working with fig autocomplete specs",
|
|
5
|
+
"author": "The Fig Team",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"bin": "./build/bin.js",
|
|
9
|
+
"main": "./build/index.js",
|
|
10
|
+
"types": "./build/index.d.ts",
|
|
11
|
+
"files": [
|
|
12
|
+
"build/"
|
|
13
|
+
],
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
|
|
16
|
+
"@types/semver": "^7.5.8",
|
|
17
|
+
"chalk": "^5.4.1",
|
|
18
|
+
"chokidar": "^4.0.1",
|
|
19
|
+
"commander": "^13.0.0",
|
|
20
|
+
"fast-glob": "^3.3.2",
|
|
21
|
+
"@ohos-ports/module-from-string": "3.3.1-beta.0",
|
|
22
|
+
"prettier": "^3.3.3",
|
|
23
|
+
"semver": "^7.6.3",
|
|
24
|
+
"@fig/autocomplete-helpers": "^2.0.0",
|
|
25
|
+
"@fig/autocomplete-merge": "^1.4.0",
|
|
26
|
+
"create-completion-spec": "^1.1.9",
|
|
27
|
+
"@ohos-ports/esbuild": "0.25.5",
|
|
28
|
+
"@ohos-ports/typescript": "5.9.3-beta.1"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/node": "^22.5.2",
|
|
32
|
+
"tsx": "^4.19.2",
|
|
33
|
+
"@withfig/autocomplete-types": "^1.31.0",
|
|
34
|
+
"@fig/complete-commander": "^3.2.0"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "rm -rf build/ && pnpm run build:bin && pnpm run build:lib",
|
|
41
|
+
"build:bin": "esbuild src/bin.ts --bundle --platform=node --packages=external --outdir=build --minify --format=esm",
|
|
42
|
+
"build:lib": "tsc",
|
|
43
|
+
"test": "tsx test/index.ts",
|
|
44
|
+
"test:overwrite": "OVERWRITE=true pnpm test",
|
|
45
|
+
"generate-spec": "tsx generate-spec.ts generate-fig-spec"
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "https://github.com/ohos-ports/ohos-ports.git",
|
|
50
|
+
"directory": "ports/withfig-autocomplete-tools/2.11.0"
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/ohos-ports/ohos-ports/issues"
|
|
54
|
+
},
|
|
55
|
+
"fig": {
|
|
56
|
+
"build": {
|
|
57
|
+
"description": "Typecheck and build the project",
|
|
58
|
+
"icon": "🛠"
|
|
59
|
+
},
|
|
60
|
+
"prepack": {
|
|
61
|
+
"description": "Run build before packing the package for publishing",
|
|
62
|
+
"icon": "🛠"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|