Skip to content

Commit 938d3f4

Browse files
committed
feat: add logger parameter to function tasks
1 parent 129147b commit 938d3f4

8 files changed

Lines changed: 170 additions & 16 deletions

File tree

‎.changeset/little-apes-appear.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'lint-staged': minor
3+
---
4+
5+
Task functions like `{ title, task }` can now use a logger function `log()` to emit output while the task runs. By default, the output will only be visible if the tasks fails, unless the `--verbose` option was used. Additionally, when the task rejects, the error will be shown in the output.
6+
7+
```js
8+
import { defineConfig } from './lib/config.js'
9+
10+
export default defineConfig({
11+
'*': {
12+
title: 'Fail if PDF files are committed',
13+
task: async (filepaths, { log }) => {
14+
const pdfFiles = filepaths.filter((f) => f.toLowerCase().endsWith('.pdf'))
15+
if (pdfFiles.length > 0) {
16+
log('PDF files should not be committed: %s', pdfFiles)
17+
throw new Error('Failed')
18+
}
19+
},
20+
},
21+
})
22+
```

‎README.md‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -425,16 +425,24 @@ This will result in _lint-staged_ first running `eslint .` (matching _all_ files
425425
You can also configure _lint-staged_ to run a JavaScript/Node.js script directly, passing the list of staged files as an argument:
426426

427427
```js
428-
export default {
429-
'*.js': {
430-
title: 'Log staged JS files to console',
431-
task: async (files) => {
432-
console.log('Staged JS files:', files)
428+
import { defineConfig } from './lib/config.js'
429+
430+
export default defineConfig({
431+
'*': {
432+
title: 'Fail if PDF files are committed',
433+
task: async (filepaths, { log }) => {
434+
const pdfFiles = filepaths.filter((f) => f.toLowerCase().endsWith('.pdf'))
435+
if (pdfFiles.length > 0) {
436+
log('PDF files should not be committed: %s', pdfFiles)
437+
throw new Error('Failed')
438+
}
433439
},
434440
},
435-
}
441+
})
436442
```
437443

444+
Use the `log()` function to emit output from the task. By default it will only be shown in the console when the task fails, unless the `--verbose` option is used. The `log()` uses [Node.js `util.format()`](https://nodejs.org/api/util.html#utilformatformat-args) and each call will be on its own line.
445+
438446
### Example: Export a function to build your own matchers
439447

440448
<details>

‎lib/config.d.ts‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,22 @@ type ParallelTasks = (SpawnedTask | GenerateTask)[]
3535
*/
3636
type SequentialTasks = (SpawnedTask | GenerateTask | ParallelTasks)[]
3737

38+
type TaskFunctionContext = {
39+
/**
40+
* Emit output from the task. All arguments of the call will be passed to Node.js `util.format()`.
41+
* The output will only be shown on error, unless `--verbose` is used.
42+
*
43+
* @example log('Hello from task')
44+
*
45+
* @see https://nodejs.org/api/util.html#utilformatformat-args
46+
*
47+
* @param {any} format
48+
* @param {any[]} param
49+
* @returns {void}
50+
*/
51+
log: (format, ...param) => void
52+
}
53+
3854
/**
3955
* A single Node.js/JavaScript task that defines its title and the function which will be
4056
* run with the list of the matched staged files as its argument.
@@ -49,7 +65,7 @@ type SequentialTasks = (SpawnedTask | GenerateTask | ParallelTasks)[]
4965
*/
5066
type TaskFunction = {
5167
title: string
52-
task: (filepaths: readonly string[]) => void | Promise<void>
68+
task: (filepaths: readonly string[], context: TaskFunctionContext) => void | Promise<void>
5369
}
5470

5571
/** An entire `lint-staged` configuration, or a function that returns one */

‎lib/getFunctionTask.js‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { format } from 'node:util'
2+
13
import { createDebug } from './debug.js'
24
import { Signal } from './getAbortController.js'
3-
import { createTaskError } from './getSpawnedTask.js'
5+
import { createTaskError, handleTaskOutput } from './getSpawnedTask.js'
46

57
const debugLog = createDebug('lint-staged:getFunctionTasks')
68

@@ -19,21 +21,44 @@ export const isFunctionTask = (commands) => typeof commands === 'object' && !Arr
1921
* @param {FunctionTask} options.command
2022
* @param {boolean} options.continueOnError
2123
* @param {import('./getStagedFiles.js').StagedFile[]} options.files
24+
* @param {boolean} [options.verbose]
2225
* @throws {Error} If the function configuration is not valid
2326
*/
24-
export const getFunctionTask = async ({ abortController, command, continueOnError, files }) => {
27+
export const getFunctionTask = async ({
28+
abortController,
29+
command,
30+
continueOnError,
31+
files,
32+
verbose,
33+
}) => {
2534
debugLog('Creating task for function %o', command)
2635

2736
const task = async (ctx) => {
37+
const output = []
38+
const addOutput = (...args) => {
39+
output.push(format(...args))
40+
}
41+
2842
try {
29-
await command.task(files.map((file) => file.filepath))
30-
} catch (e) {
43+
const filepaths = files.map((file) => file.filepath)
44+
45+
await command.task(filepaths, { log: addOutput })
46+
} catch (error) {
3147
if (continueOnError !== true) {
3248
/** Other tasks should be killed */
3349
abortController.abort(Signal.SIGKILL)
3450
}
3551

36-
throw createTaskError(command.title, e, ctx)
52+
addOutput(`\n%O`, error)
53+
54+
const taskOutput = output.join('\n').trimEnd()
55+
handleTaskOutput(command.title, taskOutput, ctx, undefined, error)
56+
57+
throw createTaskError(command.title, error, ctx)
58+
}
59+
60+
if (verbose) {
61+
handleTaskOutput(command.title, output.join('\n').trimEnd(), ctx)
3762
}
3863
}
3964

‎lib/getSpawnedTask.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const debugLog = createDebug('lint-staged:getSpawnedTask')
2020
* @param {keyof typeof Signal | undefined} signal
2121
* @param {import('tinyexec').Result} [errorResult]
2222
*/
23-
const handleTaskOutput = (command, output, ctx, signal, errorResult) => {
23+
export const handleTaskOutput = (command, output, ctx, signal, errorResult) => {
2424
if (output) {
2525
const outputTitle = errorResult
2626
? red(`${figures.error()} ${command}:`)

‎lib/runAll.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ export const runAll = async (
226226
command: task.commands,
227227
continueOnError,
228228
files: task.fileList,
229+
verbose,
229230
})
230231
: getSpawnedTasks({
231232
abortController,

‎test/types/config.test.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,16 @@ test('lint-staged TypeScript types', () => {
3838
},
3939
},
4040

41-
'*.ext9': [['oxfmt', 'oxlint']],
41+
'*.ext9': {
42+
title: 'Async Function Task with output logger function',
43+
task: async (files: readonly string[], { log }: { log: (...args: any[]) => void }) => {
44+
log(files)
45+
},
46+
},
47+
48+
'*.ext10': [['oxfmt', 'oxlint']],
4249

43-
'*.ext10': ['oxfmt', ['oxlint', () => 'tsc']],
50+
'*.ext11': ['oxfmt', ['oxlint', () => 'tsc']],
4451
}).toExtend<Configuration>()
4552

4653
expectTypeOf((files: readonly string[]) => {

‎test/unit/getFunctionTask.spec.js‎

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, it, vi } from 'vitest'
22

3+
import * as figures from '../../lib/figures.js'
34
import { Signal } from '../../lib/getAbortController.js'
45
import { getFunctionTask } from '../../lib/getFunctionTask.js'
56
import { getInitialState } from '../../lib/state.js'
@@ -31,7 +32,9 @@ describe('getFunctionTask', () => {
3132
wrapped[0].task()
3233

3334
expect(command.task).toHaveBeenCalledTimes(1)
34-
expect(command.task).toHaveBeenCalledExactlyOnceWith(['file.js'])
35+
expect(command.task).toHaveBeenCalledExactlyOnceWith(['file.js'], {
36+
log: expect.any(Function),
37+
})
3538
})
3639

3740
it('should wrap function task failure', async ({ expect }) => {
@@ -97,4 +100,76 @@ describe('getFunctionTask', () => {
97100

98101
expect(abortController.signal.aborted).toBe(false)
99102
})
103+
104+
it('should collect output from output function on error', async ({ expect }) => {
105+
const testError = new Error('test error')
106+
107+
const command = {
108+
title: 'My task',
109+
task: vi.fn().mockImplementation(async (_, { log }) => {
110+
log('test output')
111+
throw testError
112+
}),
113+
}
114+
115+
const abortController = new AbortController()
116+
117+
const wrapped = await getFunctionTask({
118+
abortController,
119+
command,
120+
files: [{ filepath: 'file.js', status: 'M' }],
121+
})
122+
123+
const context = getInitialState()
124+
125+
await expect(wrapped[0].task(context)).rejects.toThrow('My task [FAILED]')
126+
127+
expect(context.output).toEqual([
128+
expect.stringMatching(`\n${figures.error()} My task:\ntest output\n\n${testError}`),
129+
])
130+
})
131+
132+
it('should not collect output from output function when task succeeds', async ({ expect }) => {
133+
const command = {
134+
title: 'My task',
135+
task: vi.fn().mockImplementation(async (_, { log }) => {
136+
log('test output')
137+
}),
138+
}
139+
140+
const wrapped = await getFunctionTask({
141+
command,
142+
files: [{ filepath: 'file.js', status: 'M' }],
143+
})
144+
145+
const context = getInitialState()
146+
147+
await wrapped[0].task(context)
148+
149+
expect(context.output).toStrictEqual([])
150+
})
151+
152+
it('should collect output from output function when using --verbose', async ({ expect }) => {
153+
const command = {
154+
title: 'My task',
155+
task: vi.fn().mockImplementation(async (_, { log }) => {
156+
log('test output')
157+
}),
158+
}
159+
160+
const abortController = new AbortController()
161+
162+
const wrapped = await getFunctionTask({
163+
abortController,
164+
command,
165+
files: [{ filepath: 'file.js', status: 'M' }],
166+
verbose: true,
167+
})
168+
169+
const context = getInitialState()
170+
171+
await wrapped[0].task(context)
172+
173+
expect(context.output).toStrictEqual([`\n${figures.info()} My task:\ntest output`])
174+
})
100175
})

0 commit comments

Comments
 (0)