This repository was archived by the owner on Dec 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 401
/
Copy pathgit-strategies.test.js
2100 lines (1770 loc) · 79.7 KB
/
git-strategies.test.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'fs-extra';
import path from 'path';
import http from 'http';
import os from 'os';
import mkdirp from 'mkdirp';
import dedent from 'dedent-js';
import hock from 'hock';
import {GitProcess} from 'dugite';
import CompositeGitStrategy from '../lib/composite-git-strategy';
import GitShellOutStrategy, {LargeRepoError} from '../lib/git-shell-out-strategy';
import WorkerManager from '../lib/worker-manager';
import Author from '../lib/models/author';
import {cloneRepository, initRepository, assertDeepPropertyVals, setUpLocalAndRemoteRepositories} from './helpers';
import {normalizeGitHelperPath, getTempDir} from '../lib/helpers';
import * as reporterProxy from '../lib/reporter-proxy';
/**
* KU Thoughts: The GitShellOutStrategy methods are tested in Repository tests for the most part
* For now, in order to minimize duplication, I'll limit test coverage here to methods that produce
* output that we rely on, to serve as documentation
*/
[
[GitShellOutStrategy],
].forEach(function(strategies) {
const createTestStrategy = (...args) => {
return CompositeGitStrategy.withStrategies(strategies)(...args);
};
describe(`Git commands for CompositeGitStrategy made of [${strategies.map(s => s.name).join(', ')}]`, function() {
describe('exec', function() {
let git, incrementCounterStub;
beforeEach(async function() {
const workingDir = await cloneRepository();
git = createTestStrategy(workingDir);
incrementCounterStub = sinon.stub(reporterProxy, 'incrementCounter');
});
describe('when the WorkerManager is not ready or disabled', function() {
beforeEach(function() {
sinon.stub(WorkerManager.getInstance(), 'isReady').returns(false);
});
it('kills the git process when cancel is triggered by the prompt server', async function() {
const promptStub = sinon.stub().rejects();
git.setPromptCallback(promptStub);
const stdin = dedent`
protocol=https
host=noway.com
username=me
`;
await git.exec(['credential', 'fill'], {useGitPromptServer: true, stdin});
assert.isTrue(promptStub.called);
});
});
it('rejects if the process fails to spawn for an unexpected reason', async function() {
sinon.stub(git, 'executeGitCommand').returns({promise: Promise.reject(new Error('wat'))});
await assert.isRejected(git.exec(['version']), /wat/);
});
it('does not call incrementCounter when git command is on the ignore list', async function() {
await git.exec(['status']);
assert.equal(incrementCounterStub.callCount, 0);
});
it('does call incrementCounter when git command is NOT on the ignore list', async function() {
await git.exec(['commit', '--allow-empty', '-m', 'make an empty commit']);
assert.equal(incrementCounterStub.callCount, 1);
assert.deepEqual(incrementCounterStub.lastCall.args, ['commit']);
});
});
// https://github.com/atom/github/issues/1051
// https://github.com/atom/github/issues/898
it('passes all environment variables to spawned git process', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
// dugite copies the env for us, so this is only an issue when using a Renderer process
await WorkerManager.getInstance().getReadyPromise();
const hookContent = dedent`
#!/bin/sh
if [ "$ALLOWCOMMIT" != "true" ]
then
echo "cannot commit. set \\$ALLOWCOMMIT to 'true'"
exit 1
fi
`;
const hookPath = path.join(workingDirPath, '.git', 'hooks', 'pre-commit');
await fs.writeFile(hookPath, hookContent, {encoding: 'utf8'});
fs.chmodSync(hookPath, 0o755);
delete process.env.ALLOWCOMMIT;
await assert.isRejected(git.exec(['commit', '--allow-empty', '-m', 'commit yo']), /ALLOWCOMMIT/);
process.env.ALLOWCOMMIT = 'true';
await git.exec(['commit', '--allow-empty', '-m', 'commit for real']);
});
describe('resolveDotGitDir', function() {
it('returns the path to the .git dir for a working directory if it exists, and null otherwise', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
const dotGitFolder = await git.resolveDotGitDir(workingDirPath);
assert.equal(dotGitFolder, path.join(workingDirPath, '.git'));
fs.removeSync(path.join(workingDirPath, '.git'));
assert.isNull(await git.resolveDotGitDir(workingDirPath));
});
it('supports gitdir files', async function() {
const workingDirPath = await cloneRepository('three-files');
const workingDirPathWithDotGitFile = await getTempDir();
await fs.writeFile(
path.join(workingDirPathWithDotGitFile, '.git'),
`gitdir: ${path.join(workingDirPath, '.git')}`,
{encoding: 'utf8'},
);
const git = createTestStrategy(workingDirPathWithDotGitFile);
const dotGitFolder = await git.resolveDotGitDir(workingDirPathWithDotGitFile);
assert.equal(dotGitFolder, path.join(workingDirPath, '.git'));
});
});
describe('fetchCommitMessageTemplate', function() {
let git, workingDirPath, templateText;
beforeEach(async function() {
workingDirPath = await cloneRepository('three-files');
git = createTestStrategy(workingDirPath);
templateText = 'some commit message';
});
it('gets commit message from template', async function() {
const commitMsgTemplatePath = path.join(workingDirPath, '.gitmessage');
await fs.writeFile(commitMsgTemplatePath, templateText, {encoding: 'utf8'});
await git.setConfig('commit.template', commitMsgTemplatePath);
assert.equal(await git.fetchCommitMessageTemplate(), templateText);
});
it('if config is not set return null', async function() {
assert.isNotOk(await git.getConfig('commit.template')); // falsy value of null or ''
assert.isNull(await git.fetchCommitMessageTemplate());
});
it('if config is set but file does not exist throw an error', async function() {
const nonExistentCommitTemplatePath = path.join(workingDirPath, 'file-that-doesnt-exist');
await git.setConfig('commit.template', nonExistentCommitTemplatePath);
await assert.isRejected(
git.fetchCommitMessageTemplate(),
`Invalid commit template path set in Git config: ${nonExistentCommitTemplatePath}`,
);
});
it('replaces ~ with your home directory', async function() {
// Fun fact: even on Windows, git does not accept "~\does-not-exist.txt"
await git.setConfig('commit.template', '~/does-not-exist.txt');
await assert.isRejected(
git.fetchCommitMessageTemplate(),
`Invalid commit template path set in Git config: ${path.join(os.homedir(), 'does-not-exist.txt')}`,
);
});
it("replaces ~user with user's home directory", async function() {
const expectedFullPath = path.join(path.dirname(os.homedir()), 'nope/does-not-exist.txt');
await git.setConfig('commit.template', '~nope/does-not-exist.txt');
await assert.isRejected(
git.fetchCommitMessageTemplate(),
`Invalid commit template path set in Git config: ${expectedFullPath}`,
);
});
it('interprets relative paths local to the working directory', async function() {
const subDir = path.join(workingDirPath, 'abc/def/ghi');
const subPath = path.join(subDir, 'template.txt');
await fs.mkdirs(subDir);
await fs.writeFile(subPath, templateText, {encoding: 'utf8'});
await git.setConfig('commit.template', path.join('abc/def/ghi/template.txt'));
assert.strictEqual(await git.fetchCommitMessageTemplate(), templateText);
});
});
describe('getStatusBundle()', function() {
if (process.platform === 'win32') {
it('normalizes the path separator on Windows', async function() {
const workingDir = await cloneRepository('three-files');
const git = createTestStrategy(workingDir);
const [relPathA, relPathB] = ['a.txt', 'b.txt'].map(fileName => path.join('subdir-1', fileName));
const [absPathA, absPathB] = [relPathA, relPathB].map(relPath => path.join(workingDir, relPath));
await fs.writeFile(absPathA, 'some changes here\n', {encoding: 'utf8'});
await fs.writeFile(absPathB, 'more changes here\n', {encoding: 'utf8'});
await git.stageFiles([relPathB]);
const {changedEntries} = await git.getStatusBundle();
const changedPaths = changedEntries.map(entry => entry.filePath);
assert.deepEqual(changedPaths, [relPathA, relPathB]);
});
}
it('throws a LargeRepoError when the status output is too large', async function() {
const workingDir = await cloneRepository('three-files');
const git = createTestStrategy(workingDir);
sinon.stub(git, 'exec').resolves({length: 1024 * 1024 * 10 + 1});
await assert.isRejected(git.getStatusBundle(), LargeRepoError);
});
});
describe('getHeadCommit()', function() {
it('gets the SHA and message of the most recent commit', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
const commit = await git.getHeadCommit();
assert.equal(commit.sha, '66d11860af6d28eb38349ef83de475597cb0e8b4');
assert.equal(commit.messageSubject, 'Initial commit');
assert.isFalse(commit.unbornRef);
});
it('notes when HEAD is an unborn ref', async function() {
const workingDirPath = await initRepository();
const git = createTestStrategy(workingDirPath);
const commit = await git.getHeadCommit();
assert.isTrue(commit.unbornRef);
});
});
describe('getCommits()', function() {
describe('when no commits exist in the repository', function() {
it('returns an array with an unborn ref commit when the include unborn option is passed', async function() {
const workingDirPath = await initRepository();
const git = createTestStrategy(workingDirPath);
const commits = await git.getCommits({includeUnborn: true});
assert.lengthOf(commits, 1);
assert.isTrue(commits[0].unbornRef);
});
it('returns an empty array when the include unborn option is not passed', async function() {
const workingDirPath = await initRepository();
const git = createTestStrategy(workingDirPath);
const commits = await git.getCommits();
assert.lengthOf(commits, 0);
});
});
it('returns all commits if fewer than max commits exist', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
const commits = await git.getCommits({max: 10});
assert.lengthOf(commits, 3);
assert.deepEqual(commits[0], {
sha: '90b17a8e3fa0218f42afc1dd24c9003e285f4a82',
author: new Author('[email protected]', 'Katrina Uychaco'),
authorDate: 1471113656,
messageSubject: 'third commit',
messageBody: '',
coAuthors: [],
unbornRef: false,
patch: [],
});
assert.deepEqual(commits[1], {
sha: '18920c900bfa6e4844853e7e246607a31c3e2e8c',
author: new Author('[email protected]', 'Katrina Uychaco'),
authorDate: 1471113642,
messageSubject: 'second commit',
messageBody: '',
coAuthors: [],
unbornRef: false,
patch: [],
});
assert.deepEqual(commits[2], {
sha: '46c0d7179fc4e348c3340ff5e7957b9c7d89c07f',
author: new Author('[email protected]', 'Katrina Uychaco'),
authorDate: 1471113625,
messageSubject: 'first commit',
messageBody: '',
coAuthors: [],
unbornRef: false,
patch: [],
});
});
it('returns an array of the last max commits', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
for (let i = 1; i <= 10; i++) {
// eslint-disable-next-line no-await-in-loop
await git.commit(`Commit ${i}`, {allowEmpty: true});
}
const commits = await git.getCommits({max: 10});
assert.lengthOf(commits, 10);
assert.strictEqual(commits[0].messageSubject, 'Commit 10');
assert.strictEqual(commits[9].messageSubject, 'Commit 1');
});
it('includes co-authors based on commit body trailers', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.commit(dedent`
Implemented feature collaboratively
Co-authored-by: name <[email protected]>
Co-authored-by: another-name <[email protected]>
Co-authored-by: yet-another <[email protected]>
`, {allowEmpty: true});
const commits = await git.getCommits({max: 1});
assert.lengthOf(commits, 1);
assert.deepEqual(commits[0].coAuthors, [
new Author('[email protected]', 'name'),
new Author('[email protected]', 'another-name'),
new Author('[email protected]', 'yet-another'),
]);
});
it('preserves newlines and whitespace in the original commit body', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.commit(dedent`
Implemented feature
Detailed explanation paragraph 1
Detailed explanation paragraph 2
#123 with an issue reference
`.trim(), {allowEmpty: true, verbatim: true});
const commits = await git.getCommits({max: 1});
assert.lengthOf(commits, 1);
assert.strictEqual(commits[0].messageSubject, 'Implemented feature');
assert.strictEqual(commits[0].messageBody,
'Detailed explanation paragraph 1\n\nDetailed explanation paragraph 2\n#123 with an issue reference');
});
describe('when patch option is true', function() {
it('returns the diff associated with fetched commits', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
const commits = await git.getCommits({max: 3, includePatch: true});
assertDeepPropertyVals(commits[0].patch, [{
oldPath: 'file.txt',
newPath: 'file.txt',
oldMode: '100644',
newMode: '100644',
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 1,
newLineCount: 1,
heading: '',
lines: [
'-two',
'+three',
],
},
],
status: 'modified',
}]);
assertDeepPropertyVals(commits[1].patch, [{
oldPath: 'file.txt',
newPath: 'file.txt',
oldMode: '100644',
newMode: '100644',
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 1,
newLineCount: 1,
heading: '',
lines: [
'-one',
'+two',
],
},
],
status: 'modified',
}]);
assertDeepPropertyVals(commits[2].patch, [{
oldPath: null,
newPath: 'file.txt',
oldMode: null,
newMode: '100644',
hunks: [
{
oldStartLine: 0,
oldLineCount: 0,
newStartLine: 1,
newLineCount: 1,
heading: '',
lines: [
'+one',
],
},
],
status: 'added',
}]);
});
});
});
describe('getAuthors', function() {
it('returns list of all authors in the last <max> commits', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.exec(['config', 'user.name', 'Mona Lisa']);
await git.exec(['config', 'user.email', '[email protected]']);
await git.commit('Commit from Mona', {allowEmpty: true});
await git.exec(['config', 'user.name', 'Hubot']);
await git.exec(['config', 'user.email', '[email protected]']);
await git.commit('Commit from Hubot', {allowEmpty: true});
await git.exec(['config', 'user.name', 'Me']);
await git.exec(['config', 'user.email', '[email protected]']);
await git.commit('Commit from me', {allowEmpty: true});
const authors = await git.getAuthors({max: 3});
assert.deepEqual(authors, {
'[email protected]': 'Mona Lisa',
'[email protected]': 'Hubot',
'[email protected]': 'Me',
});
});
it('includes commit authors', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.exec(['config', 'user.name', 'Com Mitter']);
await git.exec(['config', 'user.email', '[email protected]']);
await git.exec(['commit', '--allow-empty', '--author="A U Thor <[email protected]>"', '-m', 'Commit together!']);
const authors = await git.getAuthors({max: 1});
assert.deepEqual(authors, {
'[email protected]': 'Com Mitter',
'[email protected]': 'A U Thor',
});
});
it('includes co-authors from trailers', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.exec(['config', 'user.name', 'Com Mitter']);
await git.exec(['config', 'user.email', '[email protected]']);
await git.commit(dedent`
Implemented feature collaboratively
Co-authored-by: name <[email protected]>
Co-authored-by: another name <[email protected]>
Co-authored-by: yet another name <[email protected]>
`, {allowEmpty: true});
const authors = await git.getAuthors({max: 1});
assert.deepEqual(authors, {
'[email protected]': 'Com Mitter',
'[email protected]': 'name',
'[email protected]': 'another name',
'[email protected]': 'yet another name',
});
});
it('returns an empty array when there are no commits', async function() {
const workingDirPath = await initRepository();
const git = createTestStrategy(workingDirPath);
const authors = await git.getAuthors({max: 1});
assert.deepEqual(authors, []);
});
it('propagates other git errors', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
sinon.stub(git, 'exec').rejects(new Error('oh no'));
await assert.isRejected(git.getAuthors(), /oh no/);
});
});
describe('diffFileStatus', function() {
it('returns an object with working directory file diff status between relative to specified target commit', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'a.txt'), 'qux\nfoo\nbar\n', 'utf8');
fs.unlinkSync(path.join(workingDirPath, 'b.txt'));
fs.renameSync(path.join(workingDirPath, 'c.txt'), path.join(workingDirPath, 'd.txt'));
fs.writeFileSync(path.join(workingDirPath, 'e.txt'), 'qux', 'utf8');
const diffOutput = await git.diffFileStatus({target: 'HEAD'});
assert.deepEqual(diffOutput, {
'a.txt': 'modified',
'b.txt': 'deleted',
'c.txt': 'deleted',
'd.txt': 'added',
'e.txt': 'added',
});
});
it('returns an empty object if there are no added, modified, or removed files', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
const diffOutput = await git.diffFileStatus({target: 'HEAD'});
assert.deepEqual(diffOutput, {});
});
it('only returns untracked files if the staged option is not passed', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'new-file.txt'), 'qux', 'utf8');
let diffOutput = await git.diffFileStatus({target: 'HEAD'});
assert.deepEqual(diffOutput, {'new-file.txt': 'added'});
diffOutput = await git.diffFileStatus({target: 'HEAD', staged: true});
assert.deepEqual(diffOutput, {});
});
});
describe('getUntrackedFiles', function() {
it('returns an array of untracked file paths', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'd.txt'), 'foo', 'utf8');
fs.writeFileSync(path.join(workingDirPath, 'e.txt'), 'bar', 'utf8');
fs.writeFileSync(path.join(workingDirPath, 'f.txt'), 'qux', 'utf8');
assert.deepEqual(await git.getUntrackedFiles(), ['d.txt', 'e.txt', 'f.txt']);
});
it('handles untracked files in nested folders', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'd.txt'), 'foo', 'utf8');
const folderPath = path.join(workingDirPath, 'folder', 'subfolder');
mkdirp.sync(folderPath);
fs.writeFileSync(path.join(folderPath, 'e.txt'), 'bar', 'utf8');
fs.writeFileSync(path.join(folderPath, 'f.txt'), 'qux', 'utf8');
assert.deepEqual(await git.getUntrackedFiles(), [
'd.txt',
path.join('folder', 'subfolder', 'e.txt'),
path.join('folder', 'subfolder', 'f.txt'),
]);
});
it('returns an empty array if there are no untracked files', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
assert.deepEqual(await git.getUntrackedFiles(), []);
});
});
describe('getDiffsForFilePath', function() {
it('returns an empty array if there are no modified, added, or deleted files', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
const diffOutput = await git.getDiffsForFilePath('a.txt');
assert.deepEqual(diffOutput, []);
});
it('ignores merge conflict files', async function() {
const workingDirPath = await cloneRepository('merge-conflict');
const git = createTestStrategy(workingDirPath);
const diffOutput = await git.getDiffsForFilePath('added-to-both.txt');
assert.deepEqual(diffOutput, []);
});
it('bypasses external diff tools', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'a.txt'), 'qux\nfoo\nbar\n', 'utf8');
process.env.GIT_EXTERNAL_DIFF = 'bogus_app_name';
const diffOutput = await git.getDiffsForFilePath('a.txt');
delete process.env.GIT_EXTERNAL_DIFF;
assert.isDefined(diffOutput);
});
it('rejects if an unexpected number of diffs is returned', async function() {
const workingDirPath = await cloneRepository();
const git = createTestStrategy(workingDirPath);
sinon.stub(git, 'exec').resolves(dedent`
diff --git aaa.txt aaa.txt
index df565d30..244a7225 100644
--- aaa.txt
+++ aaa.txt
@@ -100,3 +100,3 @@
000
-001
+002
003
diff --git aaa.txt aaa.txt
index df565d30..244a7225 100644
--- aaa.txt
+++ aaa.txt
@@ -100,3 +100,3 @@
000
-001
+002
003
diff --git aaa.txt aaa.txt
index df565d30..244a7225 100644
--- aaa.txt
+++ aaa.txt
@@ -100,3 +100,3 @@
000
-001
+002
003
`);
await assert.isRejected(git.getDiffsForFilePath('aaa.txt'), /Expected between 0 and 2 diffs/);
});
describe('when the file is unstaged', function() {
it('returns a diff comparing the working directory copy of the file and the version on the index', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'a.txt'), 'qux\nfoo\nbar\n', 'utf8');
fs.renameSync(path.join(workingDirPath, 'c.txt'), path.join(workingDirPath, 'd.txt'));
assertDeepPropertyVals(await git.getDiffsForFilePath('a.txt'), [{
oldPath: 'a.txt',
newPath: 'a.txt',
oldMode: '100644',
newMode: '100644',
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 1,
newLineCount: 3,
heading: '',
lines: [
'+qux',
' foo',
'+bar',
],
},
],
status: 'modified',
}]);
assertDeepPropertyVals(await git.getDiffsForFilePath('c.txt'), [{
oldPath: 'c.txt',
newPath: null,
oldMode: '100644',
newMode: null,
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 0,
newLineCount: 0,
heading: '',
lines: ['-baz'],
},
],
status: 'deleted',
}]);
assertDeepPropertyVals(await git.getDiffsForFilePath('d.txt'), [{
oldPath: null,
newPath: 'd.txt',
oldMode: null,
newMode: '100644',
hunks: [
{
oldStartLine: 0,
oldLineCount: 0,
newStartLine: 1,
newLineCount: 1,
heading: '',
lines: ['+baz'],
},
],
status: 'added',
}]);
});
});
describe('when the file is staged', function() {
it('returns a diff comparing the index and head versions of the file', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'a.txt'), 'qux\nfoo\nbar\n', 'utf8');
fs.renameSync(path.join(workingDirPath, 'c.txt'), path.join(workingDirPath, 'd.txt'));
await git.exec(['add', '.']);
assertDeepPropertyVals(await git.getDiffsForFilePath('a.txt', {staged: true}), [{
oldPath: 'a.txt',
newPath: 'a.txt',
oldMode: '100644',
newMode: '100644',
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 1,
newLineCount: 3,
heading: '',
lines: [
'+qux',
' foo',
'+bar',
],
},
],
status: 'modified',
}]);
assertDeepPropertyVals(await git.getDiffsForFilePath('c.txt', {staged: true}), [{
oldPath: 'c.txt',
newPath: null,
oldMode: '100644',
newMode: null,
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 0,
newLineCount: 0,
heading: '',
lines: ['-baz'],
},
],
status: 'deleted',
}]);
assertDeepPropertyVals(await git.getDiffsForFilePath('d.txt', {staged: true}), [{
oldPath: null,
newPath: 'd.txt',
oldMode: null,
newMode: '100644',
hunks: [
{
oldStartLine: 0,
oldLineCount: 0,
newStartLine: 1,
newLineCount: 1,
heading: '',
lines: ['+baz'],
},
],
status: 'added',
}]);
});
});
describe('when the file is staged and a base commit is specified', function() {
it('returns a diff comparing the file on the index and in the specified commit', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
assertDeepPropertyVals(await git.getDiffsForFilePath('file.txt', {staged: true, baseCommit: 'HEAD~'}), [{
oldPath: 'file.txt',
newPath: 'file.txt',
oldMode: '100644',
newMode: '100644',
hunks: [
{
oldStartLine: 1,
oldLineCount: 1,
newStartLine: 1,
newLineCount: 1,
heading: '',
lines: ['-two', '+three'],
},
],
status: 'modified',
}]);
});
});
describe('when the file is new', function() {
it('returns a diff representing the addition of the file', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.writeFileSync(path.join(workingDirPath, 'new-file.txt'), 'qux\nfoo\nbar\n', 'utf8');
assertDeepPropertyVals(await git.getDiffsForFilePath('new-file.txt'), [{
oldPath: null,
newPath: 'new-file.txt',
oldMode: null,
newMode: '100644',
hunks: [
{
oldStartLine: 0,
oldLineCount: 0,
newStartLine: 1,
newLineCount: 3,
heading: '',
lines: [
'+qux',
'+foo',
'+bar',
],
},
],
status: 'added',
}]);
});
describe('when the file is binary', function() {
it('returns an empty diff', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
const data = Buffer.alloc(10);
for (let i = 0; i < 10; i++) {
data.writeUInt8(i + 200, i);
}
// make the file executable so we test that executable mode is set correctly
fs.writeFileSync(path.join(workingDirPath, 'new-file.bin'), data, {mode: 0o755});
const expectedFileMode = process.platform === 'win32' ? '100644' : '100755';
assertDeepPropertyVals(await git.getDiffsForFilePath('new-file.bin'), [{
oldPath: null,
newPath: 'new-file.bin',
oldMode: null,
newMode: expectedFileMode,
hunks: [],
status: 'added',
}]);
});
});
});
});
describe('getStagedChangesPatch', function() {
it('returns an empty patch if there are no staged files', async function() {
const workdir = await cloneRepository('three-files');
const git = createTestStrategy(workdir);
const mp = await git.getStagedChangesPatch();
assert.lengthOf(mp, 0);
});
it('returns a combined diff of all staged files', async function() {
const workdir = await cloneRepository('each-staging-group');
const git = createTestStrategy(workdir);
await assert.isRejected(git.merge('origin/branch'));
await fs.writeFile(path.join(workdir, 'unstaged-1.txt'), 'Unstaged file');
await fs.writeFile(path.join(workdir, 'unstaged-2.txt'), 'Unstaged file');
await fs.writeFile(path.join(workdir, 'staged-1.txt'), 'Staged file');
await fs.writeFile(path.join(workdir, 'staged-2.txt'), 'Staged file');
await fs.writeFile(path.join(workdir, 'staged-3.txt'), 'Staged file');
await git.stageFiles(['staged-1.txt', 'staged-2.txt', 'staged-3.txt']);
const diffs = await git.getStagedChangesPatch();
assert.deepEqual(diffs.map(diff => diff.newPath), ['staged-1.txt', 'staged-2.txt', 'staged-3.txt']);
});
});
describe('isMerging', function() {
it('returns true if `.git/MERGE_HEAD` exists', async function() {
const workingDirPath = await cloneRepository('merge-conflict');
const dotGitDir = path.join(workingDirPath, '.git');
const git = createTestStrategy(workingDirPath);
let isMerging = await git.isMerging(dotGitDir);
assert.isFalse(isMerging);
try {
await git.merge('origin/branch');
} catch (e) {
// expect merge to have conflicts
}
isMerging = await git.isMerging(dotGitDir);
assert.isTrue(isMerging);
fs.unlinkSync(path.join(workingDirPath, '.git', 'MERGE_HEAD'));
isMerging = await git.isMerging(dotGitDir);
assert.isFalse(isMerging);
});
});
describe('checkout(branchName, {createNew})', function() {
it('returns the current branch name', async function() {
const workingDirPath = await cloneRepository('merge-conflict');
const git = createTestStrategy(workingDirPath);
assert.deepEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'master');
await git.checkout('branch');
assert.deepEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'branch');
// newBranch does not yet exist
await assert.isRejected(git.checkout('newBranch'));
assert.deepEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'branch');
assert.deepEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'branch');
await git.checkout('newBranch', {createNew: true});
assert.deepEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'newBranch');
});
it('specifies a different starting point with startPoint', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.checkout('new-branch', {createNew: true, startPoint: 'HEAD^'});
assert.strictEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'new-branch');
const commit = await git.getCommit('HEAD');
assert.strictEqual(commit.messageSubject, 'second commit');
});
it('establishes a tracking relationship with track', async function() {
const workingDirPath = await cloneRepository('multiple-commits');
const git = createTestStrategy(workingDirPath);
await git.checkout('other-branch', {createNew: true, startPoint: 'HEAD^^'});
await git.checkout('new-branch', {createNew: true, startPoint: 'other-branch', track: true});
assert.strictEqual((await git.exec(['symbolic-ref', '--short', 'HEAD'])).trim(), 'new-branch');
const commit = await git.getCommit('HEAD');
assert.strictEqual(commit.messageSubject, 'first commit');
assert.strictEqual(await git.getConfig('branch.new-branch.merge'), 'refs/heads/other-branch');
});
});
describe('reset()', function() {
describe('when soft and HEAD~ are passed as arguments', function() {
it('performs a soft reset to the parent of head', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
fs.appendFileSync(path.join(workingDirPath, 'a.txt'), 'bar\n', 'utf8');
await git.exec(['add', '.']);
await git.commit('add stuff');
const parentCommit = await git.getCommit('HEAD~');
await git.reset('soft', 'HEAD~');
const commitAfterReset = await git.getCommit('HEAD');
assert.strictEqual(commitAfterReset.sha, parentCommit.sha);
const stagedChanges = await git.getDiffsForFilePath('a.txt', {staged: true});
assert.lengthOf(stagedChanges, 1);
const stagedChange = stagedChanges[0];
assert.strictEqual(stagedChange.newPath, 'a.txt');
assert.deepEqual(stagedChange.hunks[0].lines, [' foo', '+bar']);
});
});
it('fails when an invalid type is passed', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
assert.throws(() => git.reset('scrambled'), /Invalid type scrambled/);
});
});
describe('deleteRef()', function() {
it('soft-resets an initial commit', async function() {
const workingDirPath = await cloneRepository('three-files');
const git = createTestStrategy(workingDirPath);
// Ensure that three-files still has only a single commit
assert.lengthOf(await git.getCommits({max: 10}), 1);
// Put something into the index to ensure it doesn't get lost
fs.appendFileSync(path.join(workingDirPath, 'a.txt'), 'zzz\n', 'utf8');
await git.exec(['add', '.']);
await git.deleteRef('HEAD');
const after = await git.getCommit('HEAD');
assert.isTrue(after.unbornRef);
const stagedChanges = await git.getDiffsForFilePath('a.txt', {staged: true});
assert.lengthOf(stagedChanges, 1);
const stagedChange = stagedChanges[0];