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

feat: CLI for quick scaffolding #277

Merged
merged 20 commits into from
Nov 11, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions bin/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env node

import { cli } from '../dist/cli/index.js'
cli()
15 changes: 11 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,22 @@
},
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"@antfu/eslint-config": "./bin/index.js",
"init": "./bin/index.js"
},
injurka marked this conversation as resolved.
Show resolved Hide resolved
"files": [
"bin",
"dist"
],
"scripts": {
"build": "tsup src/index.ts --format esm,cjs --clean --dts",
"stub": "tsup src/index.ts --format esm",
"dev": "tsup src/index.ts --format esm,cjs --watch & eslint-flat-config-viewer",
"build": "tsup src/index.ts src/cli/index.ts --format esm,cjs --clean --dts",
"stub": "tsup src/index.ts src/cli/index.ts --format esm",
"dev": "tsup src/index.ts src/cli/index.ts --format esm,cjs --watch & eslint-flat-config-viewer",
"lint": "pnpm run stub && eslint .",
"prepack": "nr build",
"release": "bumpp && pnpm publish",
"test": "vitest",
"test": "vitest --run",
"typecheck": "tsc --noEmit",
"prepare": "simple-git-hooks"
},
Expand Down Expand Up @@ -73,8 +78,10 @@
"eslint-flat-config-viewer": "^0.1.0",
"eslint-plugin-sort-keys": "^2.3.5",
"esno": "^0.17.0",
"execa": "^8.0.1",
"fast-glob": "^3.3.1",
"fs-extra": "^11.1.1",
"kleur": "^4.1.5",
"lint-staged": "^14.0.1",
"rimraf": "^5.0.5",
"simple-git-hooks": "^2.9.0",
Expand Down
36 changes: 36 additions & 0 deletions pnpm-lock.yaml

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

153 changes: 153 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/* eslint-disable no-console */
import { execSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import c from 'kleur'

export async function cli() {
const cwd = process.cwd()

console.log(c.dim(`\nSetup eslint config...\n`))

// Update package.json
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might have a few prompts for each step.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Im not quite sure what exactly is meant, and Im also not sure I can envision a completely correct promts usage scenario on your behalf, so as best I could.

By the way, what do you think about splitting the functionality into separate parts, e.g.

export async function cli() {
  console.log(c.dim(`\nSetup eslint config ...\n`))

  const pkg = await updatePackageJson()
  await updateEslintFiles(pkg)
  await updateSettingsJson()

  console.log(c.green('\nSuccessful. Now you can update the dependencies and run'), c.dim('eslint . --fix\n')))
}

Or is it better to leave it as it is?

let pkg: Record<string, any>
const pkgPath: string = path.join(cwd, 'package.json')

try {
const pkgContent: string = fs.readFileSync(pkgPath, 'utf-8')
pkg = JSON.parse(pkgContent)
}
catch (error) {
console.log(c.red('Could not find -'), c.dim('package.json'))
process.exit(1)
}

const eslintLastVersion = await execSync(`npm show eslint version --quite`)
const eslintConfigLastVersion = await execSync(`npm show @antfu/eslint-config version --quite`)

const eslintVersion: string = eslintLastVersion?.toString()?.trim()
const eslintConfigVersion: string = eslintConfigLastVersion?.toString()?.trim()

pkg.type = 'module'
injurka marked this conversation as resolved.
Show resolved Hide resolved

const pkgDep = ['dependencies', 'devDependencies']

pkgDep.forEach((depType) => {
if (pkg[depType]) {
Object.keys(pkg[depType]).forEach((key) => {
if (key.includes('eslint') || key.includes('prettier'))
delete pkg[depType][key]
})
}
})

pkg.devDependencies['@antfu/eslint-config'] = eslintConfigVersion
pkg.devDependencies.eslint = eslintVersion
injurka marked this conversation as resolved.
Show resolved Hide resolved

try {
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2))
console.log(c.cyan('Updated -'), c.dim('package.json'))
}
catch (error) {
console.log(c.red('Failed to update -'), c.dim('package.json'))
process.exit(1)
}
// End update package.json

// Update eslint files
const eslintConfigPath: string = path.join(cwd, 'eslint.config.js')
const eslintIgnorePath: string = path.join(cwd, '.eslintignore')
let eslintIgnoreLines: string[] = []

if (fs.existsSync(eslintIgnorePath)) {
const eslintIgnoreContent: string = fs.readFileSync(eslintIgnorePath, 'utf-8')
eslintIgnoreLines = eslintIgnoreContent.split('\n')
}

const eslintConfigContent = `
import antfu from '@antfu/eslint-config';

export default antfu({
${eslintIgnoreLines.length
? `ignores: [
${eslintIgnoreLines?.map(line => `'${line}'`).join(',\n')}
],`
: ''}
});`
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could use parse-gitignore package, as the ignore format is a bit different from globs, the reference here:

https://github.com/antfu/eslint-config-flat-gitignore/blob/60240bb3d1dfea0bf48aaa962e18f15f1547b4eb/src/index.ts#L24-L31

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It didn't work out for me to use parse-gitignore or prompts with esm, so i can to change the import from ejs to cjs in bin/index.js to ../dist/cli/index.cjs. Or use unbuild with alias field. I chose the second option. However, i am not competent in this and do not know how best. My desire to realize exceeds the available knowledge (((

image


const files = fs.readdirSync(cwd)
files.forEach((file) => {
if (file.includes('eslint') || file.includes('prettier'))
fs.unlinkSync(file)
})
injurka marked this conversation as resolved.
Show resolved Hide resolved

try {
fs.writeFileSync(eslintConfigPath, eslintConfigContent)
console.log(c.cyan('Created -'), c.dim('eslint.config.js'))
}
catch (error) {
console.log(c.red('Failed to create -'), c.dim('eslint.config.js'))
}
// End update eslint files

// Update .vscode/settings.json
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A prompt would be nice.

const dotVscodePath: string = path.join(cwd, '.vscode')
const settingsPath: string = path.join(dotVscodePath, 'settings.json')

if (!fs.existsSync(dotVscodePath))
fs.mkdirSync(dotVscodePath)

if (!fs.existsSync(settingsPath))
fs.writeFileSync(settingsPath, '{}')

let settings: Record<string, any> = {}
try {
const settingsContent: string = fs.readFileSync(settingsPath, 'utf8')
const settingsJsonWithoutComments = settingsContent.replace(/\/\/.*|\/\*[\s\S]*?\*\//g, '')
settings = JSON.parse(settingsJsonWithoutComments)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we won't want to remove all comments. Maybe instead of parsing, we insert the text before the last }. Leaving the formating to the ESLint config.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its quite a difficult situation, in the sense that I cant parse it because of the presence of comments and I cant overwrite the fields as such, because I read it as a string line. I tried to do as you said and take into account all the problematic situations, but im not sure that such an implementation is okay 🥴

}
catch (error) {
console.log(c.red('Error when reading a file -'), c.dim('.vscode/settings.json'))
process.exit(1)
}

settings['eslint.experimental.useFlatConfig'] = true
settings['eslint.format.enable'] = true
settings['prettier.enable'] = false
settings['editor.formatOnSave'] = false
settings['editor.codeActionsOnSave'] = {
'source.fixAll.eslint': 'explicit',
'source.organizeImports': 'never',
}
settings['eslint.rules.customizations'] = [
{ rule: '@stylistic/*', severity: 'off' },
{ rule: 'style*', severity: 'off' },
{ rule: '*-indent', severity: 'off' },
{ rule: '*-spacing', severity: 'off' },
{ rule: '*-spaces', severity: 'off' },
{ rule: '*-order', severity: 'off' },
{ rule: '*-dangle', severity: 'off' },
{ rule: '*-newline', severity: 'off' },
{ rule: '*quotes', severity: 'off' },
{ rule: '*semi', severity: 'off' },
]
settings['eslint.validate'] = [
'javascript',
'javascriptreact',
'typescript',
'typescriptreact',
'vue',
'html',
'markdown',
'json',
'jsonc',
'yaml',
]

fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2))
console.log(c.cyan('Updated -'), c.dim('.vscode/settings.json'))
// End update .vscode/settings.json

console.log(c.green('\nSuccessful. Now you can update the dependencies and run'), c.dim('eslint . --fix\n'))
}
8 changes: 5 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { antfu } from './factory'

export * from './types'
export * from './factory'
export * from './configs'
export * from './factory'
export * from './globs'
export * from './plugins'
export * from './types'
export * from './utils'
export * from './globs'

export * from './cli'

export default antfu
95 changes: 95 additions & 0 deletions test/cli.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { join } from 'node:path'
import type { ExecaSyncReturnValue } from 'execa'
import { execaCommandSync } from 'execa'
import fs from 'fs-extra'
import { afterAll, afterEach, beforeAll, expect, it } from 'vitest'

const CLI_PATH = join(__dirname, '../bin/index.js')

const projectName = 'test-app'
const genPath = join(__dirname, projectName)

function run(): ExecaSyncReturnValue {
return execaCommandSync(`node ${CLI_PATH}`, { cwd: genPath })
};

function createMockDir() {
fs.mkdirpSync(genPath)

const pkgJsonContent = {
devDependencies: {
'@custom/eslint-some-config': 'x.x.x',
'@custom/eslint-some-plugin': 'x.x.x',
'eslint-some-config': 'x.x.x',
'eslint-some-plugin': 'x.x.x',
'prettier': 'x.x.x',
},
}
fs.writeFileSync(join(genPath, 'package.json'), JSON.stringify(pkgJsonContent, null, 2))
fs.writeFileSync(join(genPath, '.eslintrc.yml'), '')
fs.writeFileSync(join(genPath, '.eslintignore'), 'some-path\nsome-file')
fs.writeFileSync(join(genPath, '.prettierc'), '')
fs.writeFileSync(join(genPath, '.prettierignore'), 'some-path\nsome-file')
};

beforeAll(() => fs.rm(genPath, { recursive: true, force: true }))
afterEach(() => fs.rm(genPath, { recursive: true, force: true }))
afterAll(() => fs.rm(genPath, { recursive: true, force: true }))

it('package.json updated', () => {
createMockDir()
const { stdout } = run()

const pkgContent: Record<string, any> = JSON.parse(fs.readFileSync(join(genPath, 'package.json'), 'utf-8'))

expect(JSON.stringify(pkgContent.devDependencies)).toContain('eslint')
expect(JSON.stringify(pkgContent.devDependencies)).toContain('@antfu/eslint-config')

expect(stdout).toContain('Updated - package.json')
})

it('.vscode updated', () => {
createMockDir()
run()

const settingsContent: Record<string, any> = JSON.parse(fs.readFileSync(join(genPath, '.vscode', 'settings.json'), 'utf-8'))

const expectedSettings = [
'"eslint.experimental.useFlatConfig":true',
'"prettier.enable":false',
'"editor.formatOnSave":false',
'"eslint.format.enable":true',
'editor.codeActionsOnSave',
'eslint.rules.customizations',
'eslint.validate',
]

expectedSettings.forEach((setting) => {
expect(JSON.stringify(settingsContent)).toContain(setting)
})
})

it('all eslint configs files removed', () => {
createMockDir()
run()

expect(fs.existsSync(join(genPath, '.eslintignore'))).toBeFalsy()
expect(fs.existsSync(join(genPath, '.eslintrc.yml'))).toBeFalsy()
})

it('all prettier configs files removed', () => {
createMockDir()
run()

expect(fs.existsSync(join(genPath, '.prettierignore'))).toBeFalsy()
expect(fs.existsSync(join(genPath, '.prettierrc'))).toBeFalsy()
})

it('ignores files added in eslint.config.js', () => {
createMockDir()
run()

const eslintConfigContent: string = fs.readFileSync(join(genPath, 'eslint.config.js'), 'utf-8').replace(/\s+/g, '')

expect(eslintConfigContent.includes('ignores:[\'some-path\',\'some-file\']')).toBeTruthy()
})