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

Kk/api revamp #10

Merged
merged 9 commits into from
Aug 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ node_modules
example/gen/*
.nyc_output
coverage
sample.json.d.ts
test/integration/sample.json.d.ts
test/integration/before.ts
test/integration/after.ts
dist
yarn-error.log
2 changes: 1 addition & 1 deletion .nycrc
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"src/**/*.ts"
],
"exclude": [
"test/**/*.spec.ts"
"**/*.spec.ts"
],
"extension": [
".ts"
Expand Down
6 changes: 6 additions & 0 deletions __snapshots__/integration.spec.ts.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
exports['integration should run ts-gen programmatically 1'] = `
/* Generated by ts-generator ver. 1.0.0 */
/* tslint:disable */
export const name: string;
export const age: number;

`

exports['integration should run ts-gen programmatically 2'] = `
/* Generated by ts-generator ver. 1.0.0 */
/* tslint:disable */
export default "after";

`

exports['integration should run ts-gen programmatically 3'] = `
/* Generated by ts-generator ver. 1.0.0 */
/* tslint:disable */
export default "before";

`
4 changes: 3 additions & 1 deletion example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,16 @@
"prepare": "./scripts/prepare.sh",
"start": "cd .. && yarn build && cd ./example && rm -rf ./gen && ../node_modules/.bin/ts-node ../dist/cli/run.js ./ts-gen.json",
"tsc": "../node_modules/.bin/tsc --noEmit",
"tslint": "../node_modules/.bin/tslint -p ./tsconfig.json -e 'node_modules/**/*' -e '**/*.ts'",
"tslint": "../node_modules/.bin/tslint -p ./tsconfig.json -e 'node_modules/**/*' '**/*.ts'",
"test": "yarn tslint & yarn tsc"
},
"dependencies": {
"bignumber.js": "^7.2.1",
"mkdirp": "^0.5.1",
"typechain": "^0.2.6"
},
"devDependencies": {
"@types/bignumber.js": "^5.0.0",
"@types/mkdirp": "^0.5.2"
}
}
21 changes: 11 additions & 10 deletions example/ts-gen-plugins/typechain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ interface TOptions {
output?: string;
}

export default class Typechain extends TsGeneratorPlugin {
export class Typechain extends TsGeneratorPlugin {
name = "Typechain";

private readonly runtimePathAbs: string;
private readonly genPath?: string;
constructor(ctx: TContext) {
constructor(ctx: TContext<TOptions>) {
super(ctx);

const { cwd, rawConfig } = ctx;
Expand All @@ -32,27 +32,28 @@ export default class Typechain extends TsGeneratorPlugin {
if (this.genPath) {
mkdirp(this.genPath);
}
this.logger.info("Copied runtime");
copyRuntime(this.runtimePathAbs);
}

transformFile(fd: TFileDesc): TFileDesc[] {
transformFile(fd: TFileDesc): TFileDesc {
const pathDetails = parse(fd.path);
const outputDir = this.genPath || pathDetails.dir;

const contractName = getFilenameWithoutAnyExtensions(pathDetails.name);
const outputPath = join(outputDir, `${contractName}.ts`);

const abi = JSON.parse(fd.contents);
const relativeRuntimePath = getRelativeModulePath(outputDir, this.runtimePathAbs);
const relativeRuntimePath = getRelativeModulePath(outputPath, this.runtimePathAbs);

const types = abiToWrapper(abi, {
fileName: contractName,
relativeRuntimePath,
});

return [
{
path: join(outputDir, contractName + ".ts"),
contents: types,
},
];
return {
path: outputPath,
contents: types,
};
}
}
10 changes: 10 additions & 0 deletions example/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
# yarn lockfile v1


"@types/bignumber.js@^5.0.0":
version "5.0.0"
resolved "https://registry.yarnpkg.com/@types/bignumber.js/-/bignumber.js-5.0.0.tgz#d9f1a378509f3010a3255e9cc822ad0eeb4ab969"
dependencies:
bignumber.js "*"

"@types/mkdirp@^0.5.2":
version "0.5.2"
resolved "https://registry.yarnpkg.com/@types/mkdirp/-/mkdirp-0.5.2.tgz#503aacfe5cc2703d5484326b1b27efa67a339c1f"
Expand Down Expand Up @@ -34,6 +40,10 @@ balanced-match@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.0.tgz#89b4d199ab2bee49de164ea02b89ce462d71b767"

bignumber.js@*, bignumber.js@^7.2.1:
version "7.2.1"
resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-7.2.1.tgz#80c048759d826800807c4bfd521e50edbba57a5f"

brace-expansion@^1.1.7:
version "1.1.11"
resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"scripts": {
"start": "ts-node ./src/cli/cli.ts ./example/ts-gen.json",
"build": "rm -rf ./dist && tsc -p tsconfig.prod.json --outDir ./dist",
"prepublish": "yarn test && yarn build",
"prepublishOnly": "yarn test && yarn build",
"format": "prettier --list-different '**/*.{ts,json,md, gql}'",
"format:fix": "prettier --write '**/*.{ts,json,md,gql}'",
"tslint": "tslint -p ./tsconfig.json -e 'node_modules/**/*' -e '**/node_modules/**/*' '**/*.ts'",
Expand Down Expand Up @@ -55,6 +55,7 @@
"dependencies": {
"@types/mkdirp": "^0.5.2",
"@types/prettier": "^1.13.2",
"chalk": "^2.4.1",
"glob": "^7.1.2",
"mkdirp": "^0.5.1",
"prettier": "^1.14.2"
Expand Down
8 changes: 5 additions & 3 deletions src/cli/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { join, dirname } from "path";
import { tsGen } from "../tsGen";
import { tsGenerator } from "../tsGenerator";
import { createDeps, TDeps } from "../deps";
import { parseConfigFile } from "../parseConfigFile";
import { loadPlugin } from "../plugins/loadPlugin";
Expand All @@ -12,7 +12,9 @@ export async function cli(configPathRel: string, customDeps?: Partial<TDeps>): P

const cfg = await parseConfigFile(deps, { configPath, cwd });

const plugins = cfg.plugins.map(pluginCfg => loadPlugin(deps, { cwd: cfg.cwd, rawConfig: pluginCfg }));
const plugins = cfg.plugins.map(pluginCfg =>
loadPlugin(deps, { cwd: cfg.cwd, rawConfig: pluginCfg, logger: deps.logger.childLogger(pluginCfg.generator) }),
);

await tsGen(cfg, plugins, deps);
await tsGenerator(cfg, plugins, deps);
}
2 changes: 1 addition & 1 deletion src/deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ export function createDeps(): TDeps {
prettier,
mkdirp,
resolve: require.resolve.bind(require),
logger: new ConsoleLogger(false),
logger: new ConsoleLogger("ts-gen", "normal"),
};
}
43 changes: 38 additions & 5 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,65 @@
/* tslint:disable:no-console */
import chalk from "chalk";

const { gray, green, yellow, red } = chalk;

type TLoggerFunction = (...args: any[]) => void;
type TLoggerLvl = "normal" | "verbose";

export interface TLogger {
info: TLoggerFunction;
verbose: TLoggerFunction;
error: TLoggerFunction;
warn: TLoggerFunction;

accent(s: string): string;
childLogger(name: string): TLogger;
}

export class ConsoleLogger implements TLogger {
constructor(private isSilent: boolean) {}
constructor(private name: string, private lvl: TLoggerLvl) {}

private prefix(): string {
return `${gray(this.name)}:`;
}

info(...args: any[]): void {
if (!this.isSilent) {
console.info(...args);
console.info(this.prefix(), ...args);
}

verbose(...args: any[]): void {
if (this.lvl === "verbose") {
console.info(this.prefix(), ...args);
}
}

error(...args: any[]): void {
console.info(...args);
console.error(this.prefix(), ...args.map(m => red(m)));
}

warn(...args: any[]): void {
console.info(...args);
console.info(this.prefix(), ...args.map(m => yellow(m)));
}

accent(s: string): string {
return green(s);
}

childLogger(name: string): TLogger {
return new ConsoleLogger(name, this.lvl);
}
}

export class NoLogger implements TLogger {
info(): void {}
verbose(): void {}
error(): void {}
warn(): void {}

accent(s: string): string {
return s;
}
childLogger(): TLogger {
return new NoLogger();
}
}
8 changes: 8 additions & 0 deletions src/outputTransformers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { TDeps } from "../deps";
import { TCfg } from "../parseConfigFile";
import { infoOutputTransformer } from "./info";
import { prettierOutputTransformer } from "./prettier";

export type TOutputTransformer = (output: string, deps: TDeps, cfg: TCfg) => string;

export const outputTransformers = [infoOutputTransformer, prettierOutputTransformer];
18 changes: 18 additions & 0 deletions src/outputTransformers/info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { TDeps } from "../deps";
import { TOutputTransformer } from ".";
import { join } from "path";

export const infoOutputTransformer: TOutputTransformer = (output, deps) => {
const version = getPackageVersion(deps);
return generateInfo(version, output);
};

export function generateInfo(version: string, output: string): string {
return [`/* Generated by ts-generator ver. ${version} */`, "/* tslint:disable */", output].join("\n");
}

function getPackageVersion({ fs }: TDeps): string {
const packageJsonPath = join(__dirname, "../../package.json");

return JSON.parse(fs.readFileSync(packageJsonPath, "utf8")).version || "UNKNOWN";
}
9 changes: 9 additions & 0 deletions src/outputTransformers/prettier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Options as PrettierOptions } from "prettier";

import { TOutputTransformer } from ".";

export const prettierOutputTransformer: TOutputTransformer = (output, { prettier }, cfg) => {
const prettierCfg: PrettierOptions = { ...(cfg.prettier || {}), parser: "typescript" };

return prettier.format(output, prettierCfg);
};
16 changes: 11 additions & 5 deletions src/parseConfigFile.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,30 @@
import { TDeps } from "./deps";
import { Options as PrettierOptions } from "prettier";

import { TDeps } from "./deps";
import { Dictionary } from "./stl";
import { Omit } from "./stl";

export type TPluginCfg<T = Dictionary<any>> = {
export type TRawPluginCfg<T = Dictionary<any>> = {
files: string;
generator: string;
} & T;

export interface TTsGenCfg {
export type TPluginCfg<T = Dictionary<any>> = Omit<TRawPluginCfg<T>, "generator">;

export interface TRawCfg {
cwd: string;
plugins: TPluginCfg[];
plugins: TRawPluginCfg[];
prettier?: PrettierOptions;
}

export type TCfg = Omit<TRawCfg, "plugins">;

interface TArgs {
cwd: string;
configPath: string;
}

export async function parseConfigFile({ fs, prettier, logger }: TDeps, { cwd, configPath }: TArgs): Promise<TTsGenCfg> {
export async function parseConfigFile({ fs, prettier, logger }: TDeps, { cwd, configPath }: TArgs): Promise<TRawCfg> {
const config = fs.readFileSync(configPath, "utf-8");

// assume that config is correctly formatted JUST FOR NOW
Expand Down
21 changes: 20 additions & 1 deletion src/plugins/loadPlugin.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,29 @@
import { resolvePlugin } from "./resolvePlugin";
import { TDeps } from "../deps";
import { TContext, TsGeneratorPlugin } from "./types";
import { Dictionary } from "../stl";

export function loadPlugin(deps: TDeps, ctx: TContext): TsGeneratorPlugin {
const pluginPath = resolvePlugin(deps, ctx.rawConfig.generator, ctx.cwd);
const PluginCtr = require(pluginPath).default as { new (ctx: TContext): TsGeneratorPlugin };
const PluginModule = require(pluginPath);

const moduleExportsCount = Object.keys(PluginModule).length;
if (moduleExportsCount !== 1) {
throw new Error(
`Loading plugin ${
ctx.rawConfig.generator
} failed. Plugin module has to export exactly one entity. Found ${moduleExportsCount} instead`,
);
}

const PluginCtr = getFirstKey<{ new (ctx: TContext): TsGeneratorPlugin }>(PluginModule);

return new PluginCtr(ctx);
}

export function getFirstKey<T>(object: Dictionary<T>): T {
for (const k of Object.keys(object)) {
return object[k];
}
throw new Error("Any key missing!");
}
File renamed without changes.
10 changes: 6 additions & 4 deletions src/plugins/types.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { TPluginCfg } from "../parseConfigFile";
import { Dictionary } from "../stl";

export type TPluginState = "uninitialized" | "initialized";
import { TLogger, NoLogger } from "../logger";

export type TOutput = void | TFileDesc | TFileDesc[];

export abstract class TsGeneratorPlugin {
public state: TPluginState = "uninitialized";
public abstract readonly name: string;
public readonly logger: TLogger;

constructor(public readonly ctx: TContext) {}
constructor(public readonly ctx: TContext) {
this.logger = ctx.logger || new NoLogger();
}

beforeRun(): TOutput | Promise<TOutput> {}
afterRun(): TOutput | Promise<TOutput> {}
Expand All @@ -20,6 +21,7 @@ export abstract class TsGeneratorPlugin {
export interface TContext<T = Dictionary<any>> {
cwd: string;
rawConfig: TPluginCfg<T>;
logger?: TLogger;
}

export interface TFileDesc {
Expand Down
2 changes: 1 addition & 1 deletion src/publicApi.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from "./utils";
export * from "./plugins/types";
export { tsGen } from "./tsGen";
export { tsGenerator } from "./tsGenerator";