8000 feat(cli): create initial, proof-of-concept CLI by bradzacher · Pull Request #4359 · typescript-eslint/typescript-eslint · GitHub
[go: up one dir, main page]

Skip to content

feat(cli): create initial, proof-of-concept CLI #4359

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

Closed
wants to merge 1 commit into from
Closed
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
38 changes: 38 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ module.exports = {
{
files: ['rollup.config.ts'],
rules: {
// rollup config must be default exported
'import/no-default-export': 'off',
},
},
Expand All @@ -311,5 +312,42 @@ module.exports = {
'no-console': 'off',
},
},
{
files: ['*.{js,jsx}'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
},
},
// CLI lint configs
{
files: [
'packages/cli/bin/**/*.{ts,js}',
'packages/cli/src/reporters/Reporter.ts',
],
rules: {
'no-console': 'off',
},
},
{
files: ['packages/cli/bin/**/*.js'],
rules: {
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
},
},
{
files: ['packages/cli/**/*.{ts,tsx,js}'],
rules: {
'@typescript-eslint/consistent-type-imports': [
'error',
{ prefer: 'type-imports', disallowTypeAnnotations: true },
],
'@typescript-eslint/consistent-type-exports': 'error',
'import/first': 'error',
'import/newline-after-import': 'error',
'import/no-duplicates': 'error',
'simple-import-sort/imports': 'error',
},
},
],
};
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
"lint-fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"lint-markdown-fix": "yarn lint-markdown --fix",
"lint-markdown": "markdownlint \"**/*.md\" --config=.markdownlint.json --ignore-path=.markdownlintignore",
"lint": "cross-env NODE_OPTIONS=\"--max-old-space-size=16384\" eslint . --ext .js,.jsx,.ts,.tsx",
"postinstall": "yarn husky install && yarn build",
"lint": "ts-eslint -p ./tsconfig.eslint.json -p \"packages/*/tsconfig.json\"",
"postinstall": "yarn patch-package && yarn husky install && yarn build",
"pre-commit": "yarn lint-staged",
"pre-push": "yarn check-format",
"start": "nx run website:start",
Expand Down Expand Up @@ -75,10 +75,12 @@
"@types/marked": "^3.0.2",
"@types/ncp": "^2.0.5",
"@types/node": "^16.11.4",
"@types/node-fetch": "^3.0.3",
"@types/prettier": "^2.4.2",
"@types/rimraf": "^3.0.2",
"@types/semver": "^7.3.9",
"@types/tmp": "^0.2.2",
"@types/yargs": "^17.0.8",
"all-contributors-cli": "^6.20.0",
"cross-env": "^7.0.3",
"cspell": "^5.12.3",
Expand All @@ -101,6 +103,7 @@
"markdownlint-cli": "^0.29.0",
"ncp": "^2.0.0",
"node-fetch": "^3.0.0",
"patch-package": "^6.4.7",
"prettier": "^2.5.0",
"pretty-format": "^27.3.1",
"rimraf": "^3.0.2",
Expand Down
21 changes: 21 additions & 0 deletions packages/cli/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 TypeScript ESLint and other contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 15 additions & 0 deletions packages/cli/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<h1 align="center">typescript-eslint CLI</h1>

<p align="center">
<img src="https://github.com/typescript-eslint/typescript-eslint/workflows/CI/badge.svg" alt="CI" />
<a href="https://www.npmjs.com/package/@typescript-eslint/cli"><img src="https://img.shields.io/npm/v/@typescript-eslint/cli.svg?style=flat-square" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/package/@typescript-eslint/cli"><img src="https://img.shields.io/npm/dm/@typescript-eslint/cli.svg?style=flat-square" alt="NPM Downloads" /></a>
</p>

CLI for coordinating lint runs that use typescript-eslint.

TODO: docs on CLI args

## Contributing

[See the contributing guide here](../../CONTRIBUTING.md)
76 changes: 76 additions & 0 deletions packages/cli/bin/ts-eslint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#!/usr/bin/env node

// @ts-check

if (process.env.USE_TS_ESLINT_SRC == null) {
// to use V8's code cache to speed up instantiation time
require('v8-compile-cache');
}

/**
* @param {unknown} thing
* @returns {thing is Record<string, unknown>}
*/
function isObject(thing) {
return typeof thing === 'object' && thing != null;
}

/**
* Get the error message of a given value.
* @param {unknown} error The value to get.
* @returns {string} The error message.
*/
function getErrorMessage(error) {
// Lazy loading because this is used only if an error happened.
const util = require('util');

if (!isObject(error)) {
return String(error);
}

// Use the stacktrace if it's an error object.
if (typeof error.stack === 'string') {
return error.stack;
}

// Otherwise, dump the object.
return util.format('%o', error);
}

/**
* Catch and report unexpected error.
* @param {unknown} error The thrown error object.
* @returns {void}
*/
function onFatalError(error) {
process.exitCode = 2;
const message = getErrorMessage(error);
console.error(`
An unhandled exception occurred!
${message}`);
}

(async function main() {
process.on('uncaughtException', onFatalError);
process.on('unhandledRejection', onFatalError);

/** @type {import('../src/index')} */
const cli = (() => {
if (process.env.USE_TS_ESLINT_SRC == null) {
// using an ignore because after a build a ts-expect-error will no longer error because TS will follow the
// build maps to the source files...
// @ts-ignore - have to reference the built file, not the src file
return require('../dist/index');
}

// ensure ts-node is registered correctly
// eslint-disable-next-line import/no-extraneous-dependencies
require('ts-node').register({
transpileOnly: true,
project: require('path').resolve(__dirname, '..', 'tsconfig.json'),
});
return require('../src/index');
})();

await cli.execute();
})().catch(onFatalError);
20 changes: 20 additions & 0 deletions packages/cli/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use strict';

// @ts-check
/** @type {import('@jest/types').Config.InitialOptions} */
module.exports = {
globals: {
'ts-jest': {
isolatedModules: true,
},
},
testEnvironment: 'node',
transform: {
['^.+\\.tsx?$']: 'ts-jest',
},
testRegex: ['./tests/.+\\.test\\.ts$'],
collectCoverage: false,
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
coverageReporters: ['text-summary', 'lcov'],
};
77 changes: 77 additions & 0 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
{
"name": "@typescript-eslint/cli",
"version": "5.9.0",
"description": "TypeScript-ESLint CLI",
"keywords": [
"eslint",
"typescript",
"estree",
"cli"
],
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"files": [
"dist",
"package.json",
"README.md",
"LICENSE"
],
"repository": {
"type": "git",
"url": "https://github.com/typescript-eslint/typescript-eslint.git",
"directory": "packages/cli"
},
"bugs": {
"url": "https://github.com/typescript-eslint/typescript-eslint/issues"
},
"license": "MIT",
"main": "dist/index.js",
"bin": {
"ts-eslint": "./bin/ts-eslint.js"
},
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc -b tsconfig.build.json",
"postbuild": "downlevel-dts dist _ts3.4/dist",
"clean": "tsc -b tsconfig.build.json --clean",
"postclean": "rimraf dist && rimraf _ts3.4 && rimraf coverage",
"format": "prettier --write \"./**/*.{ts,js,json,md}\" --ignore-path ../../.prettierignore",
"lint": "eslint . --ext .js,.ts --ignore-path='../../.eslintignore'",
"typecheck": "tsc -p tsconfig.json --noEmit",
"ts-eslint": "USE_TS_ESLINT_SRC=1 ts-node --transpile-only ./bin/ts-eslint.js"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"typesVersions": {
"<3.8": {
"*": [
"_ts3.4/*"
]
}
},
"dependencies": {
"@typescript-eslint/experimental-utils": "5.9.0",
"debug": "^4.3.2",
"globby": "^11.0.4",
"ink": "^3.2.0",
"ink-use-stdout-dimensions": "^1.0.5",
"is-glob": "^4.0.3",
"jest-worker": "^27.4.5",
"react": "^17.0.2",
"semver": "^7.3.5",
"v8-compile-cache": "^2.3.0",
"yargs": "^17.3.1"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0",
"typescript": "*"
},
"devDependencies": {
"@types/is-glob": "*",
"@types/semver": "*",
"@types/yargs": "*"
}
}
5 changes: 5 additions & 0 deletions packages/cli/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"root": "packages/cli",
"type": "library",
"implicitDependencies": []
}
31 changes: 31 additions & 0 deletions packages/cli/src/FileEnumerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { version } from 'eslint/package.json';
import * as semver from 'semver';

const isESLintV8 = semver.major(version) >= 8;

declare class _FileEnumerator {
constructor(options?: {
readonly cwd?: string;
readonly extensions?: string | null;
readonly globInputPaths?: boolean;
readonly errorOnUnmatchedPattern?: boolean;
readonly ignore?: boolean;
});

iterateFiles(
patternOrPatterns: string | readonly string[],
): IterableIterator<{
readonly filePath: string;
readonly config: unknown;
readonly ignored: boolean;
}>;
}

const FileEnumerator = (
isESLintV8
? // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
require('eslint/use-at-your-own-risk').FileEnumerator
: require('eslint/lib/cli-engine/file-enumerator')
) as typeof _FileEnumerator;

export { FileEnumerator };
54 changes: 54 additions & 0 deletions packages/cli/src/commands/Command.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import type { ArgumentsCamelCase, CommandBuilder, CommandModule } from 'yargs';

import type { Reporter } from '../reporters/Reporter';

// eslint-disable-next-line @typescript-eslint/ban-types
export interface Command<TRawOpts = {}, TProcessedOpts = {}>
extends CommandModule<
TRawOpts & GlobalOptions,
TProcessedOpts & GlobalOptions
> {
/** object declaring the options the command accepts, or a function accepting and returning a yargs instance */
builder: CommandBuilder<
TRawOpts & GlobalOptions,
TProcessedOpts & GlobalOptions
>;
/** string used as the description for the command in help text, use `false` for a hidden command */
describe: string;
/** a function which will be passed the parsed argv. */
handler: (
args: ArgumentsCamelCase<TProcessedOpts & GlobalOptions>,
) => Promise<void>;
}

export interface CommandNoOpts extends CommandModule {
/** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */
command: ReadonlyArray<string> | string;
/** string used as the description for the command in help text, use `false` for a hidden command */
describe: string;
/** a function which will be passed the parsed argv. */
handler: () => void | Promise<void>;
}

export enum ReporterConfig {
ink = 'ink',
plain = 'plain',
}

// numbering is important as each level includes the prior levels
// eg level >= LogLevel.error should include both info and debug
export enum LogLevel {
error = 0,
info = 1,
debug = 2,
}

export interface GlobalOptionsRaw {
logLevel: keyof typeof LogLevel;
reporter: ReporterConfig;
}

export interface GlobalOptions {
logLevel: LogLevel;
reporter: Reporter;
}
Loading
155F
0