Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CLI package for parsing schema files #1286

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22,635 changes: 22,099 additions & 536 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"eslint-plugin-prettier": "4.0.0",
"husky": "7.0.4",
"jest": "27.5.1",
"jsdom": "20.0.0",
"lerna": "4.0.0",
"lint-staged": "12.3.7",
"markdown-it": "10.0.0",
Expand All @@ -46,10 +47,11 @@
"react": "17.0.2",
"react-dom": "17.0.2",
"ts-loader": "9.2.8",
"typescript": "4.6.2",
"typescript": "^4.8.0-dev.20220628",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this....right?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops lol

"uuid-random": "1.3.2"
},
"dependencies": {
"@atjson/cli": "file:packages/@atjson/cli",
"@atjson/document": "file:packages/@atjson/document",
"@atjson/hir": "file:packages/@atjson/hir",
"@atjson/offset-annotations": "file:packages/@atjson/offset-annotations",
Expand Down
16 changes: 16 additions & 0 deletions packages/@atjson/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "@atjson/cli",
"version": "0.1.0",
"description": "CLI (command line interface) for building and maintaining atjson schemas",
"main": "dist/commonjs/index.js",
"module": "dist/modules/index.js",
"types": "dist/commonjs/index.d.ts",
"license": "Apache-2.0",
"publishConfig": {
"access": "public"
},
"bin": "./dist/commonjs/cli.js",
"dependencies": {
"yaml": "^2.1.1"
}
}
31 changes: 31 additions & 0 deletions packages/@atjson/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/env node
import minimist from "minimist";
import { generateTypes } from "./commands/generate-types";
import { validate } from "./commands/validate";

let args = minimist(process.argv.slice(2));

if (args._[0] === "generate-types") {
if (
typeof args._[1] === "string" &&
typeof args.out === "string" &&
(args.format === "javascript" || args.format === "typescript")
) {
generateTypes({
path: args._[1],
out: args.out,
format: args.format as "javascript" | "typescript",
dryRun: "d" in args || "dry" in args,
}).then(() => {
process.exit();
});
}
} else if (args._[0] === "validate") {
if (typeof args._[1] === "string") {
validate({
path: args._[1],
}).then(() => {
process.exit();
});
}
}
114 changes: 114 additions & 0 deletions packages/@atjson/cli/src/commands/generate-types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import { parse } from "yaml";
import path from "path";
import fs from "fs/promises";
import { format } from "prettier";

function classify(text: string) {
return text
.split("-")
.map((part) => `${part[0].toUpperCase()}${part.slice(1)}`)
.join("");
}

function dasherize(text: string) {
return text
.replace(/([a-z])([A-Z])/g, (...args) => `${args[1]}-${args[2]}`)
.split(/\s+/g)
.join("-")
.toLowerCase();
}

const TYPE_MAP = {
string: "string",
int: "number",
float: "number",
boolean: "boolean",
date: "Date",
};

export async function generateTypes(options: {
path: string;
out: string;
format: "javascript" | "typescript";
dryRun: boolean;
}) {
let file = await fs.readFile(
path.join(process.cwd(), ...options.path.split("/")),
"utf-8"
);
let yaml = parse(file.toString());

for (let key in yaml.schema) {
let annotation = yaml.schema[key];
let type =
annotation.type === "mark"
? "InlineAnnotation"
: annotation.type === "block"
? "BlockAnnotation"
: "ObjectAnnotation";

let lines = [`import { ${type} } from "@atjson/document";`, ``];
if (annotation.description) {
lines.push(`/**`, ` * ${annotation.description}`, ` */`);
}
let name = annotation.name ?? annotation.key;
lines.push(`export class ${classify(name)} extends ${type}`);

if (annotation.data) {
if (options.format === "javascript") {
continue;
}
lines.push(`<{`);

for (let key in annotation.data) {
let attribute = annotation.data[key];
let typeName = attribute.type;
let isArray = typeName.endsWith("[]");
if (isArray) {
typeName = typeName.slice(0, typeName.length - 2);
}
if (!(typeName in TYPE_MAP)) {
console.error(`${typeName} is not a valid attribute type.`);
return;
}
if (!attribute.required) {
key = `${key}?`;
}
let type = TYPE_MAP[typeName as keyof typeof TYPE_MAP];
if (isArray) {
type = `${type}[]`;
}
if (attribute.description) {
lines.push(`/**`, `* ${attribute.description}`, `*/`);
}
lines.push(`${key}: ${type}`);
}
lines.push(`}>`);
}

lines.push(
`{`,
` static vendorPrefix = "${dasherize(yaml.name)}";`,
` static type = "${key}";`,
`}`
);

let output = format(lines.join("\n"), {
parser: options.format === "javascript" ? "babel" : "typescript",
});
let filename = `${annotation.name}.${
options.format === "javascript" ? "js" : "ts"
}`;

if (options.dryRun) {
console.log(output);
} else {
await fs.writeFile(
path.join(process.cwd(), ...options.out.split("/"), filename),
output
);
}
}

return yaml;
}
26 changes: 26 additions & 0 deletions packages/@atjson/cli/src/commands/validate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { parseDocument } from "yaml";
import path from "path";
import fs from "fs/promises";

export async function validate(options: { path: string }) {
let file = await fs.readFile(
path.join(process.cwd(), ...options.path.split("/")),
"utf-8"
);
let yaml = parseDocument(file.toString());
let errors = {
missing: [] as string[],
};
if (!yaml.has("name")) {
errors.missing.push("name");
}
if (!yaml.has("version")) {
errors.missing.push("version");
}
if (!yaml.has("schema")) {
errors.missing.push("schema");
}
console.log(errors);

return errors;
}
2 changes: 2 additions & 0 deletions packages/@atjson/cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./commands/generate-types";
export * from "./commands/validate";
10 changes: 10 additions & 0 deletions packages/@atjson/cli/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/commonjs",
"rootDir": "./src",
"module": "Node16",
"target": "ES3"
},
"include": ["src/**/*"]
}
9 changes: 9 additions & 0 deletions packages/@atjson/cli/tsconfig.modules.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist/modules",
"isolatedModules": true,
"module": "esnext",
"target": "ES2018"
}
}