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

Fix variant type generation #20

Merged
merged 4 commits into from
Dec 6, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"commander": "^11.0.0",
"node-fetch": "^2.6.1",
"prettier": "^2.2.1",
"typescript": "^4.9.5"
"typescript": "^4.9.5",
"eslint": "^8.48.0"
},
"resolutions": {
"@wharfkit/antelope": "^1.0.0"
Expand Down
92 changes: 32 additions & 60 deletions src/commands/contract/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,34 +34,35 @@ export function getCoreImports(abi: ABI.Def) {

const {type} = findAbiType(field.type, abi)

if (type.includes(' | ')) {
coreImports.push('Variant')
const coreClass = findCoreClassImport(type)

type.split(' | ').forEach((typeString) => {
const coreType = findCoreClassImport(typeString)

if (coreType) {
coreTypes.push(coreType)
}
})
} else {
const coreClass = findCoreClassImport(type)
if (coreClass) {
coreImports.push(coreClass)
}

if (coreClass) {
coreImports.push(coreClass)
}
// We don't need to add action types unless the struct is an action param
if (!structIsActionParams) {
continue
}

// We don't need to add action types unless the struct is an action param
if (!structIsActionParams) {
continue
}
const coreType = findCoreType(type)

const coreType = findCoreType(type)
if (coreType) {
coreTypes.push(coreType)
}
}
}

if (coreType) {
coreTypes.push(coreType)
if (abi.variants.length != 0) {
coreImports.push('Variant')
for (const variant of abi.variants) {
variant.types.forEach((typeString) => {
const {type: abiType} = findAbiType(typeString, abi)
const coreClass = findCoreClassImport(abiType)
if (coreClass) {
coreImports.push(coreClass)
}
}
})
}
}

Expand Down Expand Up @@ -180,6 +181,7 @@ export function findInternalType(
): string {
const {type: typeString, decorator} = findType(type, abi, typeNamespace)

// TODO: inside findType, namespace is prefixed, but format internal is doing the same
return formatInternalType(typeString, typeNamespace, abi, decorator)
}

Expand All @@ -189,7 +191,7 @@ function formatInternalType(
abi: ABI.Def,
decorator = ''
): string {
const structNames = abi.structs.map((struct) => struct.name.toLowerCase())
const structNames = [...abi.structs, ...abi.variants].map((struct) => struct.name.toLowerCase())

let type

Expand All @@ -209,36 +211,10 @@ function findAliasType(typeString: string, abi: ABI.Def): string | undefined {
return alias?.type && `${alias?.type}${decorator || ''}`
}

function findVariantType(
typeString: string,
abi: ABI.Def,
typeNamespace: string,
context: string
): string | undefined {
const abiVariant = abi.variants.find(
(variant) => variant.name.toLowerCase() === typeString.toLowerCase()
)

if (!abiVariant) {
return
}

return abiVariant.types
.map((type) => {
if (context === 'external') {
return parseType(findExternalType(type, typeNamespace, abi))
} else {
return parseType(findInternalType(type, typeNamespace, abi))
}
})
.join(' | ')
}

export function findAbiType(
type: string,
abi: ABI.Def,
typeNamespace = '',
context = 'internal'
typeNamespace = ''
): {type: string; decorator?: string} {
let typeString = parseType(trim(type))

Expand All @@ -252,13 +228,9 @@ export function findAbiType(
typeString = extractDecoratorResponse.type
const decorator = extractDecoratorResponse.decorator

const variantType = findVariantType(typeString, abi, typeNamespace, context)

if (variantType) {
return {type: variantType, decorator}
}

const abiType = abi.structs.find((abiType) => abiType.name === typeString)?.name
const abiType = [...abi.structs, ...abi.variants].find(
(abiType) => abiType.name === typeString
)?.name

if (abiType) {
return {type: `${typeNamespace}${formatClassName(abiType)}`, decorator}
Expand All @@ -268,13 +240,13 @@ export function findAbiType(
}

export function findExternalType(type: string, typeNamespace = '', abi: ABI.Def): string {
const {type: typeString, decorator} = findType(type, abi, typeNamespace, 'external')
const {type: typeString, decorator} = findType(type, abi, typeNamespace)

return `${findCoreType(typeString) || capitalize(typeString)}${decorator === '[]' ? '[]' : ''}`
}

function findType(type: string, abi: ABI.Def, typeNamespace?: string, context = 'internal') {
return findAbiType(type, abi, typeNamespace, context)
function findType(type: string, abi: ABI.Def, typeNamespace?: string) {
return findAbiType(type, abi, typeNamespace)
}

const decorators = ['?', '[]']
Expand Down
32 changes: 24 additions & 8 deletions src/commands/contract/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import * as eslint from 'eslint'
import * as fs from 'fs'
import * as prettier from 'prettier'
import * as ts from 'typescript'
import * as fs from 'fs'

import type {ABI} from '@wharfkit/session'
import type {ABIDef} from '@wharfkit/antelope'
import {abiToBlob, ContractKit} from '@wharfkit/contract'

import {log, makeClient} from '../../utils'
import {generateContractClass} from './class'
import {generateImportStatement, getCoreImports} from './helpers'
import {generateActionNamesInterface, generateActionsNamespace} from './interfaces'
import {generateTableMap, generateTableTypesInterface} from './maps'
import {generateNamespace} from './namespace'
import {generateStructClasses} from './structs'
import {log, makeClient} from '../../utils'
import {generateActionsTypeAlias, generateRowType, generateTablesTypeAlias} from './types'

const printer = ts.createPrinter()
Expand All @@ -20,9 +22,13 @@ interface CommandOptions {
url: string
file?: string
json?: string
eslintrc?: string
}

export async function generateContractFromCommand(contractName, {url, file, json}: CommandOptions) {
export async function generateContractFromCommand(
contractName,
{url, file, json, eslintrc}: CommandOptions
) {
let abi: ABIDef | undefined

if (json) {
Expand Down Expand Up @@ -52,7 +58,7 @@ export async function generateContractFromCommand(contractName, {url, file, json
const contract = await contractKit.load(contractName)

log(`Generating Contract helpers for ${contractName}...`)
const contractCode = await generateContract(contractName, contract.abi)
const contractCode = await generateContract(contractName, contract.abi, eslintrc)

log(`Generated Contract helper class for ${contractName}...`)
if (file) {
Expand All @@ -64,7 +70,7 @@ export async function generateContractFromCommand(contractName, {url, file, json
}
}

export async function generateContract(contractName, abi) {
export async function generateContract(contractName: string, abi: ABI, eslintrc?: string) {
try {
const {classes, types} = getCoreImports(abi)

Expand Down Expand Up @@ -181,16 +187,17 @@ export async function generateContract(contractName, abi) {
ts.NodeFlags.None
)

return runPrettier(printer.printFile(sourceFile))
return runPrettier(printer.printFile(sourceFile), eslintrc)
} catch (e) {
// eslint-disable-next-line no-console
console.error(`An error occurred while generating the contract code: ${e}`)
throw e
}
}

function runPrettier(codeText: string) {
return prettier.format(codeText, {
async function runPrettier(codeText: string, eslintrc?: string): Promise<string> {
// First prettier and then eslint fix, cause prettier result cann't pass eslint check
const prettiered = prettier.format(codeText, {
arrowParens: 'always',
bracketSpacing: false,
endOfLine: 'lf',
Expand All @@ -201,6 +208,15 @@ function runPrettier(codeText: string) {
trailingComma: 'es5',
parser: 'typescript',
})

const linter = new eslint.ESLint({
useEslintrc: false,
fix: true,
baseConfig: {},
overrideConfigFile: eslintrc ? eslintrc : null,
})
const results = await linter.lintText(prettiered)
return results[0].output ? results[0].output : prettiered
}

function cleanupImports(imports: string[]) {
Expand Down
Loading
Loading