Skip to content

Commit

Permalink
feat(@mud/cli): add mud cli and move diamond abi generation to cli
Browse files Browse the repository at this point in the history
  • Loading branch information
alvrs committed May 18, 2022
1 parent 5b9f790 commit 034af90
Show file tree
Hide file tree
Showing 10 changed files with 345 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/cli/build/cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const yargs_1 = __importDefault(require("yargs"));
const helpers_1 = require("yargs/helpers");
(0, yargs_1.default)((0, helpers_1.hideBin)(process.argv))
// Use the commands directory to scaffold.
.commandDir("commands")
// Enable strict mode.
.strict()
// Useful aliases.
.alias({ h: "help" }).argv;
47 changes: 47 additions & 0 deletions packages/cli/build/commands/diamond-abi.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
const fs_1 = __importDefault(require("fs"));
const glob_1 = __importDefault(require("glob"));
const utils_1 = require("../utils");
exports.command = "diamond-abi";
exports.desc = "Merges the abis of different facets of a diamond to a single diamond abi";
const builder = (yargs) => yargs.options({
include: { type: "array" },
exclude: { type: "array" },
out: { type: "string" },
});
exports.builder = builder;
const handler = async (argv) => {
const { include: _include, exclude: _exclude, out: _out } = argv;
const wd = process.cwd();
console.log("Current working directory:", wd);
const include = _include || [`${wd}/abi/*Facet.json`];
const exclude = _exclude ||
["DiamondCutFacet", "DiamondLoupeFacet", "OwnershipFacet"].map((file) => `./abi/${file}.json`);
const out = _out || `${wd}/abi/CombinedFacets.json`;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const abi = [];
for (const path of include) {
const [resolve, , promise] = (0, utils_1.deferred)();
(0, glob_1.default)(path, {}, (_, facets) => {
// Merge all abis matching the path glob
const pathAbi = facets
.filter((facet) => !exclude.includes(facet))
.map((facet) => require(facet))
.map((abis) => abis.abi)
.flat(1);
abi.push(...pathAbi);
resolve();
});
// Make the callback syncronous
await promise;
}
fs_1.default.writeFileSync(out, JSON.stringify({ abi }));
console.log(`Created diamond abi at ${out}`);
process.exit(0);
};
exports.handler = handler;
18 changes: 18 additions & 0 deletions packages/cli/build/commands/hello.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = exports.builder = exports.desc = exports.command = void 0;
exports.command = "hello <name>";
exports.desc = "Greet <name> with Hello";
const builder = (yargs) => yargs
.options({
upper: { type: "boolean" },
})
.positional("name", { type: "string", demandOption: true });
exports.builder = builder;
const handler = (argv) => {
const { name, upper } = argv;
const greeting = `Hello, ${name}!`;
process.stdout.write(upper ? greeting.toUpperCase() : greeting);
process.exit(0);
};
exports.handler = handler;
18 changes: 18 additions & 0 deletions packages/cli/build/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deferred = void 0;
/**
* A convenient way to create a promise with resolve and reject functions.
* @returns Tuple with resolve function, reject function and promise.
*/
function deferred() {
let resolve = null;
let reject = null;
const promise = new Promise((r, rj) => {
resolve = (t) => r(t);
reject = (e) => rj(e);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return [resolve, reject, promise];
}
exports.deferred = deferred;
39 changes: 39 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "@mud/cli",
"version": "0.0.1",
"description": "Command line interface for mud",
"main": "./build/cli.js",
"license": "MIT",
"bin": {
"mud": "./build/cli.js"
},
"scripts": {
"globalinstall": "chmod u+x build/cli.js && yarn build && yarn link && yarn global add @mud/cli@link:./",
"build": "rimraf build && tsc -p .",
"start": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/cli.ts",
"link:bin": "export PATH=\"$(yarn global bin):$PATH\""
},
"devDependencies": {
"@types/clear": "^0.1.2",
"@types/figlet": "^1.5.4",
"@types/node": "^17.0.34",
"@types/yargs": "^17.0.10",
"nodemon": "^2.0.16",
"pkg": "^5.7.0",
"rimraf": "^3.0.2",
"ts-node": "^10.7.0",
"typescript": "^4.6.4"
},
"dependencies": {
"@mud/utils": "0.0.1",
"chalk": "4.1.2",
"clear": "^0.1.0",
"commander": "^9.2.0",
"figlet": "^1.5.2",
"path": "^0.12.7",
"yargs": "^17.5.1"
},
"pkg": {
"scripts": "build/**/*.js"
}
}
12 changes: 12 additions & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env node

import yargs from "yargs";
import { hideBin } from "yargs/helpers";

yargs(hideBin(process.argv))
// Use the commands directory to scaffold.
.commandDir("commands")
// Enable strict mode.
.strict()
// Useful aliases.
.alias({ h: "help" }).argv;
58 changes: 58 additions & 0 deletions packages/cli/src/commands/diamond-abi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import fs from "fs";
import glob from "glob";
import type { Arguments, CommandBuilder } from "yargs";
import { deferred } from "../utils";

type Options = {
include: (string | number)[] | undefined;
exclude: (string | number)[] | undefined;
out: string | undefined;
};

export const command = "diamond-abi";
export const desc = "Merges the abis of different facets of a diamond to a single diamond abi";

export const builder: CommandBuilder<Options, Options> = (yargs) =>
yargs.options({
include: { type: "array" },
exclude: { type: "array" },
out: { type: "string" },
});

export const handler = async (argv: Arguments<Options>): Promise<void> => {
const { include: _include, exclude: _exclude, out: _out } = argv;
const wd = process.cwd();
console.log("Current working directory:", wd);

const include = (_include as string[]) || [`${wd}/abi/*Facet.json`];
const exclude =
(_exclude as string[]) ||
["DiamondCutFacet", "DiamondLoupeFacet", "OwnershipFacet"].map((file) => `./abi/${file}.json`);
const out = _out || `${wd}/abi/CombinedFacets.json`;

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const abi: any[] = [];

for (const path of include) {
const [resolve, , promise] = deferred<void>();
glob(path, {}, (_, facets) => {
// Merge all abis matching the path glob
const pathAbi = facets
.filter((facet) => !exclude.includes(facet))
.map((facet) => require(facet))
.map((abis) => abis.abi)
.flat(1);

abi.push(...pathAbi);
resolve();
});

// Make the callback syncronous
await promise;
}

fs.writeFileSync(out, JSON.stringify({ abi }));

console.log(`Created diamond abi at ${out}`);
process.exit(0);
};
23 changes: 23 additions & 0 deletions packages/cli/src/commands/hello.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { Arguments, CommandBuilder } from "yargs";

type Options = {
name: string;
upper: boolean | undefined;
};

export const command = "hello <name>";
export const desc = "Greet <name> with Hello";

export const builder: CommandBuilder<Options, Options> = (yargs) =>
yargs
.options({
upper: { type: "boolean" },
})
.positional("name", { type: "string", demandOption: true });

export const handler = (argv: Arguments<Options>): void => {
const { name, upper } = argv;
const greeting = `Hello, ${name}!`;
process.stdout.write(upper ? greeting.toUpperCase() : greeting);
process.exit(0);
};
14 changes: 14 additions & 0 deletions packages/cli/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* A convenient way to create a promise with resolve and reject functions.
* @returns Tuple with resolve function, reject function and promise.
*/
export function deferred<T>(): [(t: T) => void, (t: Error) => void, Promise<T>] {
let resolve: ((t: T) => void) | null = null;
let reject: ((t: Error) => void) | null = null;
const promise = new Promise<T>((r, rj) => {
resolve = (t: T) => r(t);
reject = (e: Error) => rj(e);
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return [resolve as any, reject as any, promise];
}
101 changes: 101 additions & 0 deletions packages/cli/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */

/* Language and Environment */
"target": "es2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */

/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "resolveJsonModule": true, /* Enable importing .json files */
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
"outDir": "./build" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
"importHelpers": false /* Allow importing helper functions from tslib once per project, instead of including them per-file. */,
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}

0 comments on commit 034af90

Please sign in to comment.