Socket
Socket
Sign inDemoInstall

pedantic

Package Overview
Dependencies
Maintainers
1
Versions
38
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pedantic - npm Package Compare versions

Comparing version 1.2.1 to 2.0.0

format.js

16

CHANGELOG.md

@@ -6,2 +6,18 @@ # Change Log

# [2.0.0](https://github.com/4Catalyzer/cli/compare/pedantic@1.2.1...pedantic@2.0.0) (2019-03-05)
### Features
* add lint command ([5e1e1eb](https://github.com/4Catalyzer/cli/commit/5e1e1eb))
### BREAKING CHANGES
* split pedantic into two commands
## [1.2.1](https://github.com/4Catalyzer/cli/compare/pedantic@1.2.0...pedantic@1.2.1) (2019-02-26)

@@ -8,0 +24,0 @@

13

cli.js
#!/usr/bin/env node
require('@4c/cli-core/createCliFromCommand')(require('./command'));
const yargs = require('yargs');
yargs
.help()
.alias('h', 'help')
.version()
.alias(`v`, `version`)
.wrap(yargs.terminalWidth())
.strict()
.command(require('./format'))
.command(require('./lint'))
.parse(process.argv.slice(2));

162

lib.js
const path = require('path');
const chalk = require('chalk');
const { promises: fs } = require('fs');
const { default: sortImports } = require('import-sort');
const { debuglog } = require('util');
const prettier = require('prettier');
const { getConfig } = require('import-sort-config');
const ConsoleUtilities = require('@4c/cli-core/ConsoleUtilities');
const {
spinner,
chalk,
stripAnsi,
table,
} = require('@4c/cli-core/ConsoleUtilities');
const ArgUtilities = require('@4c/cli-core/ArgUtilities');
const sortImports = require('./sort-imports');
const runPrettier = require('./prettier');
const Linter = require('./Linter');
const debug = debuglog('pedantic');
const DEFAULT_SORT_CONFIGS = {
'.js, .jsx, .mjs, .ts, .tsx': {
parser: require.resolve('import-sort-parser-babylon'),
style: require.resolve('@4c/import-sort/style'),
},
};
function sortFileImports(content, filePath, includeTypeDefs = false) {
if (!includeTypeDefs && filePath.endsWith('.d.ts')) {
debug('Not attempting to sort imports in type def file:', filePath);
return content;
}
const resolvedConfig = getConfig(
path.extname(filePath),
path.dirname(filePath),
DEFAULT_SORT_CONFIGS,
);
if (!resolvedConfig || !resolvedConfig.parser || !resolvedConfig.style) {
debug('could not resolve import sort config for:', filePath);
return content;
}
const { parser, style, options } = resolvedConfig;
const result = sortImports(content, parser, style, filePath, options);
return result.code;
}
async function runPrettier(content, filePath, ignorePath = '.prettierignore') {
const { ignored } = await prettier.getFileInfo(filePath, { ignorePath });
if (ignored) return content;
const options = await prettier.resolveConfig(filePath);
return prettier.format(content, { filepath: filePath, ...options });
}
/**
* possible combinations are:
* - fix: fix errors, don't report non-fixable errors
* - fix & check: fix anything that's fixable and report non-fixable errors
* - check: report fixable and non-fixable errors
*/
module.exports = async (
filePatterns,
{ cwd = process.cwd(), ignorePath, ignoreNodeModules, write, check },
{ cwd = process.cwd(), ignorePath, ignoreNodeModules, fix, check },
) => {
debug('patterns:', filePatterns, 'write:', write, 'cwd', cwd);
const spinner = ConsoleUtilities.spinner('Checking formatting…');
debug('patterns:', filePatterns, 'fix:', fix, 'cwd', cwd);
const progress = spinner('Checking formatting…');
const linter = new Linter({ cwd, fix, check });
const filePaths = await ArgUtilities.resolveFilePatterns(filePatterns, {
cwd,
ignoreNodeModules,
cwd,
absolute: true,
});

@@ -66,3 +41,3 @@

process.exitCode = 1;
spinner.fail(
progress.fail(
"The provided file patterns didn't match any files: ",

@@ -72,3 +47,6 @@ filePatterns.join(', '),

}
let numDifferent = 0;
const needsFormatting = [];
try {

@@ -80,7 +58,19 @@ await Promise.all(

// Prettier has the largest pool of files it can format so if
// it can't parse it assume nothing else can and move on
const canParse = await runPrettier.canParse(filePath);
if (!canParse) {
return;
}
try {
content = await fs.readFile(filePath, 'utf8');
code = sortFileImports(content, filePath);
code = sortImports(content, filePath);
code = await runPrettier(code, filePath, ignorePath);
if (code !== content) needsFormatting.push(filePath);
code = linter.check(code, filePath);
} catch (err) {

@@ -93,15 +83,13 @@ // Don't exit the process if one file failed

if (content === code) return;
if (content === code) {
return;
}
numDifferent++;
if (check) {
// we don't want these to replace each other
if (spinner.isSpinning) spinner.stopAndPersist();
console.log(` -> ${chalk.dim(filePath)}`);
} else if (write) {
spinner.text = chalk.dim(path.relative(cwd, filePath));
progress.text = chalk.dim(path.relative(cwd, filePath));
if (fix) {
await fs.writeFile(filePath, code, 'utf8');
} else {
spinner.stopAndPersist();
} else if (!check) {
process.stdout.write(code);

@@ -112,28 +100,54 @@ }

} catch (err) {
spinner.stop();
progress.stop();
throw err;
}
if (!numDifferent) {
spinner.succeed(
`All ${filePaths.length} of matched files are properly formatted`,
if (!numDifferent && !linter.hasChanges) {
progress.succeed(
`All ${
filePaths.length
} of matched files are properly formatted and linted`,
);
return;
}
if (check) {
process.exitCode = 1;
const files = `file${numDifferent === 1 ? '' : 's'}`;
progress.stop();
if (!check) {
if (fix) {
progress.succeed(
`Code style issues fixed in ${numDifferent} of ${
filePaths.length
} ${files} checked.`,
);
}
return;
}
const files = `file${numDifferent === 1 ? '' : 's'}`;
if (check) {
spinner.fail(
`Code style issues found in the above ${numDifferent} ${files}`,
process.exitCode = 1;
console.log(linter.output());
if (!fix) {
let output = '\n';
output += `${table(
needsFormatting.map(filePath => [
'',
path.relative(cwd, filePath).trim(),
]),
{
align: ['', 'l'],
stringLength: str => stripAnsi(str).length,
},
)}
`;
output += chalk.red.bold(
`\u2716 ${needsFormatting.length} Formatting issues`,
);
} else if (write) {
spinner.succeed(
`Code style issues fixed in ${numDifferent} of ${
filePaths.length
} ${files} checked.`,
);
console.log(output);
}
};
{
"name": "pedantic",
"version": "1.2.1",
"version": "2.0.0",
"main": "lib.js",

@@ -10,2 +10,5 @@ "repository": {

},
"scripts": {
"test": "jest"
},
"author": "4Catalyzer",

@@ -28,11 +31,13 @@ "license": "MIT",

"dependencies": {
"@4c/cli-core": "^1.3.0",
"@4c/cli-core": "^1.4.0",
"@4c/import-sort": "^4.3.1",
"chalk": "^2.4.2",
"eslint": "^5.14.1",
"import-sort": "^6.0.0",
"import-sort-config": "^6.0.0",
"import-sort-parser-babylon": "^6.0.0",
"prettier": "^1.16.4"
"prettier": "^1.16.4",
"yargs": "^13.2.1"
},
"gitHead": "99f72ccba79d5c364e68489388db8e3d0c3e001c"
"gitHead": "cd60e4a713d47497146ebbc5449755d0fc05d2b3"
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc