Skip to content

Commit

Permalink
Add code formatter (#17)
Browse files Browse the repository at this point in the history
* + Add code formatter.

* + Revert editorconfig.

* + Update README.md
  • Loading branch information
LancerComet authored Apr 23, 2022
1 parent fdcbe12 commit 0ad3581
Show file tree
Hide file tree
Showing 22 changed files with 415 additions and 267 deletions.
21 changes: 0 additions & 21 deletions packages/generator/.eslintrc.js

This file was deleted.

22 changes: 22 additions & 0 deletions packages/generator/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"env": {
"es2021": true,
"node": true
},
"extends": [
"standard",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {
"indent": ["error", 2, { "SwitchCase": 1, "ignoredNodes": ["PropertyDefinition"] }],
"@typescript-eslint/no-inferrable-types": 0
}
}
22 changes: 22 additions & 0 deletions packages/generator/.jest/resolver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* @ts-check */

// This resolver is for using ESLint within Jest.

// temporary workaround - https://github.com/facebook/jest/issues/9771#issuecomment-871585234
const resolver = require('enhanced-resolve').create.sync({
conditionNames: ['require', 'node', 'default'],
extensions: ['.js', '.json', '.node', '.ts', '.tsx'],
});

/**
* @param request {unknown}
* @param options {{ defaultResolver(...args: unknown[]): unknown, basedir: unknown }}
* @returns {unknown}
*/
module.exports = function (request, options) {
// list global module that must be resolved by defaultResolver here
if (['fs', 'http', 'path'].includes(request)) {
return options.defaultResolver(request, options);
}
return resolver(options.basedir, request);
};
4 changes: 2 additions & 2 deletions packages/generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A codegen to create [SunTori](https://github.com/LancerComet/SunTori/tree/master
```ts
import { generate } from '@lancercomet/suntori.generator'

const result = generate({
const result = await generate({
jsonObject: {
name: 'John Smith',
age: 200,
Expand Down Expand Up @@ -63,7 +63,7 @@ class User {
All `null` JSON fields would be converted to the `unknown`, as well as empty arrays.

```ts
generate({
await generate({
jsonObject: {
a: null,
b: []
Expand Down
6 changes: 6 additions & 0 deletions packages/generator/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
resolver: '<rootDir>/.jest/resolver.js',
preset: 'ts-jest',
testEnvironment: 'node'
}
13 changes: 13 additions & 0 deletions packages/generator/lib/format.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const codeFormat = (code: string) => {
return code.replace(/ {4}/g, ' ')
.replace(/\r\n/g, '\n')
.replace(/;/g, '\n')
.replace(/"/g, '\'')
.replace(/\n\n}/g, '\n}\n')
.replace(/}\n\n/g, '}\n')
.replace(/\n@Serializable/g, '\n\n@Serializable')
}

export {
codeFormat
}
17 changes: 11 additions & 6 deletions packages/generator/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
getInitializer,
getSyntaxKind,
printTsCode
} from './utils'
} from './tsc'
import { codeFormat } from './format'

const getJsonString = (jsonObject: unknown): string => {
try {
Expand Down Expand Up @@ -175,13 +176,13 @@ const walkObjectNode = (
/**
* Generate SunTori codes.
*/
const generate = (param: {
const generate = async (param: {
/**
* JSON object.
*
* @type {never}
*/
jsonObject: never
jsonObject: any

/**
* Classname for the entire json.
Expand All @@ -206,7 +207,7 @@ const generate = (param: {
* @default false
*/
addReadonly?: boolean
}): string => {
}): Promise<string> => {
const jsonObject = param.jsonObject
const rootClassName = param.rootClassName ?? 'Root'
const useCamelCase = param.useCamelCase ?? true
Expand All @@ -229,10 +230,14 @@ const generate = (param: {
useCamelCase, addReadonly
)
classDefs.forEach(item => {
result += printTsCode(item) + '\n\n'
result += printTsCode(item) + '\n'
})

return result
try {
return codeFormat(result)
} catch (error) {
throw new Error('Failed to format code: ' + (error as Error).message)
}
}

export {
Expand Down
84 changes: 84 additions & 0 deletions packages/generator/lib/tsc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import ts from 'typescript'
import { isBoolean, isNumber, isString } from './utils'

const getSyntaxKind = (target: unknown) => {
if (isNumber(target)) {
return ts.SyntaxKind.NumberKeyword
}

if (isBoolean(target)) {
return ts.SyntaxKind.BooleanKeyword
}

if (isString(target)) {
return ts.SyntaxKind.StringKeyword
}

return ts.SyntaxKind.UnknownKeyword
}

const getInitializer = (target: unknown): ts.Expression => {
if (isNumber(target)) {
return ts.factory.createNumericLiteral(0)
}

if (isBoolean(target)) {
return ts.factory.createFalse()
}

if (isString(target)) {
return ts.factory.createStringLiteral('')
}

return ts.factory.createNull()
}

const createSerializableDecorator = () => {
return ts.factory.createDecorator(
ts.factory.createCallExpression(
ts.factory.createIdentifier('Serializable'), undefined, []
)
)
}

const createJsonPropertyDecorator = (propName: string) => {
return ts.factory.createDecorator(
ts.factory.createCallExpression(
ts.factory.createIdentifier('JsonProperty'),
undefined,
[
ts.factory.createStringLiteral(propName)
]
)
)
}

const printTsCode = (node: ts.Node): string => {
const resultFile = ts.createSourceFile(
'test.ts',
'',
ts.ScriptTarget.Latest,
false,
ts.ScriptKind.TS
)

const printer = ts.createPrinter({
newLine: ts.NewLineKind.LineFeed
})

const result = printer.printNode(
ts.EmitHint.Unspecified,
node,
resultFile
)

return result
}

export {
getSyntaxKind,
getInitializer,
createSerializableDecorator,
createJsonPropertyDecorator,
printTsCode
}
88 changes: 1 addition & 87 deletions packages/generator/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import ts from 'typescript'

const isString = (target: unknown): target is string => {
return typeof target === 'string'
}
Expand All @@ -12,92 +10,8 @@ const isBoolean = (target: unknown): target is boolean => {
return typeof target === 'boolean'
}

const isNull = (target: unknown): target is null => {
return target === null
}

const getSyntaxKind = (target: unknown) => {
if (isNumber(target)) {
return ts.SyntaxKind.NumberKeyword
}

if (isBoolean(target)) {
return ts.SyntaxKind.BooleanKeyword
}

if (isString(target)) {
return ts.SyntaxKind.StringKeyword
}

return ts.SyntaxKind.UnknownKeyword
}

const getInitializer = (target: unknown): ts.Expression => {
if (isNumber(target)) {
return ts.factory.createNumericLiteral(0)
}

if (isBoolean(target)) {
return ts.factory.createFalse()
}

if (isString(target)) {
return ts.factory.createStringLiteral('')
}

return ts.factory.createNull()
}

const createSerializableDecorator = () => {
return ts.factory.createDecorator(
ts.factory.createCallExpression(
ts.factory.createIdentifier('Serializable'), undefined, []
)
)
}

const createJsonPropertyDecorator = (propName: string) => {
return ts.factory.createDecorator(
ts.factory.createCallExpression(
ts.factory.createIdentifier('JsonProperty'),
undefined,
[
ts.factory.createStringLiteral(propName)
]
)
)
}

const printTsCode = (node: ts.Node): string => {
const resultFile = ts.createSourceFile(
'test.ts',
'',
ts.ScriptTarget.Latest,
false,
ts.ScriptKind.TS
)

const printer = ts.createPrinter({
newLine: ts.NewLineKind.LineFeed
})

const result = printer.printNode(
ts.EmitHint.Unspecified,
node,
resultFile
)

return result
}

export {
isString,
isNumber,
isBoolean,
isNull,
getSyntaxKind,
getInitializer,
createSerializableDecorator,
createJsonPropertyDecorator,
printTsCode
isBoolean
}
Loading

0 comments on commit 0ad3581

Please sign in to comment.