Skip to content

Commit

Permalink
Bump to 0.9.0 & lint fix (#113)
Browse files Browse the repository at this point in the history
  • Loading branch information
haven2world authored Feb 20, 2023
1 parent 3d92991 commit bafb0d0
Show file tree
Hide file tree
Showing 9 changed files with 80 additions and 46 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ts-gyb",
"version": "0.8.0",
"version": "0.9.0",
"description": "Generate Native API based on TS interface",
"repository": {
"type": "git",
Expand Down
17 changes: 8 additions & 9 deletions src/cli/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ export function generateWithConfig(config: Configuration): void {
);

const namedTargets = Object.fromEntries(
Object.entries(config.parsing.targets)
.map(([target, targetConfig]) => ([
target,
generator.parseTarget(
targetConfig.source,
targetConfig.exportedInterfaceBases !== undefined ? new Set(targetConfig.exportedInterfaceBases) : undefined,
targetConfig.tsconfigPath
)
]))
Object.entries(config.parsing.targets).map(([target, targetConfig]) => [
target,
generator.parseTarget(
targetConfig.source,
targetConfig.exportedInterfaceBases !== undefined ? new Set(targetConfig.exportedInterfaceBases) : undefined,
targetConfig.tsconfigPath
),
])
);

let sharedTypes = generator.extractTargetsSharedTypes(Object.values(namedTargets));
Expand Down
33 changes: 21 additions & 12 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,16 @@ function run(): void {
program
.scriptName('ts-gyb')
.command(['gen', '*'], 'generate code from a configuration file', () => {}, generate)
.command('list-output', 'list all output files', (subprogram) => {
subprogram
.option('language', { description: 'language of the output files to list', choices: ['swift', 'kotlin'] })
.option('expand', { description: 'expand directories' });
}, listOutput)
.command(
'list-output',
'list all output files',
(subprogram) => {
subprogram
.option('language', { description: 'language of the output files to list', choices: ['swift', 'kotlin'] })
.option('expand', { description: 'expand directories' });
},
listOutput
)
.option('config', {
describe: 'path to the configuration file',
type: 'string',
Expand Down Expand Up @@ -44,18 +49,22 @@ function listOutput(args: { config: string; language?: 'swift' | 'kotlin'; expan
}
files = renderingConfig.renders.map((render) => render.outputPath);
} else {
files = Object.values(config.rendering).flatMap((renderingConfig: RenderConfiguration) => renderingConfig.renders.map((render) => render.outputPath));
files = Object.values(config.rendering).flatMap((renderingConfig: RenderConfiguration) =>
renderingConfig.renders.map((render) => render.outputPath)
);
}

files = files.map((file) => path.resolve(file));
if (args.expand) {
files = files.map((filePath) => {
if (!fs.lstatSync(filePath).isDirectory()) {
return filePath;
}
files = files
.map((filePath) => {
if (!fs.lstatSync(filePath).isDirectory()) {
return filePath;
}

return fs.readdirSync(filePath).map((file) => path.join(filePath, file));
}).flat();
return fs.readdirSync(filePath).map((file) => path.join(filePath, file));
})
.flat();
}

files = [...new Set(files)];
Expand Down
2 changes: 1 addition & 1 deletion src/configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export interface RenderConfiguration {
* A list of render configurations.
*/
renders: TargetRenderConfiguration[];

/**
* Template path for named types. Must be a mustache template.
* If it is a relative path, it will be resolved based on the configuration file path.
Expand Down
37 changes: 23 additions & 14 deletions src/generator/CodeGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import fs from 'fs';
import path from 'path';
import { dropIPrefixInCustomTypes, extractTargetsSharedTypes, NamedTypeInfo, ParsedModule, ParsedTarget, parseTarget } from './named-types';
import {
dropIPrefixInCustomTypes,
extractTargetsSharedTypes,
NamedTypeInfo,
ParsedModule,
ParsedTarget,
parseTarget,
} from './named-types';
import { Parser } from '../parser/Parser';
import { renderCode } from '../renderer/renderer';
import { NamedTypeView, ModuleView, InterfaceTypeView, EnumTypeView } from '../renderer/views';
Expand All @@ -26,11 +33,17 @@ export class CodeGenerator {
private readonly predefinedTypes: Set<string>,
private readonly defaultCustomTags: Record<string, unknown>,
private readonly skipInvalidMethods: boolean,
private readonly dropInterfaceIPrefix: boolean,
private readonly dropInterfaceIPrefix: boolean
) {}

parseTarget(interfacePaths: string[], exportedInterfaceBases?: Set<string>, tsconfigPath?: string): ParsedTarget {
const parser = new Parser(interfacePaths, this.predefinedTypes, this.skipInvalidMethods, exportedInterfaceBases, tsconfigPath);
const parser = new Parser(
interfacePaths,
this.predefinedTypes,
this.skipInvalidMethods,
exportedInterfaceBases,
tsconfigPath
);
const modules = parser.parse();

modules.forEach((module) => applyDefaultCustomTags(module, this.defaultCustomTags));
Expand Down Expand Up @@ -69,16 +82,17 @@ export class CodeGenerator {
renderModules(modules: ParsedModule[], options: RenderOptions): void {
const valueTransformer = this.getValueTransformer(options.language, options.typeNameMap);

const moduleViews = modules.map((module) =>
this.getModuleView(module, valueTransformer)
);
const moduleViews = modules.map((module) => this.getModuleView(module, valueTransformer));

if (path.extname(options.outputPath) === '') {
// The path is a directory
moduleViews.forEach((moduleView) => {
const renderedCode = renderCode(options.templatePath, moduleView);

this.writeFile(renderedCode, path.join(options.outputPath, `${moduleView.moduleName}${this.getFileExtension(options.language)}`));
this.writeFile(
renderedCode,
path.join(options.outputPath, `${moduleView.moduleName}${this.getFileExtension(options.language)}`)
);
});
} else {
moduleViews.forEach((moduleView, index) => {
Expand All @@ -93,9 +107,7 @@ export class CodeGenerator {
renderNamedTypes(sharedTypes: NamedTypeInfo[], options: RenderOptions): void {
const valueTransformer = this.getValueTransformer(options.language, options.typeNameMap);

const namedTypesView = sharedTypes.map((namedType) =>
this.getNamedTypeView(namedType, valueTransformer)
);
const namedTypesView = sharedTypes.map((namedType) => this.getNamedTypeView(namedType, valueTransformer));
const renderedCode = renderCode(options.templatePath, namedTypesView);
this.writeFile(renderedCode, options.outputPath);
}
Expand Down Expand Up @@ -124,10 +136,7 @@ export class CodeGenerator {
return namedTypeView;
}

private getModuleView(
module: ParsedModule,
valueTransformer: ValueTransformer
): ModuleView {
private getModuleView(module: ParsedModule, valueTransformer: ValueTransformer): ModuleView {
return new ModuleView(
module,
module.associatedTypes.map((associatedType) => this.getNamedTypeView(associatedType, valueTransformer)),
Expand Down
2 changes: 1 addition & 1 deletion src/generator/named-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ export function extractTargetsSharedTypes(targets: ParsedTarget[]): NamedTypeInf

const sharedTypes = Object.entries(typeTargetsMap)
.filter(([, [, targetSet]]) => targetSet.size > 1)
.map(([, [namedType,]]) => namedType);
.map(([, [namedType]]) => namedType);

const sharedTypeNames = new Set(sharedTypes.map(({ type }) => type.name));

Expand Down
22 changes: 17 additions & 5 deletions src/parser/Parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ export class Parser {

private valueParser: ValueParser;

constructor(globPatterns: string[], predefinedTypes: Set<string>, skipInvalidMethods = false, private readonly exportedInterfaceBases: Set<string> | undefined, tsconfigPath: string | undefined) {
constructor(
globPatterns: string[],
predefinedTypes: Set<string>,
skipInvalidMethods = false,
private readonly exportedInterfaceBases: Set<string> | undefined,
tsconfigPath: string | undefined
) {
const filePaths = globPatterns.flatMap((pattern) => glob.sync(pattern));

if (tsconfigPath !== undefined) {
Expand All @@ -33,9 +39,14 @@ export class Parser {
options: {},
});
}

this.checker = this.program.getTypeChecker();
this.valueParser = new ValueParser(this.checker, predefinedTypes, new ParserLogger(this.checker), skipInvalidMethods);
this.valueParser = new ValueParser(
this.checker,
predefinedTypes,
new ParserLogger(this.checker),
skipInvalidMethods
);
}

parse(): Module[] {
Expand Down Expand Up @@ -67,12 +78,13 @@ export class Parser {
throw Error('Invalid module node');
}

const exportedInterfaceBases = node.heritageClauses?.flatMap((heritageClause) => heritageClause.types.map((type) => type.getText())) ?? [];
const exportedInterfaceBases =
node.heritageClauses?.flatMap((heritageClause) => heritageClause.types.map((type) => type.getText())) ?? [];

const jsDocTagsResult = parseTypeJSDocTags(symbol);

if (this.exportedInterfaceBases !== undefined) {
if (!(exportedInterfaceBases.some((extendedInterface) => this.exportedInterfaceBases?.has(extendedInterface)))) {
if (!exportedInterfaceBases.some((extendedInterface) => this.exportedInterfaceBases?.has(extendedInterface))) {
return null;
}
} else if (!jsDocTagsResult.shouldExport) {
Expand Down
7 changes: 6 additions & 1 deletion src/parser/ValueParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ import { ParserLogger } from '../logger/ParserLogger';
import { ValueParserError } from './ValueParserError';

export class ValueParser {
constructor(private readonly checker: ts.TypeChecker, private readonly predefinedTypes: Set<string>, private readonly logger: ParserLogger, private readonly skipInvalidMethods: boolean) {}
constructor(
private readonly checker: ts.TypeChecker,
private readonly predefinedTypes: Set<string>,
private readonly logger: ParserLogger,
private readonly skipInvalidMethods: boolean
) {}

parseFunctionReturnType(methodSignature: ts.SignatureDeclarationBase): [ValueType | null, boolean] {
if (methodSignature.type === undefined) {
Expand Down

0 comments on commit bafb0d0

Please sign in to comment.