diff --git a/README.md b/README.md index 0b2a7ca46..d30042762 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ Options: -r, --relative pass relative filepaths to tasks (default: false) -x, --shell skip parsing of tasks for better shell support (default: false) + -v, --verbose always show task output (default: false) -h, --help output usage information ``` @@ -88,6 +89,7 @@ Options: - **`--quiet`**: Supress all CLI output, except from tasks. - **`--relative`**: Pass filepaths relative to `process.cwd()` (where `lint-staged` runs) to tasks. Default is `false`. - **`--shell`**: By default linter commands will be parsed for speed and security. This has the side-effect that regular shell scripts might not work as expected. You can skip parsing of commands with this option. +- **`--verbose`**: Show task output even when tasks succeed. By default only failed output is shown. ## Configuration @@ -199,7 +201,7 @@ type TaskFn = (filenames: string[]) => string | string[] | Promise filenames.map(filename => `prettier --write '${filename}'`) + '**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`) } ``` @@ -217,7 +219,8 @@ module.exports = { ```js // .lintstagedrc.js module.exports = { - '**/*.js?(x)': filenames => (filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`) + '**/*.js?(x)': (filenames) => + filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}` } ``` @@ -228,7 +231,7 @@ module.exports = { const micromatch = require('micromatch') module.exports = { - '*': allFiles => { + '*': (allFiles) => { const match = micromatch(allFiles, ['*.js', '*.ts']) return `eslint ${match.join(' ')}` } @@ -244,7 +247,7 @@ If for some reason you want to ignore files from the glob match, you can use `mi const micromatch = require('micromatch') module.exports = { - '*.js': files => { + '*.js': (files) => { // from `files` filter those _NOT_ matching `*test.js` const match = micromatch.not(files, '*test.js') return `eslint ${match.join(' ')}` @@ -260,9 +263,9 @@ Please note that for most cases, globs can achieve the same effect. For the abov const path = require('path') module.exports = { - '*.ts': absolutePaths => { + '*.ts': (absolutePaths) => { const cwd = process.cwd() - const relativePaths = absolutePaths.map(file => path.relative(cwd, file)) + const relativePaths = absolutePaths.map((file) => path.relative(cwd, file)) return `ng lint myProjectName --files ${relativePaths.join(' ')}` } } @@ -422,12 +425,16 @@ Parameters to `lintStaged` are equivalent to their CLI counterparts: ```js const success = await lintStaged({ + allowEmpty: false, + concurrent: true, configPath: './path/to/configuration/file', + debug: false, maxArgLength: null, - relative: false, - shell: false, quiet: false, - debug: false + relative: false, + shell: false + stash: true, + verbose: false }) ``` @@ -435,14 +442,16 @@ You can also pass config directly with `config` option: ```js const success = await lintStaged({ - config: { - '*.js': 'eslint --fix' - }, + allowEmpty: false, + concurrent: true, + config: { '*.js': 'eslint --fix' }, + debug: false, maxArgLength: null, + quiet: false, relative: false, shell: false, - quiet: false, - debug: false + stash: true, + verbose: false }) ``` @@ -518,7 +527,7 @@ const { CLIEngine } = require('eslint') const cli = new CLIEngine({}) module.exports = { - '*.js': files => - 'eslint --max-warnings=0 ' + files.filter(file => !cli.isPathIgnored(file)).join(' ') + '*.js': (files) => + 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' ') } ``` diff --git a/bin/lint-staged.js b/bin/lint-staged.js index 0589a0c63..0f9307ea3 100755 --- a/bin/lint-staged.js +++ b/bin/lint-staged.js @@ -40,6 +40,7 @@ cmdline .option('-q, --quiet', 'disable lint-staged’s own console output', false) .option('-r, --relative', 'pass relative filepaths to tasks', false) .option('-x, --shell', 'skip parsing of tasks for better shell support', false) + .option('-v, --verbose', 'always show task output', false) .parse(process.argv) if (cmdline.debug) { @@ -75,7 +76,8 @@ const options = { stash: !!cmdline.stash, // commander inverts `no-` flags to `!x` quiet: !!cmdline.quiet, relative: !!cmdline.relative, - shell: !!cmdline.shell + shell: !!cmdline.shell, + verbose: !!cmdline.verbose } debug('Options parsed from command-line:', options) diff --git a/lib/index.js b/lib/index.js index 217cb66f8..1a3a67f3f 100644 --- a/lib/index.js +++ b/lib/index.js @@ -5,7 +5,10 @@ const { cosmiconfig } = require('cosmiconfig') const debugLog = require('debug')('lint-staged') const stringifyObject = require('stringify-object') +const { PREVENTED_EMPTY_COMMIT, GIT_ERROR, RESTORE_STASH_EXAMPLE } = require('./messages') +const printTaskOutput = require('./printTaskOutput') const runAll = require('./runAll') +const { ApplyEmptyCommitError, GetBackupStashError, GitError } = require('./symbols') const validateConfig = require('./validateConfig') const errConfigNotFound = new Error('Config could not be found') @@ -51,6 +54,7 @@ function loadConfig(configPath) { * @param {boolean} [options.relative] - Pass relative filepaths to tasks * @param {boolean} [options.shell] - Skip parsing of tasks for better shell support * @param {boolean} [options.stash] - Enable the backup stash, and revert in case of errors + * @param {boolean} [options.verbose] - Always show task output * @param {Logger} [logger] * * @returns {Promise} Promise of whether the linting passed or failed @@ -66,7 +70,8 @@ module.exports = async function lintStaged( quiet = false, relative = false, shell = false, - stash = true + stash = true, + verbose = false } = {}, logger = console ) { @@ -97,16 +102,37 @@ module.exports = async function lintStaged( delete process.env.GIT_LITERAL_PATHSPECS try { - await runAll( - { allowEmpty, concurrent, config, debug, maxArgLength, stash, quiet, relative, shell }, + const ctx = await runAll( + { + allowEmpty, + concurrent, + config, + debug, + maxArgLength, + quiet, + relative, + shell, + stash, + verbose + }, logger ) - debugLog('tasks were executed successfully!') + debugLog('Tasks were executed successfully!') + printTaskOutput(ctx, logger) return true } catch (runAllError) { - if (runAllError && runAllError.ctx && runAllError.ctx.output) { - logger.error(...runAllError.ctx.output) + const { ctx } = runAllError + if (ctx.errors.has(ApplyEmptyCommitError)) { + logger.warn(PREVENTED_EMPTY_COMMIT) + } else if (ctx.errors.has(GitError) && !ctx.errors.has(GetBackupStashError)) { + logger.error(GIT_ERROR) + if (ctx.shouldBackup) { + // No sense to show this if the backup stash itself is missing. + logger.error(RESTORE_STASH_EXAMPLE) + } } + + printTaskOutput(ctx, logger) return false } } catch (lintStagedError) { diff --git a/lib/makeCmdTasks.js b/lib/makeCmdTasks.js index 2b1682f3c..2045a5aae 100644 --- a/lib/makeCmdTasks.js +++ b/lib/makeCmdTasks.js @@ -13,8 +13,9 @@ const debug = require('debug')('lint-staged:make-cmd-tasks') * @param {Array} options.files * @param {string} options.gitDir * @param {Boolean} shell + * @param {Boolean} verbose */ -module.exports = async function makeCmdTasks({ commands, files, gitDir, shell }) { +module.exports = async function makeCmdTasks({ commands, files, gitDir, shell, verbose }) { debug('Creating listr tasks for commands %o', commands) const commandArray = Array.isArray(commands) ? commands : [commands] const cmdTasks = [] @@ -49,7 +50,7 @@ module.exports = async function makeCmdTasks({ commands, files, gitDir, shell }) cmdTasks.push({ title, command, - task: resolveTaskFn({ command, files, gitDir, isFn, shell }) + task: resolveTaskFn({ command, files, gitDir, isFn, shell, verbose }) }) } } diff --git a/lib/messages.js b/lib/messages.js index d5a99fdf3..7f81c64a2 100644 --- a/lib/messages.js +++ b/lib/messages.js @@ -1,16 +1,22 @@ 'use strict' const chalk = require('chalk') -const symbols = require('log-symbols') +const { error, info, warning } = require('log-symbols') -const NO_STAGED_FILES = `${symbols.info} No staged files found.` +const NOT_GIT_REPO = chalk.redBright(`${error} Current directory is not a git directory!`) + +const FAILED_GET_STAGED_FILES = chalk.redBright(`${error} Failed to get staged files!`) + +const NO_STAGED_FILES = `${info} No staged files found.` + +const NO_TASKS = `${info} No staged files match any configured task.` const skippingBackup = (hasInitialCommit) => { const reason = hasInitialCommit ? '`--no-stash` was used' : 'there’s no initial commit yet' - return `${symbols.warning} ${chalk.yellow(`Skipping backup because ${reason}.\n`)}` + return `${warning} ${chalk.yellow(`Skipping backup because ${reason}.\n`)}` } -const DEPRECATED_GIT_ADD = `${symbols.warning} ${chalk.yellow( +const DEPRECATED_GIT_ADD = `${warning} ${chalk.yellow( `Some of your tasks use \`git add\` command. Please remove it from the config since all modifications made by tasks will be automatically added to the git commit index.` )} ` @@ -19,10 +25,10 @@ const TASK_ERROR = 'Skipped because of errors from tasks.' const SKIPPED_GIT_ERROR = 'Skipped because of previous git error.' -const GIT_ERROR = `\n ${symbols.error} ${chalk.red(`lint-staged failed due to a git error.`)}` +const GIT_ERROR = `\n ${error} ${chalk.red(`lint-staged failed due to a git error.`)}` const PREVENTED_EMPTY_COMMIT = ` - ${symbols.warning} ${chalk.yellow(`lint-staged prevented an empty git commit. + ${warning} ${chalk.yellow(`lint-staged prevented an empty git commit. Use the --allow-empty option to continue, or check your task configuration`)} ` @@ -34,7 +40,10 @@ const RESTORE_STASH_EXAMPLE = ` Any lost modifications can be restored from a g ` module.exports = { + NOT_GIT_REPO, + FAILED_GET_STAGED_FILES, NO_STAGED_FILES, + NO_TASKS, skippingBackup, DEPRECATED_GIT_ADD, TASK_ERROR, diff --git a/lib/printTaskOutput.js b/lib/printTaskOutput.js new file mode 100644 index 000000000..1a8f6c7d3 --- /dev/null +++ b/lib/printTaskOutput.js @@ -0,0 +1,16 @@ +'use strict' + +/** + * Handle logging of listr `ctx.output` to the specified `logger` + * @param {Object} ctx - The listr initial state + * @param {Object} logger - The logger + */ +const printTaskOutput = (ctx = {}, logger) => { + if (!Array.isArray(ctx.output)) return + const log = ctx.errors && ctx.errors.size > 0 ? logger.error : logger.log + for (const line of ctx.output) { + log(line) + } +} + +module.exports = printTaskOutput diff --git a/lib/resolveTaskFn.js b/lib/resolveTaskFn.js index 70d14d8f0..f154ca8b8 100644 --- a/lib/resolveTaskFn.js +++ b/lib/resolveTaskFn.js @@ -4,15 +4,17 @@ const { redBright, dim } = require('chalk') const execa = require('execa') const debug = require('debug')('lint-staged:task') const { parseArgsStringToArgv } = require('string-argv') -const { error } = require('log-symbols') +const { error, info } = require('log-symbols') const { getInitialState } = require('./state') const { TaskError } = require('./symbols') +const getTag = ({ code, killed, signal }) => signal || (killed && 'KILLED') || code || 'FAILED' + /** - * Create a failure message dependding on process result. + * Handle task console output. * - * @param {string} linter + * @param {string} command * @param {Object} result * @param {string} result.stdout * @param {string} result.stderr @@ -22,23 +24,39 @@ const { TaskError } = require('./symbols') * @param {Object} ctx * @returns {Error} */ -const makeErr = (command, result, ctx) => { - ctx.errors.add(TaskError) - const { code, killed, signal, stderr, stdout } = result - - const tag = signal || (killed && 'KILLED') || code || 'FAILED' - +const handleOutput = (command, result, ctx, isError = false) => { + const { stderr, stdout } = result const hasOutput = !!stderr || !!stdout + if (hasOutput) { - const errorTitle = redBright(`${error} ${command}:`) - const output = ['', errorTitle].concat(stderr ? [stderr] : []).concat(stdout ? [stdout] : []) + const outputTitle = isError ? redBright(`${error} ${command}:`) : `${info} ${command}:` + const output = ['', outputTitle].concat(stderr ? [stderr] : []).concat(stdout ? [stdout] : []) ctx.output.push(output.join('\n')) } else { // Show generic error when task had no output + const tag = getTag(result) const message = redBright(`\n${error} ${command} failed without output (${tag}).`) ctx.output.push(message) } +} +/** + * Create a error output dependding on process result. + * + * @param {string} command + * @param {Object} result + * @param {string} result.stdout + * @param {string} result.stderr + * @param {boolean} result.failed + * @param {boolean} result.killed + * @param {string} result.signal + * @param {Object} ctx + * @returns {Error} + */ +const makeErr = (command, result, ctx) => { + ctx.errors.add(TaskError) + handleOutput(command, result, ctx, true) + const tag = getTag(result) return new Error(`${redBright(command)} ${dim(`[${tag}]`)}`) } @@ -52,9 +70,18 @@ const makeErr = (command, result, ctx) => { * @param {Array} options.files — Filepaths to run the linter task against * @param {Boolean} [options.relative] — Whether the filepaths should be relative * @param {Boolean} [options.shell] — Whether to skip parsing linter task for better shell support + * @param {Boolean} [options.verbose] — Always show task verbose * @returns {function(): Promise>} */ -module.exports = function resolveTaskFn({ command, files, gitDir, isFn, relative, shell = false }) { +module.exports = function resolveTaskFn({ + command, + files, + gitDir, + isFn, + relative, + shell = false, + verbose = false +}) { const [cmd, ...args] = parseArgsStringToArgv(command) debug('cmd:', cmd) debug('args:', args) @@ -77,5 +104,9 @@ module.exports = function resolveTaskFn({ command, files, gitDir, isFn, relative if (result.failed || result.killed || result.signal != null) { throw makeErr(command, result, ctx) } + + if (verbose) { + handleOutput(command, result, ctx) + } } } diff --git a/lib/runAll.js b/lib/runAll.js index c0796c3f6..d891ccccc 100644 --- a/lib/runAll.js +++ b/lib/runAll.js @@ -5,6 +5,7 @@ const { Listr } = require('listr2') const chunkFiles = require('./chunkFiles') +const debugLog = require('debug')('lint-staged:run') const execGit = require('./execGit') const generateTasks = require('./generateTasks') const getStagedFiles = require('./getStagedFiles') @@ -12,17 +13,17 @@ const GitWorkflow = require('./gitWorkflow') const makeCmdTasks = require('./makeCmdTasks') const { DEPRECATED_GIT_ADD, - GIT_ERROR, + FAILED_GET_STAGED_FILES, + NOT_GIT_REPO, NO_STAGED_FILES, - PREVENTED_EMPTY_COMMIT, - RESTORE_STASH_EXAMPLE, + NO_TASKS, SKIPPED_GIT_ERROR, skippingBackup } = require('./messages') const resolveGitRepo = require('./resolveGitRepo') -const { ApplyEmptyCommitError, GetBackupStashError, GitError } = require('./symbols') const { applyModificationsSkipped, + cleanupEnabled, cleanupSkipped, getInitialState, hasPartiallyStagedFiles, @@ -30,8 +31,9 @@ const { restoreOriginalStateSkipped, restoreUnstagedChangesSkipped } = require('./state') +const { GitRepoError, GetStagedFilesError, GitError } = require('./symbols') -const debugLog = require('debug')('lint-staged:run') +const createError = (ctx) => Object.assign(new Error('lint-staged failed'), { ctx }) const getRenderer = ({ debug, quiet }) => { if (quiet) return 'silent' @@ -51,6 +53,7 @@ const getRenderer = ({ debug, quiet }) => { * @param {Object} [options.cwd] - Current working directory * @param {boolean} [options.debug] - Enable debug mode * @param {number} [options.maxArgLength] - Maximum argument string length + * @param {boolean} [options.verbose] - Always show task output * @param {boolean} [options.quiet] - Disable lint-staged’s own console output * @param {boolean} [options.relative] - Pass relative filepaths to tasks * @param {boolean} [options.shell] - Skip parsing of tasks for better shell support @@ -69,14 +72,21 @@ const runAll = async ( quiet = false, relative = false, shell = false, - stash = true + stash = true, + verbose = false }, logger = console ) => { debugLog('Running all linter scripts') + const ctx = getInitialState() + const { gitDir, gitConfigDir } = await resolveGitRepo(cwd) - if (!gitDir) throw new Error('Current directory is not a git directory!') + if (!gitDir) { + ctx.output.push(NOT_GIT_REPO) + ctx.errors.add(GitRepoError) + throw createError(ctx) + } // Test whether we have any commits or not. // Stashing must be disabled with no initial commit. @@ -85,18 +95,23 @@ const runAll = async ( .catch(() => false) // Lint-staged should create a backup stash only when there's an initial commit - const shouldBackup = hasInitialCommit && stash - if (!shouldBackup) { + ctx.shouldBackup = hasInitialCommit && stash + if (!ctx.shouldBackup) { logger.warn(skippingBackup(hasInitialCommit)) } const files = await getStagedFiles({ cwd: gitDir }) - if (!files) throw new Error('Unable to get staged files!') + if (!files) { + ctx.output.push(FAILED_GET_STAGED_FILES) + ctx.errors.add(GetStagedFilesError) + throw createError(ctx, GetStagedFilesError) + } debugLog('Loaded list of staged files in git:\n%O', files) // If there are no files avoid executing any lint-staged logic if (files.length === 0) { - return logger.log(NO_STAGED_FILES) + ctx.output.push(NO_STAGED_FILES) + return ctx } const stagedFileChunks = chunkFiles({ baseDir: gitDir, files, maxArgLength, relative }) @@ -107,9 +122,6 @@ const runAll = async ( // Warn user when their command includes `git add` let hasDeprecatedGitAdd = false - const ctx = getInitialState() - ctx.shouldBackup = shouldBackup - const listrOptions = { ctx, dateFormat: false, @@ -131,7 +143,8 @@ const runAll = async ( commands: task.commands, files: task.fileList, gitDir, - shell + shell, + verbose }) // Add files from task to match set @@ -183,8 +196,8 @@ const runAll = async ( // If all of the configured tasks should be skipped // avoid executing any lint-staged logic if (listrTasks.every((task) => task.skip())) { - logger.log('No staged files match any of provided globs.') - return 'No tasks to run.' + ctx.output.push(NO_TASKS) + return ctx } const git = new GitWorkflow({ allowEmpty, gitConfigDir, gitDir, matchedFiles, maxArgLength }) @@ -221,7 +234,7 @@ const runAll = async ( { title: 'Cleaning up...', task: (ctx) => git.cleanup(ctx), - enabled: () => shouldBackup, + enabled: cleanupEnabled, skip: cleanupSkipped } ], @@ -231,18 +244,10 @@ const runAll = async ( await runner.run() if (ctx.errors.size > 0) { - if (ctx.errors.has(ApplyEmptyCommitError)) { - logger.warn(PREVENTED_EMPTY_COMMIT) - } else if (ctx.errors.has(GitError) && !ctx.errors.has(GetBackupStashError)) { - logger.error(GIT_ERROR) - if (shouldBackup) { - // No sense to show this if the backup stash itself is missing. - logger.error(RESTORE_STASH_EXAMPLE) - } - } - const error = new Error('lint-staged failed') - throw Object.assign(error, { ctx }) + throw createError(ctx) } + + return ctx } module.exports = runAll diff --git a/lib/state.js b/lib/state.js index 6fc36c856..808202846 100644 --- a/lib/state.js +++ b/lib/state.js @@ -59,6 +59,8 @@ const restoreOriginalStateSkipped = (ctx) => { } } +const cleanupEnabled = (ctx) => ctx.shouldBackup + const cleanupSkipped = (ctx) => { // Should be skipped in case of unknown git errors if ( @@ -81,5 +83,6 @@ module.exports = { restoreUnstagedChangesSkipped, restoreOriginalStateEnabled, restoreOriginalStateSkipped, + cleanupEnabled, cleanupSkipped } diff --git a/lib/symbols.js b/lib/symbols.js index 02fcac417..d7a0d49ed 100644 --- a/lib/symbols.js +++ b/lib/symbols.js @@ -1,5 +1,9 @@ 'use strict' +const GitRepoError = Symbol('GitRepoError') + +const GetStagedFilesError = Symbol('GetStagedFilesError') + const TaskError = Symbol('TaskError') const GitError = Symbol('GitError') @@ -15,6 +19,8 @@ const RestoreUnstagedChangesError = Symbol('RestoreUnstagedChangesError') const RestoreOriginalStateError = Symbol('RestoreOriginalStateError') module.exports = { + GitRepoError, + GetStagedFilesError, ApplyEmptyCommitError, GetBackupStashError, GitError, diff --git a/test/__snapshots__/index.spec.js.snap b/test/__snapshots__/index.spec.js.snap index 34cc1f06a..f1934f91b 100644 --- a/test/__snapshots__/index.spec.js.snap +++ b/test/__snapshots__/index.spec.js.snap @@ -11,7 +11,8 @@ exports[`lintStaged should load an npm config package when specified 1`] = ` LOG Running lint-staged with the following config: LOG { '*': 'mytask' -}" +} +ERROR × Failed to get staged files!" `; exports[`lintStaged should load config file when specified 1`] = ` @@ -19,17 +20,22 @@ exports[`lintStaged should load config file when specified 1`] = ` LOG Running lint-staged with the following config: LOG { '*': 'mytask' -}" +} +ERROR × Failed to get staged files!" `; -exports[`lintStaged should not output config in normal mode 1`] = `""`; +exports[`lintStaged should not output config in normal mode 1`] = ` +" +ERROR × Failed to get staged files!" +`; exports[`lintStaged should output config in debug mode 1`] = ` " LOG Running lint-staged with the following config: LOG { '*': 'mytask' -}" +} +ERROR × Failed to get staged files!" `; exports[`lintStaged should parse function linter from js config 1`] = ` @@ -38,7 +44,8 @@ LOG Running lint-staged with the following config: LOG { '*.css': filenames => \`echo \${filenames.join(' ')}\`, '*.js': filenames => filenames.map(filename => \`echo \${filename}\`) -}" +} +ERROR × Failed to get staged files!" `; exports[`lintStaged should print helpful error message when config file is not found 2`] = ` @@ -74,10 +81,14 @@ exports[`lintStaged should use config object 1`] = ` LOG Running lint-staged with the following config: LOG { '*': 'node -e \\"process.exit(1)\\"' -}" +} +ERROR × Failed to get staged files!" `; -exports[`lintStaged should use cosmiconfig if no params are passed 1`] = `""`; +exports[`lintStaged should use cosmiconfig if no params are passed 1`] = ` +" +ERROR × Failed to get staged files!" +`; exports[`lintStaged should use use the console if no logger is passed 1`] = ` " diff --git a/test/printTaskOutput.spec.js b/test/printTaskOutput.spec.js new file mode 100644 index 000000000..ce429702c --- /dev/null +++ b/test/printTaskOutput.spec.js @@ -0,0 +1,15 @@ +import printTaskOutput from '../lib/printTaskOutput' + +const logger = { + error: jest.fn(() => {}), + log: jest.fn(() => {}) +} + +describe('printTaskOutput', () => { + it('should no-op when context is incomplete', () => { + printTaskOutput(undefined, logger) + printTaskOutput({}, logger) + expect(logger.error).toHaveBeenCalledTimes(0) + expect(logger.log).toHaveBeenCalledTimes(0) + }) +}) diff --git a/test/runAll.spec.js b/test/runAll.spec.js index 4a67dbaf8..5c9996592 100644 --- a/test/runAll.spec.js +++ b/test/runAll.spec.js @@ -38,26 +38,29 @@ describe('runAll', () => { it('should resolve the promise with no tasks', async () => { expect.assertions(1) - await expect(runAll({ config: {} })).resolves.toEqual(undefined) + await expect(runAll({ config: {} })).resolves.toMatchInlineSnapshot(` + Object { + "errors": Set {}, + "hasPartiallyStagedFiles": null, + "output": Array [ + "i No staged files found.", + ], + "shouldBackup": true, + } + `) }) it('should resolve the promise with no files', async () => { expect.assertions(1) await runAll({ config: { '*.js': ['echo "sample"'] } }) - expect(console.printHistory()).toMatchInlineSnapshot(` - " - LOG i No staged files found." - `) + expect(console.printHistory()).toMatchInlineSnapshot(`""`) }) it('should use an injected logger', async () => { expect.assertions(1) const logger = makeConsoleMock() await runAll({ config: { '*.js': ['echo "sample"'] }, debug: true }, logger) - expect(logger.printHistory()).toMatchInlineSnapshot(` - " - LOG i No staged files found." - `) + expect(logger.printHistory()).toMatchInlineSnapshot(`""`) }) it('should not skip tasks if there are files', async () => { @@ -102,15 +105,7 @@ describe('runAll', () => { ERROR ✖ test INFO ❯ Running tasks... INFO ❯ Applying modifications... - INFO ❯ Cleaning up... - ERROR - × lint-staged failed due to a git error. - ERROR Any lost modifications can be restored from a git stash: - - > git stash list - stash@{0}: automatic lint-staged backup - > git stash apply --index stash@{0} - " + INFO ❯ Cleaning up..." `) }) diff --git a/test/runAll.unmocked.2.spec.js b/test/runAll.unmocked.2.spec.js index b4287568b..62d7eb9fc 100644 --- a/test/runAll.unmocked.2.spec.js +++ b/test/runAll.unmocked.2.spec.js @@ -117,15 +117,7 @@ describe('runAll', () => { INFO ❯ Applying modifications... INFO ❯ Reverting to original state because of errors... ERROR ✖ Merge state could not be restored due to an error! - INFO ❯ Cleaning up... - ERROR - × lint-staged failed due to a git error. - ERROR Any lost modifications can be restored from a git stash: - - > git stash list - stash@{0}: automatic lint-staged backup - > git stash apply --index stash@{0} - " + INFO ❯ Cleaning up..." `) }) }) diff --git a/test/runAll.unmocked.spec.js b/test/runAll.unmocked.spec.js index 2d24fea58..d5f3b1f45 100644 --- a/test/runAll.unmocked.spec.js +++ b/test/runAll.unmocked.spec.js @@ -78,7 +78,7 @@ describe('runAll', () => { it('should throw when not in a git directory', async () => { const nonGitDir = await createTempDir() await expect(runAll({ cwd: nonGitDir })).rejects.toThrowErrorMatchingInlineSnapshot( - `"Current directory is not a git directory!"` + `"lint-staged failed"` ) await removeTempDir(nonGitDir) }) @@ -414,17 +414,7 @@ describe('runAll', () => { } }) ).rejects.toThrowError() - expect(console.printHistory()).toMatchInlineSnapshot(` - " - ERROR - × lint-staged failed due to a git error. - ERROR Any lost modifications can be restored from a git stash: - - > git stash list - stash@{0}: automatic lint-staged backup - > git stash apply --index stash@{0} - " - `) + expect(console.printHistory()).toMatchInlineSnapshot(`""`) // Something was wrong so new commit wasn't created expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1') @@ -797,10 +787,6 @@ describe('runAll', () => { expect(console.printHistory()).toMatchInlineSnapshot(` " WARN ‼ Some of your tasks use \`git add\` command. Please remove it from the config since all modifications made by tasks will be automatically added to the git commit index. - - WARN - ‼ lint-staged prevented an empty git commit. - Use the --allow-empty option to continue, or check your task configuration " `) @@ -994,9 +980,7 @@ describe('runAll', () => { INFO ❯ Applying modifications... LOG ✔ Applying modifications... INFO ❯ Restoring unstaged changes to partially staged files... - ERROR ✖ Unstaged changes could not be restored due to a merge conflict! - ERROR - × lint-staged failed due to a git error." + ERROR ✖ Unstaged changes could not be restored due to a merge conflict!" `) // Something was wrong so the commit was aborted