Skip to content

Commit 242deb5

Browse files
iirojokonet
authored andcommittedJul 10, 2019
feat: add --relative option for controlling file paths
All commands specified in the configuration will run in the current directory when using relative paths, instead of git commands running in the repo root
1 parent 6572a82 commit 242deb5

14 files changed

+199
-124
lines changed
 

‎bin/lint-staged

+4-2
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,9 @@ const debug = debugLib('lint-staged:bin')
2727
cmdline
2828
.version(pkg.version)
2929
.option('-c, --config [path]', 'Path to configuration file')
30-
.option('-x, --shell', 'Use execa’s shell mode to execute linter commands')
31-
.option('-q, --quiet', 'Use Listr’s silent renderer')
30+
.option('-r, --relative', 'Pass relative filepaths to tasks')
31+
.option('-x, --shell', 'Skip parsing of tasks for better shell support')
32+
.option('-q, --quiet', 'Disable lint-staged’s own console output')
3233
.option('-d, --debug', 'Enable debug mode')
3334
.parse(process.argv)
3435

@@ -40,6 +41,7 @@ debug('Running `lint-staged@%s`', pkg.version)
4041

4142
lintStaged({
4243
configPath: cmdline.config,
44+
relative: !!cmdline.relative,
4345
shell: !!cmdline.shell,
4446
quiet: !!cmdline.quiet,
4547
debug: !!cmdline.debug

‎src/generateTasks.js

+18-7
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,25 @@ const isPathInside = (parent, child) => {
1818
return relative && !relative.startsWith('..') && !path.isAbsolute(relative)
1919
}
2020

21-
module.exports = async function generateTasks(linters, gitDir, stagedRelFiles) {
21+
/**
22+
* Generates all task commands, and filelist
23+
*
24+
* @param {object} options
25+
* @param {Object} [options.config] - Task configuration
26+
* @param {boolean} [options.gitDir] - Git root directory
27+
* @param {boolean} [options.files] - Staged filepaths
28+
* @param {boolean} [options.relative] - Whether filepaths to should be relative to gitDir
29+
* @returns {Promise}
30+
*/
31+
module.exports = async function generateTasks({ config, gitDir, files, relative = false }) {
2232
debug('Generating linter tasks')
2333

2434
const cwd = process.cwd()
25-
const stagedFiles = stagedRelFiles.map(file => path.resolve(gitDir, file))
35+
const stagedFiles = files.map(file => path.resolve(gitDir, file))
2636

27-
return Object.keys(linters).map(pattern => {
37+
return Object.keys(config).map(pattern => {
2838
const isParentDirPattern = pattern.startsWith('../')
29-
const commands = linters[pattern]
39+
const commands = config[pattern]
3040

3141
const fileList = micromatch(
3242
stagedFiles
@@ -43,9 +53,10 @@ module.exports = async function generateTasks(linters, gitDir, stagedRelFiles) {
4353
matchBase: !pattern.includes('/'),
4454
dot: true
4555
}
46-
).map(file =>
47-
// Return absolute path after the filter is run
48-
path.resolve(cwd, file)
56+
).map(
57+
file =>
58+
// Return absolute path after the filter is run
59+
relative ? path.normalize(file) : path.resolve(cwd, file)
4960
)
5061

5162
const task = { pattern, commands, fileList }

‎src/index.js

+7-6
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,16 @@ function loadConfig(configPath) {
4343
*
4444
* @param {object} options
4545
* @param {string} [options.configPath] - Path to configuration file
46-
* @param {boolean} [options.shell] - Use execa’s shell mode to execute linter commands
47-
* @param {boolean} [options.quiet] - Use Listr’s silent renderer
46+
* @param {boolean} [options.relative] - Pass relative filepaths to tasks
47+
* @param {boolean} [options.shell] - Skip parsing of tasks for better shell support
48+
* @param {boolean} [options.quiet] - Disable lint-staged’s own console output
4849
* @param {boolean} [options.debug] - Enable debug mode
4950
* @param {Logger} [logger]
5051
*
5152
* @returns {Promise<boolean>} Promise of whether the linting passed or failed
5253
*/
5354
module.exports = function lintStaged(
54-
{ configPath, shell = false, quiet = false, debug = false } = {},
55+
{ configPath, relative = false, shell = false, quiet = false, debug = false } = {},
5556
logger = console
5657
) {
5758
debugLog('Loading config using `cosmiconfig`')
@@ -71,12 +72,12 @@ module.exports = function lintStaged(
7172
} else {
7273
// We might not be in debug mode but `DEBUG=lint-staged*` could have
7374
// been set.
74-
debugLog('Normalized config:\n%O', config)
75+
debugLog('lint-staged config:\n%O', config)
7576
}
7677

77-
return runAll(config, shell, quiet, debug, logger)
78+
return runAll({ config, relative, shell, quiet, debug }, logger)
7879
.then(() => {
79-
debugLog('linters were executed successfully!')
80+
debugLog('tasks were executed successfully!')
8081
return Promise.resolve(true)
8182
})
8283
.catch(error => {

‎src/makeCmdTasks.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@ const debug = require('debug')('lint-staged:make-cmd-tasks')
77
/**
88
* Creates and returns an array of listr tasks which map to the given commands.
99
*
10-
* @param {Array<string|Function>|string|Function} commands
10+
* @param {object} options
11+
* @param {Array<string|Function>|string|Function} [options.commands]
12+
* @param {string} [options.gitDir]
13+
* @param {Array<string>} [options.pathsToLint]
1114
* @param {Boolean} shell
12-
* @param {Array<string>} pathsToLint
1315
*/
14-
module.exports = async function makeCmdTasks(commands, shell, gitDir, pathsToLint) {
16+
module.exports = async function makeCmdTasks({ commands, gitDir, pathsToLint, shell }) {
1517
debug('Creating listr tasks for commands %o', commands)
1618
const commandsArray = Array.isArray(commands) ? commands : [commands]
1719

‎src/resolveGitDir.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
const execGit = require('./execGit')
44
const path = require('path')
55

6-
module.exports = async function resolveGitDir(options) {
6+
module.exports = async function resolveGitDir(options = {}) {
77
try {
88
// git cli uses GIT_DIR to fast track its response however it might be set to a different path
99
// depending on where the caller initiated this from, hence clear GIT_DIR

‎src/resolveTaskFn.js

+22-12
Original file line numberDiff line numberDiff line change
@@ -77,16 +77,32 @@ function makeErr(linter, result, context = {}) {
7777
* if the OS is Windows.
7878
*
7979
* @param {Object} options
80-
* @param {string} options.gitDir
81-
* @param {Boolean} options.isFn
82-
* @param {string} options.linter
83-
* @param {Array<string>} options.pathsToLint
84-
* @param {Boolean} [options.shell]
80+
* @param {String} [options.gitDir] - Current git repo path
81+
* @param {Boolean} [options.isFn] - Whether the linter task is a function
82+
* @param {string} [options.linter] — Linter task
83+
* @param {Array<string>} [options.pathsToLint] — Filepaths to run the linter task against
84+
* @param {Boolean} [options.relative] — Whether the filepaths should be relative
85+
* @param {Boolean} [options.shell] — Whether to skip parsing linter task for better shell support
8586
* @returns {function(): Promise<Array<string>>}
8687
*/
87-
module.exports = function resolveTaskFn({ gitDir, isFn, linter, pathsToLint, shell = false }) {
88+
module.exports = function resolveTaskFn({
89+
gitDir,
90+
isFn,
91+
linter,
92+
pathsToLint,
93+
relative,
94+
shell = false
95+
}) {
8896
const execaOptions = { preferLocal: true, reject: false, shell }
8997

98+
if (relative) {
99+
execaOptions.cwd = process.cwd()
100+
} else if (/^git(\.exe)?/i.test(linter) && gitDir !== process.cwd()) {
101+
// Only use gitDir as CWD if we are using the git binary
102+
// e.g `npm` should run tasks in the actual CWD
103+
execaOptions.cwd = gitDir
104+
}
105+
90106
let cmd
91107
let args
92108

@@ -101,12 +117,6 @@ module.exports = function resolveTaskFn({ gitDir, isFn, linter, pathsToLint, she
101117
args = isFn ? parsedArgs : parsedArgs.concat(pathsToLint)
102118
}
103119

104-
// Only use gitDir as CWD if we are using the git binary
105-
// e.g `npm` should run tasks in the actual CWD
106-
if (/^git(\.exe)?/i.test(linter) && gitDir !== process.cwd()) {
107-
execaOptions.cwd = gitDir
108-
}
109-
110120
return ctx =>
111121
execLinter(cmd, args, execaOptions).then(result => {
112122
if (result.failed || result.killed || result.signal != null) {

‎src/runAll.js

+24-22
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const git = require('./gitWorkflow')
1313
const makeCmdTasks = require('./makeCmdTasks')
1414
const resolveGitDir = require('./resolveGitDir')
1515

16-
const debug = require('debug')('lint-staged:run')
16+
const debugLog = require('debug')('lint-staged:run')
1717

1818
/**
1919
* https://serverfault.com/questions/69430/what-is-the-maximum-length-of-a-command-line-in-mac-os-x
@@ -26,37 +26,36 @@ const MAX_ARG_LENGTH =
2626
/**
2727
* Executes all tasks and either resolves or rejects the promise
2828
*
29-
* @param config {Object}
30-
* @param {Boolean} [shellMode] Use execa’s shell mode to execute linter commands
31-
* @param {Boolean} [quietMode] Use Listr’s silent renderer
32-
* @param {Boolean} [debugMode] Enable debug mode
29+
* @param {object} options
30+
* @param {Object} [options.config] - Task configuration
31+
* @param {boolean} [options.relative] - Pass relative filepaths to tasks
32+
* @param {boolean} [options.shell] - Skip parsing of tasks for better shell support
33+
* @param {boolean} [options.quiet] - Disable lint-staged’s own console output
34+
* @param {boolean} [options.debug] - Enable debug mode
3335
* @param {Logger} logger
3436
* @returns {Promise}
3537
*/
3638
module.exports = async function runAll(
37-
config,
38-
shellMode = false,
39-
quietMode = false,
40-
debugMode = false,
39+
{ config, relative = false, shell = false, quiet = false, debug = false },
4140
logger = console
4241
) {
43-
debug('Running all linter scripts')
42+
debugLog('Running all linter scripts')
4443

45-
const gitDir = await resolveGitDir(config)
44+
const gitDir = await resolveGitDir()
4645

4746
if (!gitDir) {
4847
throw new Error('Current directory is not a git directory!')
4948
}
5049

51-
debug('Resolved git directory to be `%s`', gitDir)
50+
debugLog('Resolved git directory to be `%s`', gitDir)
5251

5352
const files = await getStagedFiles({ cwd: gitDir })
5453

5554
if (!files) {
5655
throw new Error('Unable to get staged files!')
5756
}
5857

59-
debug('Loaded list of staged files in git:\n%O', files)
58+
debugLog('Loaded list of staged files in git:\n%O', files)
6059

6160
const argLength = files.join(' ').length
6261
if (argLength > MAX_ARG_LENGTH) {
@@ -70,16 +69,19 @@ https://github.com/okonet/lint-staged#using-js-functions-to-customize-linter-com
7069
)
7170
}
7271

73-
const tasks = (await generateTasks(config, gitDir, files)).map(task => ({
72+
const tasks = (await generateTasks({ config, gitDir, files, relative })).map(task => ({
7473
title: `Running tasks for ${task.pattern}`,
7574
task: async () =>
76-
new Listr(await makeCmdTasks(task.commands, shellMode, gitDir, task.fileList), {
77-
// In sub-tasks we don't want to run concurrently
78-
// and we want to abort on errors
79-
dateFormat: false,
80-
concurrent: false,
81-
exitOnError: true
82-
}),
75+
new Listr(
76+
await makeCmdTasks({ commands: task.commands, gitDir, shell, pathsToLint: task.fileList }),
77+
{
78+
// In sub-tasks we don't want to run concurrently
79+
// and we want to abort on errors
80+
dateFormat: false,
81+
concurrent: false,
82+
exitOnError: true
83+
}
84+
),
8385
skip: () => {
8486
if (task.fileList.length === 0) {
8587
return `No staged files match ${task.pattern}`
@@ -90,7 +92,7 @@ https://github.com/okonet/lint-staged#using-js-functions-to-customize-linter-com
9092

9193
const listrOptions = {
9294
dateFormat: false,
93-
renderer: (quietMode && 'silent') || (debugMode && 'verbose') || 'update'
95+
renderer: (quiet && 'silent') || (debug && 'verbose') || 'update'
9496
}
9597

9698
// If all of the configured "linters" should be skipped

‎test/generateTasks.spec.js

+57-36
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ const files = [
2525

2626
// Mocks get hoisted
2727
jest.mock('../src/resolveGitDir.js')
28-
const workDir = path.join(os.tmpdir(), 'tmp-lint-staged')
29-
resolveGitDir.mockResolvedValue(workDir)
28+
const gitDir = path.join(os.tmpdir(), 'tmp-lint-staged')
29+
resolveGitDir.mockResolvedValue(gitDir)
3030

3131
const config = {
3232
'*.js': 'root-js',
@@ -39,29 +39,29 @@ const config = {
3939

4040
describe('generateTasks', () => {
4141
beforeAll(() => {
42-
jest.spyOn(process, 'cwd').mockReturnValue(workDir)
42+
jest.spyOn(process, 'cwd').mockReturnValue(gitDir)
4343
})
4444

4545
afterAll(() => {
4646
process.cwd.mockRestore()
4747
})
4848

4949
it('should return absolute paths', async () => {
50-
const [task] = await generateTasks(
51-
{
50+
const [task] = await generateTasks({
51+
config: {
5252
'*': 'lint'
5353
},
54-
workDir,
54+
gitDir,
5555
files
56-
)
56+
})
5757
task.fileList.forEach(file => {
5858
expect(path.isAbsolute(file)).toBe(true)
5959
})
6060
})
6161

6262
it('should not match non-children files', async () => {
6363
const relPath = path.join(process.cwd(), '..')
64-
const result = await generateTasks({ ...config }, relPath, files)
64+
const result = await generateTasks({ config, gitDir: relPath, files })
6565
const linter = result.find(item => item.pattern === '*.js')
6666
expect(linter).toEqual({
6767
pattern: '*.js',
@@ -71,7 +71,7 @@ describe('generateTasks', () => {
7171
})
7272

7373
it('should return an empty file list for linters with no matches.', async () => {
74-
const result = await generateTasks(config, workDir, files)
74+
const result = await generateTasks({ config, gitDir, files })
7575

7676
result.forEach(task => {
7777
if (task.commands === 'unknown-js') {
@@ -83,74 +83,95 @@ describe('generateTasks', () => {
8383
})
8484

8585
it('should match pattern "*.js"', async () => {
86-
const result = await generateTasks(config, workDir, files)
86+
const result = await generateTasks({ config, gitDir, files })
8787
const linter = result.find(item => item.pattern === '*.js')
8888
expect(linter).toEqual({
8989
pattern: '*.js',
9090
commands: 'root-js',
9191
fileList: [
92-
`${workDir}/test.js`,
93-
`${workDir}/deeper/test.js`,
94-
`${workDir}/deeper/test2.js`,
95-
`${workDir}/even/deeper/test.js`,
96-
`${workDir}/.hidden/test.js`
92+
`${gitDir}/test.js`,
93+
`${gitDir}/deeper/test.js`,
94+
`${gitDir}/deeper/test2.js`,
95+
`${gitDir}/even/deeper/test.js`,
96+
`${gitDir}/.hidden/test.js`
9797
].map(path.normalize)
9898
})
9999
})
100100

101101
it('should match pattern "**/*.js"', async () => {
102-
const result = await generateTasks(config, workDir, files)
102+
const result = await generateTasks({ config, gitDir, files })
103103
const linter = result.find(item => item.pattern === '**/*.js')
104104
expect(linter).toEqual({
105105
pattern: '**/*.js',
106106
commands: 'any-js',
107107
fileList: [
108-
`${workDir}/test.js`,
109-
`${workDir}/deeper/test.js`,
110-
`${workDir}/deeper/test2.js`,
111-
`${workDir}/even/deeper/test.js`,
112-
`${workDir}/.hidden/test.js`
108+
`${gitDir}/test.js`,
109+
`${gitDir}/deeper/test.js`,
110+
`${gitDir}/deeper/test2.js`,
111+
`${gitDir}/even/deeper/test.js`,
112+
`${gitDir}/.hidden/test.js`
113113
].map(path.normalize)
114114
})
115115
})
116116

117117
it('should match pattern "deeper/*.js"', async () => {
118-
const result = await generateTasks(config, workDir, files)
118+
const result = await generateTasks({ config, gitDir, files })
119119
const linter = result.find(item => item.pattern === 'deeper/*.js')
120120
expect(linter).toEqual({
121121
pattern: 'deeper/*.js',
122122
commands: 'deeper-js',
123-
fileList: [`${workDir}/deeper/test.js`, `${workDir}/deeper/test2.js`].map(path.normalize)
123+
fileList: [`${gitDir}/deeper/test.js`, `${gitDir}/deeper/test2.js`].map(path.normalize)
124124
})
125125
})
126126

127127
it('should match pattern ".hidden/*.js"', async () => {
128-
const result = await generateTasks(config, workDir, files)
128+
const result = await generateTasks({ config, gitDir, files })
129129
const linter = result.find(item => item.pattern === '.hidden/*.js')
130130
expect(linter).toEqual({
131131
pattern: '.hidden/*.js',
132132
commands: 'hidden-js',
133-
fileList: [path.normalize(`${workDir}/.hidden/test.js`)]
133+
fileList: [path.normalize(`${gitDir}/.hidden/test.js`)]
134134
})
135135
})
136136

137137
it('should match pattern "*.{css,js}"', async () => {
138-
const result = await generateTasks(config, workDir, files)
138+
const result = await generateTasks({ config, gitDir, files })
139+
const linter = result.find(item => item.pattern === '*.{css,js}')
140+
expect(linter).toEqual({
141+
pattern: '*.{css,js}',
142+
commands: 'root-css-or-js',
143+
fileList: [
144+
`${gitDir}/test.js`,
145+
`${gitDir}/deeper/test.js`,
146+
`${gitDir}/deeper/test2.js`,
147+
`${gitDir}/even/deeper/test.js`,
148+
`${gitDir}/.hidden/test.js`,
149+
`${gitDir}/test.css`,
150+
`${gitDir}/deeper/test.css`,
151+
`${gitDir}/deeper/test2.css`,
152+
`${gitDir}/even/deeper/test.css`,
153+
`${gitDir}/.hidden/test.css`
154+
].map(path.normalize)
155+
})
156+
})
157+
158+
it('should be able to return relative paths for "*.{css,js}"', async () => {
159+
const result = await generateTasks({ config, gitDir, files, relative: true })
139160
const linter = result.find(item => item.pattern === '*.{css,js}')
140161
expect(linter).toEqual({
141162
pattern: '*.{css,js}',
142163
commands: 'root-css-or-js',
143164
fileList: [
144-
`${workDir}/test.js`,
145-
`${workDir}/deeper/test.js`,
146-
`${workDir}/deeper/test2.js`,
147-
`${workDir}/even/deeper/test.js`,
148-
`${workDir}/.hidden/test.js`,
149-
`${workDir}/test.css`,
150-
`${workDir}/deeper/test.css`,
151-
`${workDir}/deeper/test2.css`,
152-
`${workDir}/even/deeper/test.css`,
153-
`${workDir}/.hidden/test.css`
165+
'test.js',
166+
'deeper/test.js',
167+
'deeper/test2.js',
168+
'even/deeper/test.js',
169+
'.hidden/test.js',
170+
'test.css',
171+
'deeper/test.css',
172+
'deeper/test2.css',
173+
'even/deeper/test.css',
174+
'.hidden/test.css'
154175
].map(path.normalize)
155176
})
156177
})

‎test/makeCmdTasks.spec.js

+21-15
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ describe('makeCmdTasks', () => {
99
})
1010

1111
it('should return an array', async () => {
12-
const array = await makeCmdTasks('test', false, gitDir, ['test.js'])
12+
const array = await makeCmdTasks({ commands: 'test', gitDir, pathsToLint: ['test.js'] })
1313
expect(array).toBeInstanceOf(Array)
1414
})
1515

1616
it('should work with a single command', async () => {
1717
expect.assertions(4)
18-
const res = await makeCmdTasks('test', false, gitDir, ['test.js'])
18+
const res = await makeCmdTasks({ commands: 'test', gitDir, pathsToLint: ['test.js'] })
1919
expect(res.length).toBe(1)
2020
const [linter] = res
2121
expect(linter.title).toBe('test')
@@ -27,7 +27,11 @@ describe('makeCmdTasks', () => {
2727

2828
it('should work with multiple commands', async () => {
2929
expect.assertions(9)
30-
const res = await makeCmdTasks(['test', 'test2'], false, gitDir, ['test.js'])
30+
const res = await makeCmdTasks({
31+
commands: ['test', 'test2'],
32+
gitDir,
33+
pathsToLint: ['test.js']
34+
})
3135
expect(res.length).toBe(2)
3236
const [linter1, linter2] = res
3337
expect(linter1.title).toBe('test')
@@ -54,37 +58,39 @@ describe('makeCmdTasks', () => {
5458
})
5559

5660
it('should work with function linter returning a string', async () => {
57-
const res = await makeCmdTasks(() => 'test', false, gitDir, ['test.js'])
61+
const res = await makeCmdTasks({ commands: () => 'test', gitDir, pathsToLint: ['test.js'] })
5862
expect(res.length).toBe(1)
5963
expect(res[0].title).toEqual('test')
6064
})
6165

6266
it('should work with function linter returning array of string', async () => {
63-
const res = await makeCmdTasks(() => ['test', 'test2'], false, gitDir, ['test.js'])
67+
const res = await makeCmdTasks({
68+
commands: () => ['test', 'test2'],
69+
gitDir,
70+
pathsToLint: ['test.js']
71+
})
6472
expect(res.length).toBe(2)
6573
expect(res[0].title).toEqual('test')
6674
expect(res[1].title).toEqual('test2')
6775
})
6876

6977
it('should work with function linter accepting arguments', async () => {
70-
const res = await makeCmdTasks(
71-
filenames => filenames.map(file => `test ${file}`),
72-
false,
78+
const res = await makeCmdTasks({
79+
commands: filenames => filenames.map(file => `test ${file}`),
7380
gitDir,
74-
['test.js', 'test2.js']
75-
)
81+
pathsToLint: ['test.js', 'test2.js']
82+
})
7683
expect(res.length).toBe(2)
7784
expect(res[0].title).toEqual('test test.js')
7885
expect(res[1].title).toEqual('test test2.js')
7986
})
8087

8188
it('should work with array of mixed string and function linters', async () => {
82-
const res = await makeCmdTasks(
83-
[() => 'test', 'test2', files => files.map(file => `test ${file}`)],
84-
false,
89+
const res = await makeCmdTasks({
90+
commands: [() => 'test', 'test2', files => files.map(file => `test ${file}`)],
8591
gitDir,
86-
['test.js', 'test2.js', 'test3.js']
87-
)
92+
pathsToLint: ['test.js', 'test2.js', 'test3.js']
93+
})
8894
expect(res.length).toBe(5)
8995
expect(res[0].title).toEqual('test')
9096
expect(res[1].title).toEqual('test2')

‎test/resolveTaskFn.spec.js

+18
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,24 @@ describe('resolveTaskFn', () => {
107107
})
108108
})
109109

110+
it('should always pass `process.cwd()` as `cwd` to `execa()` when relative = true', async () => {
111+
expect.assertions(2)
112+
const taskFn = resolveTaskFn({
113+
...defaultOpts,
114+
linter: 'git add',
115+
relative: true
116+
})
117+
118+
await taskFn()
119+
expect(execa).toHaveBeenCalledTimes(1)
120+
expect(execa).lastCalledWith('git', ['add', 'test.js'], {
121+
cwd: process.cwd(),
122+
preferLocal: true,
123+
reject: false,
124+
shell: false
125+
})
126+
})
127+
110128
it('should throw error for failed linters', async () => {
111129
expect.assertions(1)
112130
execa.mockResolvedValueOnce({

‎test/runAll.2.spec.js

-10
This file was deleted.

‎test/runAll.spec.js

+10-10
Original file line numberDiff line numberDiff line change
@@ -38,36 +38,36 @@ describe('runAll', () => {
3838

3939
it('should resolve the promise with no tasks', async () => {
4040
expect.assertions(1)
41-
const res = await runAll({})
41+
const res = await runAll({ config: {} })
4242

4343
expect(res).toEqual('No tasks to run.')
4444
})
4545

4646
it('should resolve the promise with no files', async () => {
4747
expect.assertions(1)
48-
await runAll({ '*.js': ['echo "sample"'] })
48+
await runAll({ config: { '*.js': ['echo "sample"'] } })
4949
expect(console.printHistory()).toMatchSnapshot()
5050
})
5151

5252
it('should use an injected logger', async () => {
5353
expect.assertions(1)
5454
const logger = makeConsoleMock()
55-
await runAll({ '*.js': ['echo "sample"'] }, undefined, true, undefined, logger)
55+
await runAll({ config: { '*.js': ['echo "sample"'] }, debug: true }, logger)
5656
expect(logger.printHistory()).toMatchSnapshot()
5757
})
5858

5959
it('should not skip tasks if there are files', async () => {
6060
expect.assertions(1)
6161
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
62-
await runAll({ '*.js': ['echo "sample"'] })
62+
await runAll({ config: { '*.js': ['echo "sample"'] } })
6363
expect(console.printHistory()).toMatchSnapshot()
6464
})
6565

6666
it('should not skip stashing and restoring if there are partially staged files', async () => {
6767
expect.assertions(4)
6868
hasPartiallyStagedFiles.mockImplementationOnce(() => Promise.resolve(true))
6969
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
70-
await runAll({ '*.js': ['echo "sample"'] })
70+
await runAll({ config: { '*.js': ['echo "sample"'] } })
7171
expect(gitStashSave).toHaveBeenCalledTimes(1)
7272
expect(updateStash).toHaveBeenCalledTimes(1)
7373
expect(gitStashPop).toHaveBeenCalledTimes(1)
@@ -78,7 +78,7 @@ describe('runAll', () => {
7878
expect.assertions(4)
7979
hasPartiallyStagedFiles.mockImplementationOnce(() => Promise.resolve(false))
8080
getStagedFiles.mockImplementationOnce(async () => ['sample.js'])
81-
await runAll({ '*.js': ['echo "sample"'] })
81+
await runAll({ config: { '*.js': ['echo "sample"'] } })
8282
expect(gitStashSave).toHaveBeenCalledTimes(0)
8383
expect(updateStash).toHaveBeenCalledTimes(0)
8484
expect(gitStashPop).toHaveBeenCalledTimes(0)
@@ -100,7 +100,7 @@ describe('runAll', () => {
100100
)
101101

102102
try {
103-
await runAll({ '*.js': ['echo "sample"'] })
103+
await runAll({ config: { '*.js': ['echo "sample"'] } })
104104
} catch (err) {
105105
console.log(err)
106106
}
@@ -115,7 +115,7 @@ describe('runAll', () => {
115115
getStagedFiles.mockImplementationOnce(async () => new Array(100000).fill('sample.js'))
116116

117117
try {
118-
await runAll({ '*.js': () => 'echo "sample"' })
118+
await runAll({ config: { '*.js': () => 'echo "sample"' } })
119119
} catch (err) {
120120
console.log(err)
121121
}
@@ -139,7 +139,7 @@ describe('runAll', () => {
139139
)
140140

141141
try {
142-
await runAll({ '*.js': ['echo "sample"'] })
142+
await runAll({ config: { '*.js': ['echo "sample"'] } })
143143
} catch (err) {
144144
console.log(err)
145145
}
@@ -170,7 +170,7 @@ describe('runAll', () => {
170170
)
171171

172172
try {
173-
await runAll({ '*.js': ['echo "sample"'] })
173+
await runAll({ config: { '*.js': ['echo "sample"'] } })
174174
} catch (err) {
175175
console.log(err)
176176
}

‎test/runAll.unmocked.spec.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import runAll from '../src/runAll'
2+
import resolveGitDir from '../src/resolveGitDir'
3+
4+
jest.mock('../src/resolveGitDir')
5+
jest.unmock('execa')
6+
7+
describe('runAll', () => {
8+
it('should throw when not in a git directory', async () => {
9+
resolveGitDir.mockImplementationOnce(async () => null)
10+
await expect(runAll({})).rejects.toThrowErrorMatchingSnapshot()
11+
})
12+
})

0 commit comments

Comments
 (0)
Please sign in to comment.