diff --git a/src/makeCmdTasks.js b/src/makeCmdTasks.js index f73cf5eac..5598baf34 100644 --- a/src/makeCmdTasks.js +++ b/src/makeCmdTasks.js @@ -4,10 +4,23 @@ const resolveTaskFn = require('./resolveTaskFn') const debug = require('debug')('lint-staged:make-cmd-tasks') +/** + * Get title for linter task. For a function, evaluate by passing single [file]. + * For strings, return as-is + * @param {string|Function} linter + */ +const getTitle = linter => { + if (typeof linter === 'function') { + const resolved = linter(['[file]']) + return Array.isArray(resolved) ? resolved[0] : resolved + } + return linter +} + /** * Creates and returns an array of listr tasks which map to the given commands. * - * @param {Array|string} commands + * @param {Array|string|Function} commands * @param {Boolean} shell * @param {Array} pathsToLint * @param {Object} [options] @@ -18,7 +31,7 @@ module.exports = async function makeCmdTasks(commands, shell, gitDir, pathsToLin const lintersArray = Array.isArray(commands) ? commands : [commands] return lintersArray.map(linter => ({ - title: linter, + title: getTitle(linter), task: resolveTaskFn({ linter, shell, diff --git a/test/makeCmdTasks.spec.js b/test/makeCmdTasks.spec.js index 8dbdd756e..ee6cfc2b5 100644 --- a/test/makeCmdTasks.spec.js +++ b/test/makeCmdTasks.spec.js @@ -52,4 +52,34 @@ describe('makeCmdTasks', () => { shell: false }) }) + + it('should work with function linter returning a string', async () => { + const res = await makeCmdTasks(() => 'test', false, gitDir, ['test.js']) + expect(res.length).toBe(1) + expect(res[0].title).toEqual('test') + }) + + it('should work with function linter returning array of string', async () => { + const res = await makeCmdTasks(() => ['test', 'test2'], false, gitDir, ['test.js']) + expect(res.length).toBe(1) + expect(res[0].title).toEqual('test') + }) + + it('should work with function linter accepting arguments', async () => { + const res = await makeCmdTasks( + filenames => filenames.map(file => `test ${file}`), + false, + gitDir, + ['test.js'] + ) + expect(res.length).toBe(1) + expect(res[0].title).toEqual('test [file]') + }) + + it('should work with array of mixed string and function linters', async () => { + const res = await makeCmdTasks([() => 'test', 'test2'], false, gitDir, ['test.js']) + expect(res.length).toBe(2) + expect(res[0].title).toEqual('test') + expect(res[1].title).toEqual('test2') + }) })