diff --git a/.gitignore b/.gitignore index dccee74..9a07fea 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/.nycrc b/.nycrc index 6d96695..b20dd1a 100644 --- a/.nycrc +++ b/.nycrc @@ -7,7 +7,7 @@ "src/**/*.ts" ], "exclude": [ - "test/**/*.spec.ts" + "**/*.spec.ts" ], "extension": [ ".ts" diff --git a/__snapshots__/integration.spec.ts.js b/__snapshots__/integration.spec.ts.js index 0ae0463..4e5f219 100644 --- a/__snapshots__/integration.spec.ts.js +++ b/__snapshots__/integration.spec.ts.js @@ -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"; ` diff --git a/example/package.json b/example/package.json index 3d7d4e3..a9d7db1 100644 --- a/example/package.json +++ b/example/package.json @@ -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" } } diff --git a/example/ts-gen-plugins/typechain/index.ts b/example/ts-gen-plugins/typechain/index.ts index 1b135f9..621c1d4 100644 --- a/example/ts-gen-plugins/typechain/index.ts +++ b/example/ts-gen-plugins/typechain/index.ts @@ -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) { super(ctx); const { cwd, rawConfig } = ctx; @@ -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, + }; } } diff --git a/example/yarn.lock b/example/yarn.lock index 191f708..1b66edf 100644 --- a/example/yarn.lock +++ b/example/yarn.lock @@ -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" @@ -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" diff --git a/package.json b/package.json index 44cdcc3..6c59032 100644 --- a/package.json +++ b/package.json @@ -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'", @@ -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" diff --git a/src/cli/cli.ts b/src/cli/cli.ts index 7167baa..f90efe6 100644 --- a/src/cli/cli.ts +++ b/src/cli/cli.ts @@ -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"; @@ -12,7 +12,9 @@ export async function cli(configPathRel: string, customDeps?: Partial): 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); } diff --git a/src/deps.ts b/src/deps.ts index 5045a74..8faf21e 100644 --- a/src/deps.ts +++ b/src/deps.ts @@ -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"), }; } diff --git a/src/logger.ts b/src/logger.ts index d310598..1ded296 100644 --- a/src/logger.ts +++ b/src/logger.ts @@ -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(); + } } diff --git a/src/outputTransformers/index.ts b/src/outputTransformers/index.ts new file mode 100644 index 0000000..826c7e4 --- /dev/null +++ b/src/outputTransformers/index.ts @@ -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]; diff --git a/src/outputTransformers/info.ts b/src/outputTransformers/info.ts new file mode 100644 index 0000000..a5c2299 --- /dev/null +++ b/src/outputTransformers/info.ts @@ -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"; +} diff --git a/src/outputTransformers/prettier.ts b/src/outputTransformers/prettier.ts new file mode 100644 index 0000000..f5ca481 --- /dev/null +++ b/src/outputTransformers/prettier.ts @@ -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); +}; diff --git a/src/parseConfigFile.ts b/src/parseConfigFile.ts index 0cdb439..6797854 100644 --- a/src/parseConfigFile.ts +++ b/src/parseConfigFile.ts @@ -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> = { +export type TRawPluginCfg> = { files: string; generator: string; } & T; -export interface TTsGenCfg { +export type TPluginCfg> = Omit, "generator">; + +export interface TRawCfg { cwd: string; - plugins: TPluginCfg[]; + plugins: TRawPluginCfg[]; prettier?: PrettierOptions; } +export type TCfg = Omit; + interface TArgs { cwd: string; configPath: string; } -export async function parseConfigFile({ fs, prettier, logger }: TDeps, { cwd, configPath }: TArgs): Promise { +export async function parseConfigFile({ fs, prettier, logger }: TDeps, { cwd, configPath }: TArgs): Promise { const config = fs.readFileSync(configPath, "utf-8"); // assume that config is correctly formatted JUST FOR NOW diff --git a/src/plugins/loadPlugin.ts b/src/plugins/loadPlugin.ts index 85b1e10..d5ba8f6 100644 --- a/src/plugins/loadPlugin.ts +++ b/src/plugins/loadPlugin.ts @@ -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(object: Dictionary): T { + for (const k of Object.keys(object)) { + return object[k]; + } + throw new Error("Any key missing!"); +} diff --git a/test/plugins/resolvePlugin.spec.ts b/src/plugins/resolvePlugin.spec.ts similarity index 100% rename from test/plugins/resolvePlugin.spec.ts rename to src/plugins/resolvePlugin.spec.ts diff --git a/src/plugins/types.ts b/src/plugins/types.ts index 2b19a8e..1ae0084 100644 --- a/src/plugins/types.ts +++ b/src/plugins/types.ts @@ -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 {} afterRun(): TOutput | Promise {} @@ -20,6 +21,7 @@ export abstract class TsGeneratorPlugin { export interface TContext> { cwd: string; rawConfig: TPluginCfg; + logger?: TLogger; } export interface TFileDesc { diff --git a/src/publicApi.ts b/src/publicApi.ts index b3786b0..19202ad 100644 --- a/src/publicApi.ts +++ b/src/publicApi.ts @@ -1,3 +1,3 @@ export * from "./utils"; export * from "./plugins/types"; -export { tsGen } from "./tsGen"; +export { tsGenerator } from "./tsGenerator"; diff --git a/src/tsGen.ts b/src/tsGen.ts deleted file mode 100644 index 1245db4..0000000 --- a/src/tsGen.ts +++ /dev/null @@ -1,62 +0,0 @@ -import * as glob from "glob"; -import { Options as PrettierOptions } from "prettier"; - -import { TFileDesc, TOutput, TsGeneratorPlugin } from "./plugins/types"; -import { TTsGenCfg } from "./parseConfigFile"; -import { TDeps, createDeps } from "./deps"; -import { isArray } from "util"; -import { Omit } from "./stl"; -import { dirname } from "path"; - -export async function tsGen( - cfg: Omit, - _plugins: TsGeneratorPlugin | TsGeneratorPlugin[], - _deps?: TDeps, -): Promise { - const deps = _deps || createDeps(); - const plugins = isArray(_plugins) ? _plugins : [_plugins]; - - const { cwd, prettier } = cfg; - const { fs, logger } = deps; - - for (const plugin of plugins) { - logger.info("Running before run"); - processOutput(deps, prettier, await plugin.beforeRun()); - - const filePaths = glob.sync(plugin.ctx.rawConfig.files, { ignore: "node_modules/**", absolute: true, cwd }); - const fileDescs = filePaths.map( - path => - ({ - path, - contents: fs.readFileSync(path, "utf8"), - } as TFileDesc), - ); - for (const fd of fileDescs) { - logger.info(`Processing ${fd.path} with ${plugin.name} plugin`); - - processOutput(deps, prettier, await plugin.transformFile(fd)); - } - - logger.info("Running after run"); - processOutput(deps, prettier, await plugin.afterRun()); - } -} - -export function processOutput( - { fs, prettier, logger, mkdirp }: TDeps, - prettierCfg: PrettierOptions | undefined, - output: TOutput, -): void { - if (!output) { - return; - } - const outputFds = isArray(output) ? output : [output]; - - outputFds.forEach(fd => { - // ensure directory first - mkdirp(dirname(fd.path)); - - logger.info("Writing file: ", fd.path); - fs.writeFileSync(fd.path, prettier.format(fd.contents, { ...(prettierCfg || {}), parser: "typescript" }), "utf8"); - }); -} diff --git a/test/tsGen.spec.ts b/src/tsGenerator.spec.ts similarity index 54% rename from test/tsGen.spec.ts rename to src/tsGenerator.spec.ts index 1b68f3d..e9a33e6 100644 --- a/test/tsGen.spec.ts +++ b/src/tsGenerator.spec.ts @@ -1,10 +1,18 @@ -import { TFileDesc } from "../src/publicApi"; -import { processOutput } from "../src/tsGen"; -import { unimock } from "./utils"; -import { TDeps } from "../src/deps"; +import { TFileDesc } from "./publicApi"; +import { processOutput } from "./tsGenerator"; +import { unimock } from "../test/utils"; +import { TDeps } from "./deps"; import { expect } from "chai"; +import { NoLogger } from "./logger"; +import { TCfg } from "./parseConfigFile"; +import { generateInfo } from "./outputTransformers/info"; describe("processOutput", () => { + const logger = new NoLogger(); + const dummyCfg: TCfg = { + cwd: "/", + }; + it("should do nothing when no files to process", () => { const deps = unimock({ fs: undefined, @@ -13,52 +21,56 @@ describe("processOutput", () => { mkdirp: undefined, }); - processOutput(deps, undefined, undefined); + processOutput(deps, dummyCfg, undefined); }); it("should work with single file", () => { const file: TFileDesc = { path: "/dir/a.ts", contents: "AAA" }; const deps = unimock({ - fs: { writeFileSync: () => {} }, + fs: { writeFileSync: () => {}, readFileSync: () => "{}" }, prettier: { format: (contents: string) => contents }, - logger: { info: () => {} }, + logger, mkdirp: (_path: string) => {}, }); - processOutput(deps, undefined, file); + processOutput(deps, dummyCfg, file); expect(deps.mkdirp).to.be.calledOnce; expect(deps.mkdirp).to.be.calledWithExactly("/dir"); expect(deps.prettier.format).to.be.calledOnce; - expect(deps.prettier.format).to.be.calledWithExactly("AAA", { parser: "typescript" }); + expect(deps.prettier.format).to.be.calledWithExactly(wrapWithInfoBlock("AAA"), { parser: "typescript" }); expect(deps.fs.writeFileSync).to.be.calledOnce; - expect(deps.fs.writeFileSync).to.be.calledWithExactly("/dir/a.ts", "AAA", "utf8"); + expect(deps.fs.writeFileSync).to.be.calledWithExactly("/dir/a.ts", wrapWithInfoBlock("AAA"), "utf8"); }); it("should work with multiple files", () => { const files: TFileDesc[] = [{ path: "/dir/a.ts", contents: "AAA" }, { path: "/dir/b.ts", contents: "BBB" }]; const deps = unimock({ - fs: { writeFileSync: () => {} }, + fs: { writeFileSync: () => {}, readFileSync: () => "{}" }, prettier: { format: (contents: string) => contents }, - logger: { info: () => {} }, + logger, mkdirp: (_path: string) => {}, }); - processOutput(deps, undefined, files); + processOutput(deps, dummyCfg, files); expect(deps.mkdirp).to.be.calledTwice; expect(deps.mkdirp).to.be.calledWithExactly("/dir"); expect(deps.prettier.format).to.be.calledTwice; - expect(deps.prettier.format).to.be.calledWithExactly("AAA", { parser: "typescript" }); - expect(deps.prettier.format).to.be.calledWithExactly("BBB", { parser: "typescript" }); + expect(deps.prettier.format).to.be.calledWithExactly(wrapWithInfoBlock("AAA"), { parser: "typescript" }); + expect(deps.prettier.format).to.be.calledWithExactly(wrapWithInfoBlock("BBB"), { parser: "typescript" }); expect(deps.fs.writeFileSync).to.be.calledTwice; - expect(deps.fs.writeFileSync).to.be.calledWithExactly("/dir/a.ts", "AAA", "utf8"); - expect(deps.fs.writeFileSync).to.be.calledWithExactly("/dir/b.ts", "BBB", "utf8"); + expect(deps.fs.writeFileSync).to.be.calledWithExactly("/dir/a.ts", wrapWithInfoBlock("AAA"), "utf8"); + expect(deps.fs.writeFileSync).to.be.calledWithExactly("/dir/b.ts", wrapWithInfoBlock("BBB"), "utf8"); }); }); + +function wrapWithInfoBlock(contents: string): string { + return generateInfo("UNKNOWN", contents); +} diff --git a/src/tsGenerator.ts b/src/tsGenerator.ts new file mode 100644 index 0000000..3e047b7 --- /dev/null +++ b/src/tsGenerator.ts @@ -0,0 +1,63 @@ +import * as glob from "glob"; + +import { TFileDesc, TOutput, TsGeneratorPlugin } from "./plugins/types"; +import { TCfg } from "./parseConfigFile"; +import { TDeps, createDeps } from "./deps"; +import { isArray } from "util"; +import { dirname, relative } from "path"; +import { outputTransformers } from "./outputTransformers"; + +export async function tsGenerator( + cfg: TCfg, + plugins_: TsGeneratorPlugin | TsGeneratorPlugin[], + deps_?: TDeps, +): Promise { + const deps = deps_ || createDeps(); + const plugins = isArray(plugins_) ? plugins_ : [plugins_]; + + const { cwd } = cfg; + const { fs, logger } = deps; + + for (const plugin of plugins) { + logger.verbose("Running before hook for", logger.accent(plugin.name)); + processOutput(deps, cfg, await plugin.beforeRun()); + + const filePaths = glob.sync(plugin.ctx.rawConfig.files, { ignore: "node_modules/**", absolute: true, cwd }); + const fileDescs = filePaths.map( + path => + ({ + path, + contents: fs.readFileSync(path, "utf8"), + } as TFileDesc), + ); + for (const fd of fileDescs) { + logger.info(`Processing ${logger.accent(relative(cwd, fd.path))} with ${logger.accent(plugin.name)} plugin`); + + processOutput(deps, cfg, await plugin.transformFile(fd)); + } + + logger.verbose("Running after hook for", logger.accent(plugin.name)); + processOutput(deps, cfg, await plugin.afterRun()); + } +} + +export function processOutput(deps: TDeps, cfg: TCfg, output: TOutput): void { + const { fs, logger, mkdirp } = deps; + if (!output) { + return; + } + const outputFds = isArray(output) ? output : [output]; + + outputFds.forEach(fd => { + // ensure directory first + mkdirp(dirname(fd.path)); + + const finalOutput = outputTransformers.reduce( + (content, transformer) => transformer(content, deps, cfg), + fd.contents, + ); + + logger.verbose("Writing file: ", fd.path); + fs.writeFileSync(fd.path, finalOutput, "utf8"); + }); +} diff --git a/test/utils.spec.ts b/src/utils.spec.ts similarity index 97% rename from test/utils.spec.ts rename to src/utils.spec.ts index 061175e..41eef2b 100644 --- a/test/utils.spec.ts +++ b/src/utils.spec.ts @@ -1,4 +1,4 @@ -import { getFilenameWithoutAnyExtensions, getRelativeModulePath } from "../src/utils"; +import { getFilenameWithoutAnyExtensions, getRelativeModulePath } from "./utils"; import { expect } from "chai"; describe("utils", () => { diff --git a/test/integration.spec.ts b/test/integration.spec.ts index 614f440..de10261 100644 --- a/test/integration.spec.ts +++ b/test/integration.spec.ts @@ -17,7 +17,21 @@ describe("integration", () => { }); it("should run ts-gen programmatically", async () => { - await cli("./test/integration/ts-gen.json", { logger: new NoLogger() }); + const fsButWithFixedNpmVersion: typeof fs = { + ...fs, + readFileSync: (...args: any[]): any => { + const packageJsonPath = join(__dirname, "../package.json"); + if (args[0] === packageJsonPath) { + return JSON.stringify({ + version: "1.0.0", + }); + } else { + return (fs as any).readFileSync(...args); + } + }, + }; + + await cli("./test/integration/ts-gen.json", { logger: new NoLogger(), fs: fsButWithFixedNpmVersion }); snapshot(fs.readFileSync(generateFilePath, "utf-8")); snapshot(fs.readFileSync(afterFilePath, "utf-8")); diff --git a/test/integration/after.ts b/test/integration/after.ts deleted file mode 100644 index 339ef0a..0000000 --- a/test/integration/after.ts +++ /dev/null @@ -1 +0,0 @@ -export default "after"; diff --git a/test/integration/before.ts b/test/integration/before.ts deleted file mode 100644 index ca7a72e..0000000 --- a/test/integration/before.ts +++ /dev/null @@ -1 +0,0 @@ -export default "before"; diff --git a/test/integration/ts-gen-plugins/dummy-json/index.ts b/test/integration/ts-gen-plugins/dummy-json/index.ts index 2cec5b0..a861622 100644 --- a/test/integration/ts-gen-plugins/dummy-json/index.ts +++ b/test/integration/ts-gen-plugins/dummy-json/index.ts @@ -3,7 +3,7 @@ import { join } from "path"; const generateType = (name: string, type: string): string => `export const ${name}: ${type}`; -export default class JsonPlugin extends TsGeneratorPlugin { +export class JsonPlugin extends TsGeneratorPlugin { name = "JsonPlugin"; transformFile({ path, contents }: TFileDesc): TFileDesc { diff --git a/tsconfig.prod.json b/tsconfig.prod.json index 27a28e4..bef99ae 100644 --- a/tsconfig.prod.json +++ b/tsconfig.prod.json @@ -4,5 +4,6 @@ "sourceMap": false, "declaration": true }, - "include": ["src/**/*.ts"] + "include": ["src/**/*.ts"], + "exclude": ["test/**/*.ts", "src/**/*.spec.ts"] } diff --git a/yarn.lock b/yarn.lock index 631a8d1..d4e1fe9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -401,7 +401,7 @@ chalk@^1.1.1, chalk@^1.1.3: strip-ansi "^3.0.0" supports-color "^2.0.0" -chalk@^2.0.0, chalk@^2.3.0: +chalk@^2.0.0, chalk@^2.3.0, chalk@^2.4.1: version "2.4.1" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.1.tgz#18c49ab16a037b6eb0152cc83e3471338215b66e" dependencies: