eslint#CLIEngine TypeScript Examples
The following examples show how to use
eslint#CLIEngine.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts From garment with MIT License | 6 votes |
function filterResultsBySeverity(
results: CLIEngine.LintResult[],
severity: SeverityLevel
) {
const filtered: CLIEngine.LintResult[] = [];
const count = (sevLevel: SeverityLevel, messagesSum: number) => {
return severity === sevLevel ? messagesSum : 0;
};
results.forEach(result => {
const filteredMessages = result.messages.filter(
mess => mess.severity === severity
);
if (filteredMessages.length > 0) {
filtered.push({
...result,
messages: filteredMessages,
errorCount: count(SeverityLevel.Error, filteredMessages.length),
warningCount: count(SeverityLevel.Warning, filteredMessages.length),
fixableErrorCount: result.fixableErrorCount,
fixableWarningCount: 0
});
}
});
return filtered;
}
Example #2
Source File: lint.test.ts From ytdl with MIT License | 6 votes |
describe('Lint', () => {
it('Check for linting errors', () => {
const cli = new CLIEngine({ useEslintrc: true });
const report = cli.executeOnFiles(['src/**/*.ts', 'test/**/*.ts']);
try {
expect(report.errorCount).to.equal(0);
} catch (err) {
const errorFiles: string[] = [];
report.results.forEach((result) => {
if (result.errorCount !== 0) {
errorFiles.push(`\n\t${result.filePath}`);
}
});
const lintError = new Error(errorFiles.toString());
lintError.name = 'LintError';
throw lintError;
}
});
});
Example #3
Source File: plugin.build.ts From grafana-chinese with Apache License 2.0 | 5 votes |
lintPlugin = useSpinner<Fixable>('Linting', async ({ fix } = {}) => {
try {
// Show a warning if the tslint file exists
await access(resolvePath(process.cwd(), 'tslint.json'));
console.log('\n');
console.log('--------------------------------------------------------------');
console.log('NOTE: @grafana/toolkit has migrated to use eslint');
console.log('Update your configs to use .eslintrc rather than tslint.json');
console.log('--------------------------------------------------------------');
} catch {
// OK: tslint does not exist
}
// @todo should remove this because the config file could be in a parent dir or within package.json
const configFile = await globby(resolvePath(process.cwd(), '.eslintrc?(.cjs|.js|.json|.yaml|.yml)')).then(
filePaths => {
if (filePaths.length > 0) {
return filePaths[0];
} else {
return resolvePath(__dirname, '../../config/eslint.plugin.json');
}
}
);
const cli = new CLIEngine({
configFile,
fix,
});
const report = cli.executeOnFiles(await getTypescriptSources());
if (fix) {
CLIEngine.outputFixes(report);
}
const { errorCount, results, warningCount } = report;
if (errorCount > 0 || warningCount > 0) {
const formatter = cli.getFormatter();
console.log('\n');
console.log(formatter(results));
console.log('\n');
throw new Error(`${errorCount + warningCount} linting errors found in ${results.length} files`);
}
})
Example #4
Source File: lintUtils.ts From design-systems-cli with MIT License | 4 votes |
/** Lint JS */
async function lintJS(args: LintArgs): Promise<number> {
const root = getMonorepoRoot();
const isRoot = root === process.cwd();
const cacheLocation = path.join(tmpdir(), `eslint-${monorepoName()}`);
const lastCacheUpdate = getLastEdited(cacheLocation);
const lastEslintRcUpdate = getLastEdited(path.join(root, '.eslintrc'));
logger.debug(`Using .eslintcache located at: "${cacheLocation}"`);
logger.debug(`Cache was last updated: ${lastCacheUpdate}`);
logger.debug(`RC was last updated: ${lastEslintRcUpdate}`);
// Eslint cache will only re-run a file if a file has changed.
// This doesn't interact well with plugins that rely on non-js files
//
// We need to also bust the cache in the following situations
//
// - .eslintrc - when rules change
// - **/package.json - when new deps are added (for import plugin)
let bustCache = false;
const packages = (await glob(['**/package.json', '!**/node_modules'])).map(
getLastEdited
);
if (lastCacheUpdate > 0) {
if (lastEslintRcUpdate > lastCacheUpdate) {
logger.debug(`RC has been updated since last run, deleting cache.`);
bustCache = true;
} else if (packages.find((c) => c > lastCacheUpdate)) {
logger.debug(
`A package.json has been updated since last run, deleting cache.`
);
bustCache = true;
}
}
const linter = new CLIEngine({
fix: args.fix,
cache: !args.noCache && !bustCache,
cacheLocation,
extensions: ['ts', 'tsx', 'js', 'jsx', 'mdx', 'json'],
ignorePath: path.join(__dirname, '../../.eslintignore'),
reportUnusedDisableDirectives: true,
});
const lintFiles = isRoot ? getPackageFolders() : ['src'];
const report = linter.executeOnFiles(
args.files ? files(args, 'ts|tsx|js|jsx|mdx|json') : lintFiles
);
const maxWarnings = args.maxWarnings ? args.maxWarnings : 1;
if (args.fix) {
CLIEngine.outputFixes(report);
}
const annotate = Boolean(
args.annotate || (process.env.CLI_APP_ID && process.env.CLI_PRIVATE_KEY)
);
const formattedResults = jsFormatter(report.results);
if (report.errorCount > 0) {
logger.error('Project contains JS errors', formattedResults);
} else if (report.warningCount >= maxWarnings) {
logger.warn(
`Project contains JS warnings (maximum allowable: ${maxWarnings - 1})`,
formattedResults
);
} else if (report.warningCount > 0) {
logger.warn('Project contains JS warnings', formattedResults);
} else {
logger.success('JS');
}
if (annotate) {
await createESLintAnnotations(report.results);
}
return report.errorCount > 0 || report.warningCount >= maxWarnings ? 1 : 0;
}