/
runAll.unmocked.spec.js
618 lines (504 loc) Β· 22.2 KB
/
runAll.unmocked.spec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
import fs from 'fs-extra'
import makeConsoleMock from 'consolemock'
import normalize from 'normalize-path'
import os from 'os'
import path from 'path'
import nanoid from 'nanoid'
import execGitBase from '../lib/execGit'
import runAll from '../lib/runAll'
jest.unmock('execa')
jest.setTimeout(20000)
const testJsFilePretty = `module.exports = {
foo: "bar"
};
`
const testJsFileUgly = `module.exports = {
'foo': 'bar',
}
`
const testJsFileUnfixable = `const obj = {
'foo': 'bar'
`
const fixJsConfig = { config: { '*.js': 'prettier --write' } }
const isAppveyor = !!process.env.APPVEYOR
const osTmpDir = isAppveyor ? 'C:\\projects' : fs.realpathSync(os.tmpdir())
/**
* Create temporary directory and return its path
* @returns {Promise<String>}
*/
const createTempDir = async () => {
const dirname = path.resolve(osTmpDir, 'lint-staged-test', nanoid())
await fs.ensureDir(dirname)
return dirname
}
/**
* Remove temporary directory
* @param {String} dirname
* @returns {Promise<Void>}
*/
const removeTempDir = async dirname => {
await fs.remove(dirname)
}
let tmpDir
let cwd
// Get file content
const readFile = async (filename, dir = cwd) =>
fs.readFile(path.resolve(dir, filename), { encoding: 'utf-8' })
// Append to file, creating if it doesn't exist
const appendFile = async (filename, content, dir = cwd) =>
fs.appendFile(path.resolve(dir, filename), content)
// Write (over) file, creating if it doesn't exist
const writeFile = async (filename, content, dir = cwd) =>
fs.writeFile(path.resolve(dir, filename), content)
// Wrap execGit to always pass `gitOps`
const execGit = async args => execGitBase(args, { cwd })
// Execute runAll before git commit to emulate lint-staged
const gitCommit = async (options, args = ['-m test']) => {
await runAll({ ...options, cwd, quiet: true })
await execGit(['commit', ...args])
}
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!"`
)
await removeTempDir(nonGitDir)
})
it('should short-circuit with no staged files', async () => {
const status = await runAll({ config: { '*.js': 'echo success' }, cwd })
expect(status).toEqual('No tasks to run.')
})
})
const globalConsoleTemp = console
describe('runAll', () => {
beforeAll(() => {
console = makeConsoleMock()
})
beforeEach(async () => {
tmpDir = await createTempDir()
cwd = normalize(tmpDir)
// Init repository with initial commit
await execGit('init')
await execGit(['config', 'user.name', '"test"'])
await execGit(['config', 'user.email', '"test@test.com"'])
await appendFile('README.md', '# Test\n')
await execGit(['add', 'README.md'])
await execGit(['commit', '-m initial commit'])
})
afterEach(async () => {
console.clearHistory()
if (!isAppveyor) {
await removeTempDir(tmpDir)
}
})
afterAll(() => {
console = globalConsoleTemp
})
it('Should commit entire staged file when no errors from linter', async () => {
// Stage pretty file
await appendFile('test.js', testJsFilePretty)
await execGit(['add', 'test.js'])
// Run lint-staged with `prettier --list-different` and commit pretty file
await gitCommit({ config: { '*.js': 'prettier --list-different' } })
// Nothing is wrong, so a new commit is created
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
expect(await readFile('test.js')).toEqual(testJsFilePretty)
})
it('Should commit entire staged file when no errors and linter modifies file', async () => {
// Stage multiple ugly files
await appendFile('test.js', testJsFileUgly)
await execGit(['add', 'test.js'])
await appendFile('test2.js', testJsFileUgly)
await execGit(['add', 'test2.js'])
// Run lint-staged with `prettier --write` and commit pretty file
await gitCommit(fixJsConfig)
// Nothing is wrong, so a new commit is created and file is pretty
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
expect(await readFile('test.js')).toEqual(testJsFilePretty)
expect(await readFile('test2.js')).toEqual(testJsFilePretty)
})
it('Should fail to commit entire staged file when errors from linter', async () => {
// Stage ugly file
await appendFile('test.js', testJsFileUgly)
await execGit(['add', 'test.js'])
const status = await execGit(['status'])
// Run lint-staged with `prettier --list-different` to break the linter
try {
await gitCommit({ config: { '*.js': 'prettier --list-different' } })
} catch (error) {
expect(error.message).toMatchInlineSnapshot(`"Something went wrong"`)
}
// Something was wrong so the repo is returned to original state
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('initial commit')
expect(await execGit(['status'])).toEqual(status)
expect(await readFile('test.js')).toEqual(testJsFileUgly)
})
it('Should fail to commit entire staged file when errors from linter and linter modifies files', async () => {
// Add unfixable file to commit so `prettier --write` breaks
await appendFile('test.js', testJsFileUnfixable)
await execGit(['add', 'test.js'])
const status = await execGit(['status'])
// Run lint-staged with `prettier --write` to break the linter
try {
await gitCommit(fixJsConfig)
} catch (error) {
expect(error.message).toMatchInlineSnapshot(`"Something went wrong"`)
}
// Something was wrong so the repo is returned to original state
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('initial commit')
expect(await execGit(['status'])).toEqual(status)
expect(await readFile('test.js')).toEqual(testJsFileUnfixable)
})
it('Should commit partial change from partially staged file when no errors from linter', async () => {
// Stage pretty file
await appendFile('test.js', testJsFilePretty)
await execGit(['add', 'test.js'])
// Edit pretty file but do not stage changes
const appended = '\nconsole.log("test");\n'
await appendFile('test.js', appended)
// Run lint-staged with `prettier --list-different` and commit pretty file
await gitCommit({ config: { '*.js': 'prettier --list-different' } })
// Nothing is wrong, so a new commit is created and file is pretty
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
// Latest commit contains pretty file
// `git show` strips empty line from here here
expect(await execGit(['show', 'HEAD:test.js'])).toEqual(testJsFilePretty.replace(/\n$/, ''))
// Since edit was not staged, the file is still modified
const status = await execGit(['status'])
expect(status).toMatch('modified: test.js')
expect(status).toMatch('no changes added to commit')
expect(await readFile('test.js')).toEqual(testJsFilePretty + appended)
})
it('Should commit partial change from partially staged file when no errors from linter and linter modifies file', async () => {
// Stage ugly file
await appendFile('test.js', testJsFileUgly)
await execGit(['add', 'test.js'])
// Edit ugly file but do not stage changes
const appended = '\n\nconsole.log("test");\n'
await appendFile('test.js', appended)
// Run lint-staged with `prettier --write` and commit pretty file
await gitCommit(fixJsConfig)
// Nothing is wrong, so a new commit is created and file is pretty
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
// Latest commit contains pretty file
// `git show` strips empty line from here here
expect(await execGit(['show', 'HEAD:test.js'])).toEqual(testJsFilePretty.replace(/\n$/, ''))
// Nothing is staged
const status = await execGit(['status'])
expect(status).toMatch('modified: test.js')
expect(status).toMatch('no changes added to commit')
// File is pretty, and has been edited
expect(await readFile('test.js')).toEqual(testJsFilePretty + appended)
})
it('Should fail to commit partial change from partially staged file when errors from linter', async () => {
// Stage ugly file
await appendFile('test.js', testJsFileUgly)
await execGit(['add', 'test.js'])
// Edit ugly file but do not stage changes
const appended = '\nconsole.log("test");\n'
await appendFile('test.js', appended)
const status = await execGit(['status'])
// Run lint-staged with `prettier --list-different` to break the linter
try {
await gitCommit({ config: { '*.js': 'prettier --list-different' } })
} catch (error) {
expect(error.message).toMatchInlineSnapshot(`"Something went wrong"`)
}
// Something was wrong so the repo is returned to original state
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('initial commit')
expect(await execGit(['status'])).toEqual(status)
expect(await readFile('test.js')).toEqual(testJsFileUgly + appended)
})
it('Should fail to commit partial change from partially staged file when errors from linter and linter modifies files', async () => {
// Add unfixable file to commit so `prettier --write` breaks
await appendFile('test.js', testJsFileUnfixable)
await execGit(['add', 'test.js'])
// Edit unfixable file but do not stage changes
const appended = '\nconsole.log("test");\n'
await appendFile('test.js', appended)
const status = await execGit(['status'])
// Run lint-staged with `prettier --write` to break the linter
try {
await gitCommit(fixJsConfig)
} catch (error) {
expect(error.message).toMatchInlineSnapshot(`"Something went wrong"`)
}
// Something was wrong so the repo is returned to original state
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('initial commit')
expect(await execGit(['status'])).toEqual(status)
expect(await readFile('test.js')).toEqual(testJsFileUnfixable + appended)
})
it('Should clear unstaged changes when linter applies same changes', async () => {
// Stage ugly file
await appendFile('test.js', testJsFileUgly)
await execGit(['add', 'test.js'])
// Replace ugly file with pretty but do not stage changes
await fs.remove(path.join(cwd, 'test.js'))
await appendFile('test.js', testJsFilePretty)
// Run lint-staged with `prettier --write` and commit pretty file
await gitCommit(fixJsConfig)
// Nothing is wrong, so a new commit is created and file is pretty
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
// Latest commit contains pretty file
// `git show` strips empty line from here here
expect(await execGit(['show', 'HEAD:test.js'])).toEqual(testJsFilePretty.replace(/\n$/, ''))
// Nothing is staged
expect(await execGit(['status'])).toMatch('nothing to commit, working tree clean')
// File is pretty, and has been edited
expect(await readFile('test.js')).toEqual(testJsFilePretty)
})
it('Should fail when linter creates a .git/index.lock', async () => {
// Stage ugly file
await appendFile('test.js', testJsFileUgly)
await execGit(['add', 'test.js'])
// Edit ugly file but do not stage changes
const appended = '\n\nconsole.log("test");\n'
await appendFile('test.js', appended)
expect(await readFile('test.js')).toEqual(testJsFileUgly + appended)
const diff = await execGit(['diff'])
// Run lint-staged with `prettier --write` and commit pretty file
// The task creates a git lock file to simulate failure
try {
await gitCommit({
config: {
'*.js': files => [
`touch ${cwd}/.git/index.lock`,
`prettier --write ${files.join(' ')}`,
`git add ${files.join(' ')}`
]
}
})
} catch (error) {
expect(error.message).toMatch('Another git process seems to be running in this repository')
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.
ERROR
Γ lint-staged failed due to a git error.
Any lost modifications can be restored from a git stash:
> git stash list
stash@{0}: On master: automatic lint-staged backup
> git stash pop stash@{0}
"
`)
}
// Something was wrong so new commit wasn't created
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('initial commit')
// But local modifications are gone
expect(await execGit(['diff'])).not.toEqual(diff)
expect(await execGit(['diff'])).toMatchInlineSnapshot(`
"diff --git a/test.js b/test.js
index f80f875..1c5643c 100644
--- a/test.js
+++ b/test.js
@@ -1,3 +1,3 @@
module.exports = {
- 'foo': 'bar',
-}
+ foo: \\"bar\\"
+};"
`)
expect(await readFile('test.js')).not.toEqual(testJsFileUgly + appended)
expect(await readFile('test.js')).toEqual(testJsFilePretty)
// Remove lock file
await fs.remove(`${cwd}/.git/index.lock`)
// Luckily there is a stash
expect(await execGit(['stash', 'list'])).toMatchInlineSnapshot(
`"stash@{0}: On master: lint-staged automatic backup"`
)
await execGit(['reset', '--hard'])
await execGit(['stash', 'pop', '--index'])
expect(await execGit(['diff'])).toEqual(diff)
expect(await readFile('test.js')).toEqual(testJsFileUgly + appended)
})
it('should handle merge conflicts', async () => {
const fileInBranchA = `module.exports = "foo";\n`
const fileInBranchB = `module.exports = 'bar'\n`
const fileInBranchBFixed = `module.exports = "bar";\n`
// Create one branch
await execGit(['checkout', '-b', 'branch-a'])
await appendFile('test.js', fileInBranchA)
await execGit(['add', '.'])
await gitCommit(fixJsConfig, ['-m commit a'])
expect(await readFile('test.js')).toEqual(fileInBranchA)
await execGit(['checkout', 'master'])
// Create another branch
await execGit(['checkout', '-b', 'branch-b'])
await appendFile('test.js', fileInBranchB)
await execGit(['add', '.'])
await gitCommit(fixJsConfig, ['-m commit b'])
expect(await readFile('test.js')).toEqual(fileInBranchBFixed)
// Merge first branch
await execGit(['checkout', 'master'])
await execGit(['merge', 'branch-a'])
expect(await readFile('test.js')).toEqual(fileInBranchA)
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('commit a')
// Merge second branch, causing merge conflict
try {
await execGit(['merge', 'branch-b'])
} catch (error) {
expect(error.message).toMatch('Merge conflict in test.js')
}
expect(await readFile('test.js')).toMatchInlineSnapshot(`
"<<<<<<< HEAD
module.exports = \\"foo\\";
=======
module.exports = \\"bar\\";
>>>>>>> branch-b
"
`)
// Fix conflict and commit using lint-staged
await writeFile('test.js', fileInBranchB)
expect(await readFile('test.js')).toEqual(fileInBranchB)
await execGit(['add', '.'])
// Do not use `gitCommit` wrapper here
await runAll({ ...fixJsConfig, cwd, quiet: true })
await execGit(['commit', '--no-edit'])
// Nothing is wrong, so a new commit is created and file is pretty
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('4')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatchInlineSnapshot(`
"Merge branch 'branch-b'
# Conflicts:
# test.js
"
`)
expect(await readFile('test.js')).toEqual(fileInBranchBFixed)
})
it('should handle merge conflict when task errors', async () => {
const fileInBranchA = `module.exports = "foo";\n`
const fileInBranchB = `module.exports = 'bar'\n`
const fileInBranchBFixed = `module.exports = "bar";\n`
// Create one branch
await execGit(['checkout', '-b', 'branch-a'])
await appendFile('test.js', fileInBranchA)
await execGit(['add', '.'])
await gitCommit(fixJsConfig, ['-m commit a'])
expect(await readFile('test.js')).toEqual(fileInBranchA)
await execGit(['checkout', 'master'])
// Create another branch
await execGit(['checkout', '-b', 'branch-b'])
await appendFile('test.js', fileInBranchB)
await execGit(['add', '.'])
await gitCommit(fixJsConfig, ['-m commit b'])
expect(await readFile('test.js')).toEqual(fileInBranchBFixed)
// Merge first branch
await execGit(['checkout', 'master'])
await execGit(['merge', 'branch-a'])
expect(await readFile('test.js')).toEqual(fileInBranchA)
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('commit a')
// Merge second branch, causing merge conflict
try {
await execGit(['merge', 'branch-b'])
} catch (error) {
expect(error.message).toMatch('Merge conflict in test.js')
}
expect(await readFile('test.js')).toMatchInlineSnapshot(`
"<<<<<<< HEAD
module.exports = \\"foo\\";
=======
module.exports = \\"bar\\";
>>>>>>> branch-b
"
`)
// Fix conflict and commit using lint-staged
await writeFile('test.js', fileInBranchB)
expect(await readFile('test.js')).toEqual(fileInBranchB)
await execGit(['add', '.'])
// Do not use `gitCommit` wrapper here
await expect(
runAll({ config: { '*.js': 'prettier --list-different' }, cwd, quiet: true })
).rejects.toThrowErrorMatchingInlineSnapshot(`"Something went wrong"`)
// Something went wrong, so runAll failed and merge is still going
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['status'])).toMatch('All conflicts fixed but you are still merging')
expect(await readFile('test.js')).toEqual(fileInBranchB)
})
it('should keep untracked files', async () => {
// Stage pretty file
await appendFile('test.js', testJsFilePretty)
await execGit(['add', 'test.js'])
// Add another file, but keep it untracked
await appendFile('test-untracked.js', testJsFilePretty)
// Run lint-staged with `prettier --list-different` and commit pretty file
await gitCommit({ config: { '*.js': 'prettier --list-different' } })
// Nothing is wrong, so a new commit is created
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
expect(await readFile('test.js')).toEqual(testJsFilePretty)
expect(await readFile('test-untracked.js')).toEqual(testJsFilePretty)
})
it('should work when amending previous commit with unstaged changes', async () => {
// Edit file from previous commit
await appendFile('README.md', '\n## Amended\n')
await execGit(['add', 'README.md'])
// Edit again, but keep it unstaged
await appendFile('README.md', '\n## Edited\n')
await appendFile('test-untracked.js', testJsFilePretty)
// Run lint-staged with `prettier --list-different` and commit pretty file
await gitCommit({ config: { '*.{js,md}': 'prettier --list-different' } }, [
'--amend',
'--no-edit'
])
// Nothing is wrong, so the commit was amended
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('1')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('initial commit')
expect(await readFile('README.md')).toMatchInlineSnapshot(`
"# Test
## Amended
## Edited
"
`)
expect(await readFile('test-untracked.js')).toEqual(testJsFilePretty)
const status = await execGit(['status'])
expect(status).toMatch('modified: README.md')
expect(status).toMatch('test-untracked.js')
expect(status).toMatch('no changes added to commit')
})
it('should not resurrect removed files due to git bug', async () => {
const readmeFile = path.resolve(cwd, 'README.md')
await fs.remove(readmeFile) // Remove file from previous commit
await execGit(['add', '.'])
await gitCommit({ config: { '*.{js,md}': 'prettier --list-different' } })
const exists = await fs.exists(readmeFile)
expect(exists).toEqual(false)
})
it('should handle binary files', async () => {
// mark test.js as binary file
await appendFile('.gitattributes', 'test.js binary\n')
// Stage pretty file
await appendFile('test.js', testJsFilePretty)
await execGit(['add', 'test.js'])
// Run lint-staged with `prettier --list-different` and commit pretty file
await gitCommit({ config: { '*.js': 'prettier --list-different' } })
// Nothing is wrong, so a new commit is created
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
expect(await readFile('test.js')).toEqual(testJsFilePretty)
})
it('should run chunked tasks when necessary', async () => {
// Stage two files
await appendFile('test.js', testJsFilePretty)
await execGit(['add', 'test.js'])
await appendFile('test2.js', testJsFilePretty)
await execGit(['add', 'test2.js'])
// Run lint-staged with `prettier --list-different` and commit pretty file
// Set maxArgLength low enough so that chunking is used
await gitCommit({ config: { '*.js': 'prettier --list-different' }, maxArgLength: 10 })
// Nothing is wrong, so a new commit is created
expect(await execGit(['rev-list', '--count', 'HEAD'])).toEqual('2')
expect(await execGit(['log', '-1', '--pretty=%B'])).toMatch('test')
expect(await readFile('test.js')).toEqual(testJsFilePretty)
expect(await readFile('test2.js')).toEqual(testJsFilePretty)
})
})