-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathversion-control-Tests.java
1500 lines (1330 loc) · 54.2 KB
/
version-control-Tests.java
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 org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ComparisonFailure;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.Permission;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GitletTests {
static final Path SRC = Path.of("../test_files");
static final Path WUG = SRC.resolve("wug.txt");
static final Path NOTWUG = SRC.resolve("notwug.txt");
static final Path WUG2 = SRC.resolve("wug2.txt");
static final Path WUG3 = SRC.resolve("wug3.txt");
static final Path CONFLICT1 = SRC.resolve("conflict1.txt");
static final Path CONFLICT2 = SRC.resolve("conflict2.txt");
static final Path CONFLICT3 = SRC.resolve("conflict3.txt");
static final Path CONFLICT4 = SRC.resolve("conflict4.txt");
static final Path CONFLICT5 = SRC.resolve("conflict5.txt");
static final Path CONFLICT6 = SRC.resolve("conflict6.txt");
static final Path A = SRC.resolve("a.txt");
static final Path B = SRC.resolve("b.txt");
static final Path C = SRC.resolve("c.txt");
static final Path D = SRC.resolve("d.txt");
static final Path E = SRC.resolve("e.txt");
static final Path F = SRC.resolve("f.txt");
static final Path G = SRC.resolve("g.txt");
static final Path NOTA = SRC.resolve("nota.txt");
static final Path NOTB = SRC.resolve("notb.txt");
static final Path NOTF = SRC.resolve("notf.txt");
static final String DATE = "Date: \\w\\w\\w \\w\\w\\w \\d+ \\d\\d:\\d\\d:\\d\\d \\d\\d\\d\\d [-+]\\d\\d\\d\\d";
static final String COMMIT_HEAD = "commit ([a-f0-9]+)[ \\t]*\\n(?:Merge:\\s+[0-9a-f]{7}\\s+[0-9a-f]{7}[ ]*\\n)?" + DATE;
static final String COMMIT_LOG = "(===[ ]*\\ncommit [a-f0-9]+[ ]*\\n(?:Merge:\\s+[0-9a-f]{7}\\s+[0-9a-f]{7}[ ]*\\n)?${DATE}[ ]*\\n(?:.|\\n)*?(?=\\Z|\\n===))"
.replace("${DATE}", DATE);
static final String ARBLINE = "[^\\n]*(?=\\n|\\Z)";
static final String ARBLINES = "(?:(?:.|\\n)*(?:\\n|\\Z)|\\A|\\Z)";
private static final String COMMAND_BASE = "java gitlet.Main ";
private static final int DELAY_MS = 150;
private static final String TESTING_DIR = "testing";
private static final PrintStream OG_OUT = System.out;
private static final ByteArrayOutputStream OUT = new ByteArrayOutputStream();
/**
* Asserts that the test suite is being run in TESTING_DIR.
* <p>
* Gitlet does dangerous file operations, and is affected by the existence
* of other files. Therefore, we must ensure that we are working in a known
* directory that (hopefully) has no files.
*/
public static void verifyWD() {
Path wd = Path.of(System.getProperty("user.dir"));
if (!wd.getFileName().endsWith(TESTING_DIR)) {
fail("This test is not being run in the `testing` directory. " +
"Please see the spec for information on how to fix this.");
}
}
@BeforeClass
public static void setup01_verifyWD() {
verifyWD();
}
/**
* Asserts that no class uses nontrivial statics.
* <p>
* Using a JUnit tester over a multiple-execution script means that
* we are running in a single invocation of the JVM, which means that
* static variables keep their values. Rather than attempting to restore
* static state (which is nontrivial), we simply ban any static state
* aside from primitives, Strings (immutable), Paths (immutable),
* Files (immutable), SimpleDateFormat (not immutable, but can't carry
* useful info), and a couple utility classes for tests.
* <p>
* This test is not a game to be defeated. Even if you manage to smuggle
* static state, the autograder will test your program by running it
* over multiple invocations, and your static variables will be reset.
*
* @throws IOException
*/
@BeforeClass
public static void setup02_noNontrivialStatics() throws IOException {
List<Class<?>> classes = new ArrayList<>();
for (String s : System.getProperty("java.class.path")
.split(System.getProperty("path.separator"))) {
if (s.endsWith(".jar")) continue;
Path p = Path.of(s);
Files.walkFileTree(p, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
if (dir.toString().endsWith(".idea")) return FileVisitResult.SKIP_SUBTREE;
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (!file.toString().toLowerCase().endsWith(".class")) return FileVisitResult.CONTINUE;
String qualifiedName = p.relativize(file)
.toString()
.replace(File.separatorChar, '.');
qualifiedName = qualifiedName.substring(0, qualifiedName.length() - 6);
try {
classes.add(Class.forName(qualifiedName));
} catch (ClassNotFoundException ignored) {
}
return FileVisitResult.CONTINUE;
}
});
}
List<String> violations = new ArrayList<>();
List<Class<?>> allowedClasses = List.of(
byte.class,
short.class,
int.class,
long.class,
float.class,
double.class,
boolean.class,
char.class,
String.class,
Path.class,
File.class,
SimpleDateFormat.class,
// Utils
FilenameFilter.class,
// For testing stdout; not actually for use by students.
ByteArrayOutputStream.class,
PrintStream.class
);
for (Class<?> clazz : classes) {
List<Field> staticFields = Arrays.stream(clazz.getDeclaredFields())
.filter(f -> Modifier.isStatic(f.getModifiers()))
.toList();
for (Field f : staticFields) {
if (!Modifier.isFinal(f.getModifiers())) {
violations.add("Non-final static field `" + f.getName() + "` found in " + clazz);
}
if (!allowedClasses.contains(f.getType())) {
violations.add("Static field `" + f.getName() + "` in " + clazz.getCanonicalName() +
" is of disallowed type " + f.getType().getSimpleName());
}
}
}
if (violations.size() > 0) {
violations.forEach(OG_OUT::println);
fail("Nontrivial static fields found, see class-level test output for GitletTests.\n" +
"These indicate that you might be trying to keep global state.");
}
}
@BeforeClass
public static void setup03_redirectStdout() {
System.setOut(new PrintStream(OUT));
}
@BeforeClass
@SuppressWarnings("removal")
public static void setup04_trapSystemExit() {
// https://openjdk.java.net/jeps/411
// https://bugs.openjdk.java.net/browse/JDK-8199704
// TODO: this is deprecated. See issues above.
System.setSecurityManager(new SecurityManager() {
@Override
public void checkExit(int status) {
if (status == 0) {
throw new SecurityException("Allowable exit code, interrupting: " + status);
}
}
// Default allow all - this isn't security sensitive
@Override
public void checkPermission(Permission perm) {
}
@Override
public void checkPermission(Permission perm, Object context) {
}
});
}
@AfterClass
@SuppressWarnings("removal")
public static void restoreSecurity() {
// JUnit uses system.exit(0) internally somewhere, so hand control back
// to the JVM before we leave the test class
// TODO: this is deprecated. See the other call for relevant issue.
System.setSecurityManager(null);
}
public void recursivelyCleanWD() throws IOException {
// DANGEROUS: We're wiping the directory.
// Must ensure that we're in the right directory, even though we did in setup01_verifyWD.
verifyWD();
// Recursively wipe the directory
Files.walkFileTree(Path.of(System.getProperty("user.dir")), new SimpleFileVisitor<>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
// Don't delete the directory itself, we're about to work in it!
if (dir.toString().equals(System.getProperty("user.dir"))) {
return FileVisitResult.CONTINUE;
}
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
// directory iteration failed
throw e;
}
}
});
}
@Before
public void startWithEmptyWD() throws IOException, InterruptedException {
recursivelyCleanWD();
TimeUnit.MILLISECONDS.sleep(DELAY_MS);
}
@After
public void endWithEmptyWD() throws IOException {
recursivelyCleanWD();
}
/**
* Returns captured output and flush the output stream
*/
public static String getOutput() {
String ret = OUT.toString();
OUT.reset();
return ret;
}
/**
* Copies a source testing file into the current testing directory.
*
* @param src -- Path to source testing file
* @param dst -- filename to write to; may exist
*/
public static void writeFile(Path src, String dst) {
try {
OG_OUT.println("Copy source file " + src + " to testing file " + dst);
Files.copy(src, Path.of(dst), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Deletes a file from the current testing directory.
*
* @param path -- filename to delete; must exist
*/
public static void deleteFile(String path) {
try {
OG_OUT.println("Delete file " + path);
Files.delete(Path.of(path));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Asserts that a file exists in the current testing directory.
*
* @param path
*/
public static void assertFileExists(String path) {
OG_OUT.println("Check that file or directory " + path + " exists");
if (!Files.exists(Path.of(path))) {
fail("Expected file " + path + " to exist; does not.");
}
}
/**
* Asserts that a file does not exist in the current testing directory.
*
* @param path
*/
public static void assertFileDoesNotExist(String path) {
OG_OUT.println("Check that file " + path + " does NOT exist");
if (Files.exists(Path.of(path))) {
fail("Expected file " + path + " to not exist; does.");
}
}
/**
* Asserts that a file both exists in current testing directory and has
* identical content to a source testing file.
*
* @param src -- source testing file containin expected content
* @param pathActual -- filename in current testing directory to check
*/
public static void assertFileEquals(Path src, String pathActual) {
OG_OUT.println("Check that source file " + src + " is identical to testing file " + pathActual);
if (!Files.exists(Path.of(pathActual))) {
fail("Expected file " + pathActual + " to exist; does not.");
}
try {
String expected = Files.readString(src).replace("\r\n", "\n");
String actual = Files.readString(Path.of(pathActual)).replace("\r\n", "\n");
assertEquals("File contents of src file " + src + " and actual file " + pathActual + " are not equal",
expected, actual);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Copied from Python testing script (`correctProgramOutput`). Intended to adjust for whitespace issues.
* Removes trailing spaces on lines, and replaces multi-spaces with single spaces.
*
* @param s -- string to normalize
* @return normalized output
*/
public static String normalizeStdOut(String s) {
return s.replace("\r\n", "\n")
.replaceAll("[ \\t]+\n", "\n")
.replaceAll("(?m)^[ \\t]+", " ");
}
/**
* Asserts that printed content to System.out is correct.
*
* @param expected -- expected printed content
*/
public static void checkOutput(String expected) {
expected = normalizeStdOut(expected).stripTrailing();
String actual = normalizeStdOut(getOutput()).stripTrailing();
assertEquals("ERROR (incorrect output)", expected, actual);
}
/**
* Builds a command-line command from a provided arugments list
*
* @param args
* @return command-line command, i.e. `java MyMain arg1 "arg with space"`
*/
public static String createCommand(String[] args) {
StringBuilder sb = new StringBuilder();
for (String arg : args) {
if (sb.length() > 0) {
sb.append(" ");
}
if (arg.contains(" ")) {
sb.append('"').append(arg).append('"');
} else {
sb.append(arg);
}
}
return sb.toString();
}
/**
* Runs the given Gitlet command.
*
* @param args
*/
public static void runGitletCommand(String[] args) {
try {
// Catch string ==
for (int i = 0; i < args.length; i ++) {
args[i] = new String(args[i]);
}
OG_OUT.println(COMMAND_BASE + createCommand(args));
gitlet.Main.main(args);
} catch (SecurityException ignored) {
} catch (Exception e) {
// Wrap IOException and other checked for poor implementations;
// can't directly catch it because it's checked and the compiler complains
// that it's not thrown
throw new RuntimeException(e);
}
}
/**
* Runs the given gitlet command and checks the exact output.
*
* @param args
* @param expectedOutput
*/
public static void gitletCommand(String[] args, String expectedOutput) {
runGitletCommand(args);
checkOutput(expectedOutput);
}
/**
* Constructs a regex matcher against the output, for tests to extract groups.
*
* @param pattern
* @return
*/
public static Matcher checkOutputRegex(String pattern) {
String actual = getOutput();
pattern = normalizeStdOut(pattern).stripTrailing();
String ogP = pattern;
pattern += "\\Z";
actual = normalizeStdOut(actual);
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(actual);
if (!m.matches()) {
m = p.matcher(actual.stripTrailing());
if (!m.matches()) {
// Manually raise a comparison error to get a rich diff for typo catching
throw new ComparisonFailure("Pattern does not match the output",
ogP, actual.stripTrailing());
}
}
return m;
}
/**
* Runs the given gitlet command and checks that the output matches a provided regex
*
* @param args
* @param pattern
* @return Matcher from the pattern, for group extraction
*/
public static Matcher gitletCommandP(String[] args, String pattern) {
runGitletCommand(args);
return checkOutputRegex(pattern);
}
public static void i_prelude1() {
gitletCommand(new String[]{"init"}, "");
}
public static void i_setup1() {
i_prelude1();
writeFile(WUG, "f.txt");
writeFile(NOTWUG, "g.txt");
gitletCommand(new String[]{"add", "g.txt"}, "");
gitletCommand(new String[]{"add", "f.txt"}, "");
}
public static void i_setup2() {
i_setup1();
gitletCommand(new String[]{"commit", "Two files"}, "");
}
public static void i_blankStatus() {
gitletCommand(new String[]{"status"}, """
=== Branches ===
*main
=== Staged Files ===
=== Removed Files ===
=== Modifications Not Staged For Commit ===
=== Untracked Files ===
""");
}
public static void i_blankStatus2() {
gitletCommand(new String[]{"status"}, """
=== Branches ===
*main
other
=== Staged Files ===
=== Removed Files ===
=== Modifications Not Staged For Commit ===
=== Untracked Files ===
""");
}
@Test
public void test01_init() {
gitletCommand(new String[]{"init"}, "");
}
@Test
public void test02_basicRestore() {
gitletCommand(new String[]{"init"}, "");
writeFile(WUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "added wug"}, "");
writeFile(NOTWUG, "wug.txt");
gitletCommand(new String[]{"restore", "--", "wug.txt"}, "");
assertFileEquals(WUG, "wug.txt");
}
@Test
public void test03_basicLog() {
gitletCommand(new String[]{"init"}, "");
writeFile(WUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "added wug"}, "");
gitletCommandP(new String[]{"log"}, """
===
${HEADER}
${DATE}
added wug
===
${HEADER}
${DATE}
initial commit
"""
.replace("${HEADER}", "commit [a-f0-9]+")
.replace("${DATE}", DATE));
}
@Test
public void test04_prevRestore() {
gitletCommand(new String[]{"init"}, "");
writeFile(WUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "version 1 of wug.txt"}, "");
writeFile(NOTWUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "version 2 of wug.txt"}, "");
assertFileEquals(NOTWUG, "wug.txt");
Matcher logMatch = gitletCommandP(new String[]{"log"}, """
===
${HEADER}
${DATE}
version 2 of wug.txt
===
${HEADER}
${DATE}
version 1 of wug.txt
===
${HEADER}
${DATE}
initial commit
"""
.replace("${HEADER}", "commit ([a-f0-9]+)")
.replace("${DATE}", DATE));
String uid2 = logMatch.group(1);
String uid1 = logMatch.group(2);
gitletCommand(new String[]{"restore", uid1, "--", "wug.txt"}, "");
assertFileEquals(WUG, "wug.txt");
gitletCommand(new String[]{"restore", uid2, "--", "wug.txt"}, "");
assertFileEquals(NOTWUG, "wug.txt");
}
@Test
public void test10_initErr() {
i_prelude1();
gitletCommand(new String[]{"init"}, "A Gitlet version-control system already exists in the current directory.");
}
@Test
public void test11_basicStatus() {
i_prelude1();
i_blankStatus();
}
@Test
public void test12_addStatus() {
i_setup1();
gitletCommand(new String[]{"status"}, """
=== Branches ===
*main
=== Staged Files ===
f.txt
g.txt
=== Removed Files ===
=== Modifications Not Staged For Commit ===
=== Untracked Files ===
""");
}
@Test
public void test13_removeStatus() {
i_setup2();
gitletCommand(new String[]{"rm", "f.txt"}, "");
assertFileDoesNotExist("f.txt");
gitletCommand(new String[]{"status"}, """
=== Branches ===
*main
=== Staged Files ===
=== Removed Files ===
f.txt
=== Modifications Not Staged For Commit ===
=== Untracked Files ===
""");
}
@Test
public void test14_addRemoveStatus() {
i_setup1();
gitletCommand(new String[]{"rm", "f.txt"}, "");
gitletCommandP(new String[]{"status"}, """
=== Branches ===
\\*main
=== Staged Files ===
g.txt
=== Removed Files ===
=== Modifications Not Staged For Commit ===
=== Untracked Files ===
${ARBLINES}
""".replace("${ARBLINES}", ARBLINES));
assertFileEquals(WUG, "f.txt");
}
@Test
public void test15_removeAddStatus() {
i_setup2();
gitletCommand(new String[]{"rm", "f.txt"}, "");
assertFileDoesNotExist("f.txt");
writeFile(WUG, "f.txt");
gitletCommand(new String[]{"add", "f.txt"}, "");
i_blankStatus();
}
@Test
public void test16_emptyCommitErr() {
i_prelude1();
gitletCommand(new String[]{"commit", "Nothing here"}, "No changes added to the commit.");
}
@Test
public void test17_emptyCommitMessageErr() {
i_prelude1();
writeFile(WUG, "f.txt");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", ""}, "Please enter a commit message.");
}
@Test
public void test18_nopAdd() {
i_setup2();
gitletCommand(new String[]{"add", "f.txt"}, "");
i_blankStatus();
}
@Test
public void test19_addMissingErr() {
i_prelude1();
gitletCommand(new String[]{"add", "f.txt"}, "File does not exist.");
i_blankStatus();
}
@Test
public void test20_statusAfterCommit() {
i_setup2();
i_blankStatus();
gitletCommand(new String[]{"rm", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Removed f.txt"}, "");
i_blankStatus();
}
@Test
public void test21_nopRemoveErr() {
i_prelude1();
writeFile(WUG, "f.txt");
gitletCommand(new String[]{"rm", "f.txt"}, "No reason to remove the file.");
}
@Test
public void test22_removeDeletedFile() {
i_setup2();
deleteFile("f.txt");
gitletCommand(new String[]{"rm", "f.txt"}, "");
gitletCommand(new String[]{"status"}, """
=== Branches ===
*main
=== Staged Files ===
=== Removed Files ===
f.txt
=== Modifications Not Staged For Commit ===
=== Untracked Files ===
""");
}
@Test
public void test23_globalLog() {
i_setup2();
String noTzDate = "Date: \\w\\w\\w \\w\\w\\w \\d+ \\d\\d:\\d\\d:\\d\\d \\d\\d\\d\\d";
String commitLog = "(===[ ]*\\ncommit [a-f0-9]+[ ]*\\n(?:Merge:\\s+[0-9a-f]{7}\\s+[0-9a-f]{7}[ ]*\\n)?${DATE1}) [-+](\\d\\d\\d\\d[ ]*\\n(?:.|\\n)*?(?=\\Z|\\n===))".replace("${DATE1}", noTzDate);
writeFile(WUG, "h.txt");
gitletCommand(new String[]{"add", "h.txt"}, "");
gitletCommand(new String[]{"commit", "Add h"}, "");
Matcher m = gitletCommandP(new String[]{"log"}, """
${COMMIT_LOG}
${COMMIT_LOG}
${COMMIT_LOG}
""".replace("${COMMIT_LOG}", commitLog));
String L1 = m.group(1) + " [-+]" + m.group(2);
String L2 = m.group(3) + " [-+]" + m.group(4);
String L3 = m.group(5) + " [-+]" + m.group(6);
gitletCommandP(new String[]{"global-log"}, ARBLINES + L1 + ARBLINES);
gitletCommandP(new String[]{"global-log"}, ARBLINES + L2 + ARBLINES);
gitletCommandP(new String[]{"global-log"}, ARBLINES + L3 + ARBLINES);
}
@Test
public void test24_globalLogPrev() {
i_setup2();
String noTzDate = "Date: \\w\\w\\w \\w\\w\\w \\d+ \\d\\d:\\d\\d:\\d\\d \\d\\d\\d\\d";
String commitLog = "(===[ ]*\\ncommit [a-f0-9]+[ ]*\\n(?:Merge:\\s+[0-9a-f]{7}\\s+[0-9a-f]{7}[ ]*\\n)?${DATE1}) [-+](\\d\\d\\d\\d[ ]*\\n(?:.|\\n)*?(?=\\Z|\\n===))".replace("${DATE1}", noTzDate);
writeFile(WUG, "h.txt");
gitletCommand(new String[]{"add", "h.txt"}, "");
gitletCommand(new String[]{"commit", "Add h"}, "");
Matcher m = gitletCommandP(new String[]{"log"}, """
${COMMIT_LOG}
${COMMIT_LOG}
${COMMIT_LOG}
""".replace("${COMMIT_LOG}", commitLog));
String L1 = m.group(1) + " [-+]" + m.group(2);
m = gitletCommandP(new String[]{"log"}, """
===
${COMMIT_HEAD}
Add h
===
${COMMIT_HEAD}${ARBLINES}
"""
.replace("${COMMIT_HEAD}", COMMIT_HEAD)
.replace("${ARBLINES}", ARBLINES));
String id = m.group(2);
gitletCommand(new String[]{"reset", id}, "");
gitletCommandP(new String[]{"global-log"}, ARBLINES + L1 + "?" + ARBLINES);
}
@Test
public void test25_successfulFind() {
i_setup2();
gitletCommand(new String[]{"rm", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Remove one file"}, "");
writeFile(NOTWUG, "f.txt");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Two files"}, "");
Matcher m = gitletCommandP(new String[]{"log"}, """
===
${COMMIT_HEAD}
Two files
===
${COMMIT_HEAD}
Remove one file
===
${COMMIT_HEAD}
Two files
===
${COMMIT_HEAD}
initial commit
""".replace("${COMMIT_HEAD}", COMMIT_HEAD));
String uid1 = m.group(4);
String uid2 = m.group(3);
String uid3 = m.group(2);
String uid4 = m.group(1);
gitletCommandP(
new String[]{"find", "Two files"},
"(${UID4}\n${UID2}|${UID2}\n${UID4})"
.replace("${UID2}", uid2)
.replace("${UID4}", uid4)
);
gitletCommand(new String[]{"find", "initial commit"}, uid1);
gitletCommand(new String[]{"find", "Remove one file"}, uid3);
}
@Test
public void test26_successfulFindOrphan() {
i_setup2();
gitletCommand(new String[]{"rm", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Remove one file"}, "");
Matcher m = gitletCommandP(new String[]{"log"}, """
===
${COMMIT_HEAD}
Remove one file
===
${COMMIT_HEAD}
Two files
===
${COMMIT_HEAD}
initial commit
""".replace("${COMMIT_HEAD}", COMMIT_HEAD));
String uid2 = m.group(2);
String uid3 = m.group(1);
gitletCommand(new String[]{"reset", uid2}, "");
gitletCommand(new String[]{"find", "Remove one file"}, uid3);
}
@Test
public void test27_unsuccessfulFindErr() {
i_setup2();
gitletCommand(new String[]{"rm", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Remove one file"}, "");
gitletCommand(new String[]{"find", "Add another file"}, "Found no commit with that message.");
}
@Test
public void test28_Restore() {
i_prelude1();
writeFile(WUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "version 1 of wug.txt"}, "");
writeFile(NOTWUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "version 2 of wug.txt"}, "");
assertFileEquals(NOTWUG, "wug.txt");
String header = "commit ([a-f0-9]+)";
Matcher m = gitletCommandP(new String[]{"log"}, """
===
${HEADER}
${DATE}
version 2 of wug.txt
===
${HEADER}
${DATE}
version 1 of wug.txt
===
${HEADER}
${DATE}
initial commit
""".replace("${HEADER}", header).replace("${DATE}", DATE));
String uid1 = m.group(2);
gitletCommand(new String[]{"restore", uid1, "--", "wug.txt"}, "");
gitletCommandP(new String[]{"status"}, """
=== Branches ===
\\*main
=== Staged Files ===
=== Removed Files ===
=== Modifications Not Staged For Commit ===
(${ARBLINE}\\n\\r?)?
=== Untracked Files ===
""".replace("${ARBLINE}", ARBLINE));
}
@Test
public void test29_badRestoreErr() {
i_prelude1();
writeFile(WUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "version 1 of wug.txt"}, "");
writeFile(NOTWUG, "wug.txt");
gitletCommand(new String[]{"add", "wug.txt"}, "");
gitletCommand(new String[]{"commit", "version 2 of wug.txt"}, "");
Matcher m = gitletCommandP(new String[]{"log"}, """
===
${COMMIT_HEAD}
version 2 of wug.txt
===
${COMMIT_HEAD}
version 1 of wug.txt
===
${COMMIT_HEAD}
initial commit
""".replace("${COMMIT_HEAD}", COMMIT_HEAD));
String uid2 = m.group(1);
gitletCommand(new String[]{"restore", uid2, "--", "warg.txt"}, "File does not exist in that commit.");
gitletCommand(new String[]{"restore", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "--", "wug.txt"},
"No commit with that id exists.");
gitletCommand(new String[]{"restore", uid2, "++", "wug.txt"}, "Incorrect operands.");
}
@Test
public void test30_branches() {
i_prelude1();
gitletCommand(new String[]{"branch", "other"}, "");
writeFile(WUG, "f.txt");
writeFile(NOTWUG, "g.txt");
gitletCommand(new String[]{"add", "g.txt"}, "");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Main two files"}, "");
assertFileExists("f.txt");
assertFileExists("g.txt");
gitletCommand(new String[]{"switch", "other"}, "");
assertFileDoesNotExist("f.txt");
assertFileDoesNotExist("g.txt");
writeFile(NOTWUG, "f.txt");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Alternative file"}, "");
assertFileEquals(NOTWUG, "f.txt");
assertFileDoesNotExist("g.txt");
gitletCommand(new String[]{"switch", "main"}, "");
assertFileEquals(WUG, "f.txt");
assertFileEquals(NOTWUG, "g.txt");
gitletCommand(new String[]{"switch", "other"}, "");
assertFileEquals(NOTWUG, "f.txt");
assertFileDoesNotExist("g.txt");
}
@Test
public void test30a_rmBranch() {
i_prelude1();
gitletCommand(new String[]{"branch", "other"}, "");
writeFile(WUG, "f.txt");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", "File f.txt"}, "");
gitletCommand(new String[]{"switch", "other"}, "");
writeFile(NOTWUG, "g.txt");
gitletCommand(new String[]{"add", "g.txt"}, "");
gitletCommand(new String[]{"commit", "File g.txt"}, "");
gitletCommand(new String[]{"switch", "main"}, "");
gitletCommand(new String[]{"rm-branch", "other"}, "");
gitletCommand(new String[]{"switch", "other"}, "No such branch exists.");
assertFileDoesNotExist("g.txt");
assertFileEquals(WUG, "f.txt");
}
@Test
public void test31_duplicateBranchErr() {
i_prelude1();
gitletCommand(new String[]{"branch", "other"}, "");
writeFile(WUG, "f.txt");
writeFile(NOTWUG, "g.txt");
gitletCommand(new String[]{"add", "g.txt"}, "");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", "Main two files"}, "");
gitletCommand(new String[]{"branch", "other"}, "A branch with that name already exists.");
}
@Test
public void test31a_rmBranchErr() {
i_prelude1();
gitletCommand(new String[]{"branch", "other"}, "");
gitletCommand(new String[]{"switch", "other"}, "");
writeFile(WUG, "f.txt");
gitletCommand(new String[]{"add", "f.txt"}, "");
gitletCommand(new String[]{"commit", "File f.txt"}, "");
gitletCommand(new String[]{"rm-branch", "other"}, "Cannot remove the current branch.");
assertFileExists("f.txt");
gitletCommand(new String[]{"rm-branch", "foo"}, "A branch with that name does not exist.");