Skip to content

Commit

Permalink
test: Test most of binary file
Browse files Browse the repository at this point in the history
  • Loading branch information
Sidnioulz committed Sep 11, 2023
1 parent e60efb0 commit 854f590
Show file tree
Hide file tree
Showing 14 changed files with 380 additions and 151 deletions.
7 changes: 7 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ module.exports = {
'error',
{
devDependencies: [
'__mocks__/*',
'**/*.spec.ts',
'.*.config.js',
'.*.config.cjs',
Expand Down Expand Up @@ -102,6 +103,12 @@ module.exports = {
'@typescript-eslint/no-var-requires': 'off',
},
},
{
files: ['__mocks__/*'],
rules: {
'@typescript-eslint/no-var-requires': 'off',
},
},
{
files: ['jest.setup.ts'],
rules: {
Expand Down
3 changes: 3 additions & 0 deletions __mocks__/cosmiconfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
cosmiconfigSync: jest.fn(),
}
3 changes: 3 additions & 0 deletions __mocks__/fs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const { fs } = require('memfs')

module.exports = fs
3 changes: 3 additions & 0 deletions __mocks__/globby.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
globbySync: jest.fn(),
}
1 change: 1 addition & 0 deletions __mocks__/inquirer-autocomplete-prompt.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = jest.fn()
4 changes: 4 additions & 0 deletions __mocks__/inquirer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports = {
registerPrompt: jest.fn(),
prompt: jest.fn(),
}
11 changes: 0 additions & 11 deletions bin/__tests__/vue-sfcmod.spec.ts

This file was deleted.

139 changes: 1 addition & 138 deletions bin/vue-sfcmod.ts
Original file line number Diff line number Diff line change
@@ -1,143 +1,6 @@
#!/usr/bin/env node

import * as fs from 'fs'
import * as path from 'path'

import { cosmiconfigSync } from 'cosmiconfig'
import createDebug from 'debug'
import fuzzy from 'fuzzy'
import { globbySync } from 'globby'
import inquirer from 'inquirer'
import inquirerPrompt from 'inquirer-autocomplete-prompt'
import yargs from 'yargs'

import { isValidConfig } from '~/config.schema'
import runTransformation from '~/runTransformation'
import type { Options } from '~/types/TransformationOptions'

/* Init logger and inquirer. */
inquirer.registerPrompt('autocomplete', inquirerPrompt)
const debug = createDebug('vue-sfcmod')
// eslint-disable-next-line no-console
const log = console.log.bind(console)

/* Load config file. */
const explorerSync = cosmiconfigSync('sfcmod')
const configResult = explorerSync.search()
let config
if (configResult === null) {
debug('No config file found.')
} else if (configResult.isEmpty) {
debug(`A config file was found but is empty: ${configResult.filepath}`)
} else {
debug(`Using config file: ${configResult.filepath}`)
config = configResult.config
}

/* If config.presets is set, compute list of preset transforms. */
let presets: { name: string; value: string }[] = []
if (isValidConfig(config) && Array.isArray(config.presets)) {
presets = config.presets
.map((presetItem) => {
const pathsToInclude = globbySync(
typeof presetItem === 'object' ? presetItem.glob : presetItem,
)

return pathsToInclude.map((value) => ({
name: typeof presetItem === 'object' ? presetItem.name(value) : value,
value,
}))
})
.flat()
}

/* Process CLI args. */
const yargsChain = yargs()
.usage('Usage: $0 [file pattern] -t [transformation]')
.option('transformation', {
alias: 't',
type: 'string',
describe: 'Name or path of the transformation module',
})
.help()

if (!presets.length) {
yargsChain.demandOption('transformation')
}

const {
_: files,
transformation: transformationName,
...allOptions
} = yargsChain.parseSync(process.argv.slice(2))

/* Compute transformation params. */
const params: Options = {}
for (const optKey of Object.keys(allOptions)) {
if (optKey !== 't' && optKey !== '$0' && !optKey.match(/-[a-z]/)) {
params[optKey] = allOptions[optKey]
}
}

/* Load arbitrary transformation module path. */
function loadTransformationModule(nameOrPath: string) {
const customModulePath = path.resolve(process.cwd(), nameOrPath)
if (fs.existsSync(customModulePath)) {
return import(`${process.env.PWD}/${nameOrPath}`)
}

throw new Error(`Cannot find transformation module ${nameOrPath}`)
}

/* Find a transform to run and run it on input files. */
async function main() {
let transformationModule
if (transformationName) {
transformationModule = await loadTransformationModule(transformationName)
} else {
const answer = await inquirer.prompt({
// @ts-expect-error TS does not recognise `type: 'autocomplete'` which would be cumbersome to shim.
type: 'autocomplete',
name: 'preset',
message: 'Preset transformation to run: ',
pageSize: 20,
source: async (_: unknown, input?: string) => {
if (input === undefined || input === '') {
return presets
}

const matches = fuzzy
.filter(input || '', presets, {
extract: (el: { name: string }) => el.name,
})
.map((el: { string: string }) => el.string)

return presets.filter(({ name }) => matches.includes(name))
},
})

transformationModule = await loadTransformationModule(answer.preset)
}

/* Start running. */
const resolvedPaths = globbySync(files as string[])
log(`Processing ${resolvedPaths.length} files…`)

for (const p of resolvedPaths) {
debug(`Processing ${p}…`)
const fileInfo = {
path: p,
source: fs.readFileSync(p).toString(),
}
try {
const result = runTransformation(fileInfo, transformationModule, params)
fs.writeFileSync(p, result)
} catch (e) {
// eslint-disable-next-line no-console
console.error(e)
}
}
}
import { main } from '~/bin'

main().catch((err) => {
// eslint-disable-next-line no-console
Expand Down
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
export default {
preset: 'ts-jest',
extensionsToTreatAsEsm: ['.ts'],
transform: {
'.*': [
'ts-jest',
{
diagnostics: false,
useESM: true,
},
],
},
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@
"fast-check": "^3.13.0",
"husky": "^8.0.3",
"jest": "^29.6.2",
"memfs": "^4.2.1",
"prettier": "^3.0.2",
"rollup": "^3.28.0",
"rollup-plugin-commonjs": "^10.1.0",
Expand Down
Loading

0 comments on commit 854f590

Please sign in to comment.