-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.java
1573 lines (1490 loc) · 68.5 KB
/
Main.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 java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
/** Driver class for Gitlet, the tiny stupid version-control system.
* @author Raman Varma
*/
public class Main {
/** Gitlet hidden directory. */
static final File REPO = new File(".gitlet");
/** Staging area directory containing an addition and removal stage. */
static final File STAGING = new File(REPO + "/staging");
/** Addition stage directory. */
static final File STAGING_ADD = new File(STAGING + "/addition");
/** Removal stage directory. */
static final File STAGING_REMOVE = new File(STAGING + "/removal");
/** Commit directory containing all commits (immutable). */
static final File COMMITS = new File(REPO + "/commits");
/** A file that points to the head of the current branch. */
static final File HEAD = new File(REPO + "/HEAD");
/** Branches directory containing all branches stored as files. */
static final File BRANCHES = new File(REPO + "/branches");
/** Files directory containing all committed files. */
static final File FILES = new File(REPO + "/files");
/** Remotes directory containing a HashMap of all remote name to directory
* mappings.*/
static final File REMOTES_MAP = new File(REPO + "/remotes");
/** The default length of a full SHA1 ID. */
static final int FULL_SHA1_LENGTH = 40;
/** Usage: java gitlet.Main ARGS, where ARGS contains
* <COMMAND> <OPERAND> .... */
public static void main(String... args) throws IOException {
initialChecks(args);
String command = args[0];
switch (command) {
case "init":
checkInit(args);
break;
case "add":
checkAdd(args);
break;
case "commit":
checkCommit(args);
break;
case "rm":
checkRm(args);
break;
case "log":
checkLog(args);
break;
case "global-log":
checkGlobalLog(args);
break;
case "find":
checkFind(args);
break;
case "status":
checkStatus(args);
break;
case "checkout":
checkCheckout(args);
break;
case "branch":
checkBranch(args);
break;
case "rm-branch":
checkRmBranch(args);
break;
case "reset":
checkReset(args);
break;
case "merge":
checkMerge(args);
break;
default:
commandDoesNotExist();
break;
}
}
/** Checks for no command error case and not in an initialized
* gitlet directory error case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void initialChecks(String... args) {
if (args.length == 0) {
noCommand();
}
HashSet<String> commands = requireGitletDir();
String command = args[0];
if (!command.equals("init") && commands.contains(command)
&& !REPO.exists()) {
noGitletDir();
}
}
/** Checks init command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkInit(String... args) throws IOException {
if (args.length != 1) {
incorrectOperands();
}
init();
}
/** Checks add command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkAdd(String... args) {
if (args.length != 2) {
incorrectOperands();
}
add(args[1]);
}
/** Checks commit command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkCommit(String... args) throws IOException {
if (args.length != 2) {
incorrectOperands();
} else if (args[1].equals("")) {
noCommitMessage();
} else {
commit(args[1], null);
}
}
/** Checks rm command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkRm(String... args) {
if (args.length != 2) {
incorrectOperands();
}
boolean isStaged = isStaged(args[1]);
boolean isTracked = isTracked(args[1]);
if (isStaged && isTracked) {
rm(args[1], true, true);
} else if (isStaged) {
rm(args[1], true, false);
} else if (isTracked) {
rm(args[1], false, true);
} else {
noReasonToRm();
}
}
/** Checks log command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkLog(String... args) {
if (args.length != 1) {
incorrectOperands();
}
log();
}
/** Checks global-log command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkGlobalLog(String... args) {
if (args.length != 1) {
incorrectOperands();
}
globalLog();
}
/** Checks find command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkFind(String... args) {
if (args.length != 2) {
incorrectOperands();
}
find(args[1]);
}
/** Checks status command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkStatus(String... args) {
if (args.length != 1) {
incorrectOperands();
}
status();
}
/** Checks checkout command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkCheckout(String... args) {
if (args.length != 2 && args.length != 3 && args.length != 4) {
incorrectOperands();
}
if (args.length == 2) {
checkout3(args[1]);
} else if (args[1].equals("--")) {
checkout1(args[2]);
} else if (args[2].equals("--")) {
checkout2(args[1], args[3]);
} else {
incorrectOperands();
}
}
/** Checks branch command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkBranch(String... args) {
if (args.length != 2) {
incorrectOperands();
}
branch(args[1]);
}
/** Checks rm-branch command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkRmBranch(String... args) {
if (args.length != 2) {
incorrectOperands();
}
rmBranch(args[1]);
}
/** Checks reset command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkReset(String... args) {
if (args.length != 2) {
incorrectOperands();
}
reset(args[1]);
}
/** Checks merge command input case.
* @param args - ARGS contains <COMMAND> <OPERAND> .... */
public static void checkMerge(String... args) throws IOException {
if (args.length != 2) {
incorrectOperands();
}
merge(args[1]);
}
/** @return - Returns a HashSet of all the gitlet commands that require
* an initialized gitlet directory (all commands but init). */
public static HashSet<String> requireGitletDir() {
return new HashSet<>(Arrays.asList("add", "commit", "rm",
"log", "global-log", "find", "status", "checkout", "branch",
"rm-branch", "reset", "merge"));
}
/** Determines if a file with name fileName is staged for addition.
* @param fileName - The name of the file.
* @return - Whether file with name fileName is staged. */
public static boolean isStaged(String fileName) {
boolean isStaged = false;
File[] stagedForAdd = STAGING_ADD.listFiles();
if (stagedForAdd != null) {
for (File f : stagedForAdd) {
if (f.getName().equals(fileName)) {
isStaged = true;
break;
}
}
}
return isStaged;
}
/** Determines if a file with name fileName is tracked in the
* current commit (the head commit of the current branch).
* @param fileName - The name of the file.
* @return - Whether file with name fileName is tracked. */
public static boolean isTracked(String fileName) {
boolean isTracked = false;
Commit headCommit = getHeadCommit();
HashMap<String, String> trackedFiles = headCommit.getTrackedFiles();
if (trackedFiles != null && trackedFiles.containsKey(fileName)) {
isTracked = true;
}
return isTracked;
}
/** No command entered error case. */
public static void noCommand() {
System.out.println("Please enter a command.");
System.exit(0);
}
/** No commit message error case for commit command. */
public static void noCommitMessage() {
System.out.println("Please enter a commit message.");
System.exit(0);
}
/** Command requiring initialized gitlet directory error case. */
public static void noGitletDir() {
System.out.println("Not in an initialized Gitlet directory.");
System.exit(0);
}
/** Incorrect operands error case. */
public static void incorrectOperands() {
System.out.println("Incorrect operands.");
System.exit(0);
}
/** No reason to remove file error case for rm command. */
public static void noReasonToRm() {
System.out.println("No reason to remove the file.");
System.exit(0);
}
/** Inputted command does not exist error case. */
public static void commandDoesNotExist() {
System.out.println("No command with that name exists.");
System.exit(0);
}
/** Creates a new Gitlet version-control system in the current directory.
* This system will automatically start with one commit: a commit that
* contains no files and has the commit message "initial commit". It will
* have a single branch: master, which initially points to this initial
* commit, and master will be the current branch. The timestamp for this
* initial commit will be 00:00:00 UTC, Thursday, 1 January 1970. */
public static void init() throws IOException {
if (REPO.exists()) {
System.out.println("A Gitlet version-control system "
+ "already exists in the current directory.");
System.exit(0);
} else {
REPO.mkdir();
STAGING.mkdir();
STAGING_ADD.mkdir();
STAGING_REMOVE.mkdir();
COMMITS.mkdir();
BRANCHES.mkdir();
HEAD.createNewFile();
FILES.mkdir();
REMOTES_MAP.mkdir();
Date initialDate = new Date(0);
String initialMessage = "initial commit";
String parent = null;
HashMap<String, String> trackedFiles = null;
String mergedInParent = null;
String cSHA1 = Utils.sha1(initialMessage, initialDate.toString());
Commit initial = new Commit(parent, initialMessage, initialDate,
trackedFiles, mergedInParent, cSHA1);
File initialFile = new File(COMMITS + "/" + cSHA1);
Utils.writeObject(initialFile, initial);
String pathToMaster = BRANCHES + "/master";
File master = new File(pathToMaster);
Utils.writeContents(master, cSHA1);
File head = new File(String.valueOf(HEAD));
Utils.writeContents(head, pathToMaster);
}
}
/** Adds a copy of the file as it currently exists to the staging area.
* Staging an already-staged file overwrites the previous entry in the
* staging area with the new contents. If the current working version
* of the file is identical to the version in the current commit, do not
* stage it to be added, and remove it from the staging area if it is
* already there. The file will no longer be staged for removal, if it
* was at the time of the command.
* @param fileName - The name of the file to add. */
public static void add(String fileName) {
File addFile = new File(fileName);
if (!addFile.exists()) {
System.out.println("File does not exist.");
System.exit(0);
} else {
byte[] addFileContents = Utils.readContents(addFile);
String addFileSHA1 = Utils.sha1((Object) addFileContents);
File copyFile = new File(STAGING_ADD + "/" + fileName);
Commit headCommit = getHeadCommit();
HashMap<String, String> headTrackedFiles =
headCommit.getTrackedFiles();
if (headTrackedFiles != null
&& headTrackedFiles.containsKey(fileName)
&& headTrackedFiles.get(fileName).equals(addFileSHA1)) {
if (copyFile.exists()) {
copyFile.delete();
}
} else {
Utils.writeContents(copyFile, (Object) addFileContents);
}
File stagedForRemoval = new File(STAGING_REMOVE + "/" + fileName);
if (stagedForRemoval.exists()) {
stagedForRemoval.delete();
}
}
}
/** Saves a snapshot of tracked files in the current commit and staging
* area so they can be restored at a later time, creating a new commit.
* By default, each commit's snapshot of files will be exactly the same
* as its parent commit's snapshot of files; it will keep versions of
* files exactly as they are, and not update them. A commit will only
* update the contents of files it is tracking that have been staged for
* addition at the time of commit, in which case the commit will now
* include the version of the file that was staged instead of the version
* it got from its parent. A commit will save and start tracking any
* files that were staged for addition but weren't tracked by its parent.
* Files tracked in the current commit may be untracked in the new commit
* as a result being staged for removal by the rm command.
* @param message - The commit's log message.
* @param mergedInParent - The merged-in parent of the commit. Null if
* the commit does not have a merged-in parent. */
public static void commit(String message, String mergedInParent)
throws IOException {
Date timestamp = new Date();
if (Objects.requireNonNull(STAGING_ADD.listFiles()).length == 0
&& Objects.requireNonNull(STAGING_REMOVE.listFiles()).length == 0) {
noChanges();
} else {
Commit headCommit = getHeadCommit();
HashMap<String, String> trackedFilesHead = headCommit.getTrackedFiles();
HashMap<String, String> clonedTrackedFiles = new HashMap<>();
String parentSHA1;
if (headCommit.getTrackedFiles() != null) {
parentSHA1 = Utils.sha1(headCommit.getParent(),
headCommit.getMessage(),
headCommit.getTimestamp().toString(),
convertMapToByte(headCommit.getTrackedFiles()));
} else {
parentSHA1 = Utils.sha1(headCommit.getMessage(),
headCommit.getTimestamp().toString());
}
if (trackedFilesHead != null) {
for (String fileName : trackedFilesHead.keySet()) {
String fSHA1 = trackedFilesHead.get(fileName);
clonedTrackedFiles.put(fileName, fSHA1);
}
}
File[] stagedForAdd = STAGING_ADD.listFiles();
if (stagedForAdd != null) {
for (File add : stagedForAdd) {
String fileName = add.getName();
byte[] addsContent = Utils.readContents(add);
String fSHA1 = Utils.sha1((Object) addsContent);
if (clonedTrackedFiles.containsKey(fileName)) {
clonedTrackedFiles.replace(fileName, fSHA1);
} else {
clonedTrackedFiles.put(fileName, fSHA1);
}
}
}
File[] stagedForRm = STAGING_REMOVE.listFiles();
if (stagedForRm != null) {
for (File rm: stagedForRm) {
String fileName = rm.getName();
clonedTrackedFiles.remove(fileName);
}
}
String commitSHA1 = Utils.sha1(parentSHA1, message,
timestamp.toString(), convertMapToByte(clonedTrackedFiles));
Commit commit = new Commit(parentSHA1, message, timestamp,
clonedTrackedFiles, mergedInParent, commitSHA1);
File commitFile = new File(COMMITS + "/" + commitSHA1);
Utils.writeObject(commitFile, commit);
File[] currFiles = FILES.listFiles();
for (String fileName: clonedTrackedFiles.keySet()) {
String fileNameSHA1 = clonedTrackedFiles.get(fileName);
boolean alreadyInFiles = false;
if (currFiles != null) {
for (File f : currFiles) {
if (fileNameSHA1.equals(f.getName())) {
alreadyInFiles = true;
break;
}
}
if (!alreadyInFiles) {
File addNewCommitFile =
new File(FILES + "/" + fileNameSHA1);
if (stagedForAdd != null) {
for (File f : stagedForAdd) {
if (f.getName().equals(fileName)) {
byte[] fileNameContents =
Utils.readContents(f);
Utils.writeContents(addNewCommitFile,
(Object) fileNameContents);
}
}
}
}
} else {
File addNewCommitFile =
new File(FILES + "/" + fileNameSHA1);
if (stagedForAdd != null) {
for (File f : stagedForAdd) {
if (f.getName().equals(fileName)) {
byte[] fileNameContents = Utils.readContents(f);
Utils.writeContents(addNewCommitFile,
(Object) fileNameContents);
}
}
}
}
}
if (stagedForAdd != null) {
for (File fileInAdd : stagedForAdd) {
fileInAdd.delete();
}
}
if (stagedForRm != null) {
for (File fileInRm : stagedForRm) {
fileInRm.delete();
}
}
String pathToHead = Utils.readContentsAsString(HEAD);
File currHead = new File(pathToHead);
Utils.writeContents(currHead, commitSHA1);
}
}
/** No changes added to commit error case. */
public static void noChanges() {
System.out.println("No changes added to the commit.");
System.exit(0);
}
/** Unstage the file if it is currently staged for addition. If the
* file is tracked in the current commit, stage it for removal and
* remove the file from the working directory if the user has not
* already done so. Do not remove it unless it is tracked in the
* current commit.
* @param fileName - The name of the file to remove.
* @param isStaged - Whether the file is staged.
* @param isTracked - Whether the file is tracked. */
public static void rm(String fileName, boolean isStaged, boolean isTracked) {
if (isStaged) {
File rmStaged = new File(STAGING_ADD + "/" + fileName);
rmStaged.delete();
}
if (isTracked) {
String fileSHA1 = getHeadCommit().getTrackedFiles().get(fileName);
File rmFile = new File(FILES + "/" + fileSHA1);
byte[] fileToRmContents = Utils.readContents(rmFile);
File stageForRm = new File(STAGING_REMOVE + "/" + fileName);
Utils.writeContents(stageForRm, (Object) fileToRmContents);
File removedFile = new File(fileName);
if (removedFile.exists()) {
Utils.restrictedDelete(removedFile);
}
}
}
/** Starting at the current head commit, display information about each
* commit backwards along the commit tree until the initial commit,
* following the first parent commit links, ignoring any second parents
* found in merge commits. For every node in this history, the
* information it should display is the commit id, the time the commit
* was made, and the commit message. */
public static void log() {
Commit c = getHeadCommit();
while (c != null) {
displayInfo(c, c.getMergedInParent() != null);
String parentSHA1 = c.getParent();
File parentCommitFile = new File(COMMITS + "/" + parentSHA1);
if (parentCommitFile.exists()) {
c = Utils.readObject(parentCommitFile, Commit.class);
} else {
c = null;
}
}
}
/** Like log, except displays information about all commits ever made.
* The order of the commits does not matter. */
public static void globalLog() {
File commitsDir = new File(COMMITS.toString());
List<String> allCommits = Utils.plainFilenamesIn(commitsDir);
if (allCommits != null) {
for (String commitSHA1 : allCommits) {
File commitFile = new File(COMMITS + "/" + commitSHA1);
Commit c = Utils.readObject(commitFile, Commit.class);
displayInfo(c, c.getMergedInParent() != null);
}
}
}
/** Displays the following information about commit C: the commit id,
* the time the commit was made, and the commit message. If the commit
* has a merged-in parent, also display the first 7 characters of its
* two parents' IDs on the second line.
* @param c - The commit object whose information is displayed.
* @param mergedParentExists - Whether the commit has a merged-in
* parent. */
public static void displayInfo(Commit c, boolean mergedParentExists) {
System.out.println("===");
String commitSHA1;
if (c.getTrackedFiles() != null) {
commitSHA1 = Utils.sha1(c.getParent(), c.getMessage(),
c.getTimestamp().toString(),
convertMapToByte(c.getTrackedFiles()));
} else {
commitSHA1 = Utils.sha1(c.getMessage(),
c.getTimestamp().toString());
}
System.out.println("commit " + commitSHA1);
if (mergedParentExists) {
String firstParent = c.getParent().subSequence(0, 7).toString();
String mergedInParent = c.getMergedInParent().subSequence(0, 7).toString();
System.out.println("Merge: " + firstParent + " " + mergedInParent);
}
Date timestamp = c.getTimestamp();
SimpleDateFormat formatTimestamp =
new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy Z");
String requiredFormat = formatTimestamp.format(timestamp);
System.out.println("Date: " + requiredFormat);
System.out.println(c.getMessage() + System.lineSeparator());
}
/** Prints out the IDs of all commits that have the given commit
* message, one per line. If there are multiple such commits,
* it prints the ids out on separate lines.
* @param commitMessage - The given commit message. */
public static void find(String commitMessage) {
File commitsDir = new File(COMMITS.toString());
File[] allCommitFiles = commitsDir.listFiles();
boolean commitExists = false;
if (allCommitFiles != null) {
for (File f : allCommitFiles) {
Commit c = Utils.readObject(f, Commit.class);
String cCommitMessage = c.getMessage();
if (commitMessage.equals(cCommitMessage)) {
if (!commitExists) {
commitExists = true;
}
System.out.println(f.getName());
}
}
if (!commitExists) {
System.out.println("Found no commit with that message.");
System.exit(0);
}
} else {
System.out.println("Found no commit with that message.");
System.exit(0);
}
}
/** Displays what branches currently exist, and marks the current
* branch with a *. Also displays what files have been staged for
* addition or removal. */
public static void status() {
List<String> stagedFiles = Utils.plainFilenamesIn(STAGING_ADD);
List<String> removedFiles = Utils.plainFilenamesIn(STAGING_REMOVE);
List<String> untrackedFiles = new ArrayList<>();
List<String> modifiedNotStaged = new ArrayList<>();
Commit headCommit = getHeadCommit();
HashMap<String, String> trackedFilesHead
= headCommit.getTrackedFiles();
Set<String> fileNamesHead = null;
if (trackedFilesHead != null) {
fileNamesHead = trackedFilesHead.keySet();
}
File cwd = new File(".");
File[] workingFiles = cwd.listFiles();
if (workingFiles != null) {
for (File f : workingFiles) {
if (f.isFile()) {
String fileName = f.getName();
boolean notStaged = stagedFiles != null
&& !stagedFiles.contains(fileName);
boolean emptyOrNotInHead = fileNamesHead == null
|| !fileNamesHead.contains(fileName);
boolean fileRemoved = removedFiles != null
&& removedFiles.contains(fileName);
boolean emptyOrNotStaged = stagedFiles == null
|| !stagedFiles.contains(fileName);
if ((notStaged && emptyOrNotInHead) ||
(fileRemoved && emptyOrNotStaged)) {
untrackedFiles.add(fileName);
}
byte[] fsContents = Utils.readContents(f);
String fSHA1 = Utils.sha1((Object) fsContents);
boolean notInHead = fileNamesHead != null
&& fileNamesHead.contains(fileName);
if (notInHead && emptyOrNotStaged) {
String headFileSHA1 = trackedFilesHead.get(fileName);
if (!fSHA1.equals(headFileSHA1)) {
modifiedNotStaged.add(fileName + " (modified)");
}
}
if (!modifiedNotStaged.contains(fileName) && stagedFiles != null
&& stagedFiles.contains(fileName)) {
File stagedFile = new File(STAGING_ADD + "/" + fileName);
byte[] stagedFileContents = Utils.readContents(stagedFile);
String stagedFileSHA1 = Utils.sha1((Object) stagedFileContents);
if (!fSHA1.equals(stagedFileSHA1)) {
modifiedNotStaged.add(fileName + " (modified)");
}
}
}
}
}
List<String> allBranches = Utils.plainFilenamesIn(BRANCHES);
String currentBranchName = getCurrentBranch();
if (allBranches != null) {
for (int i = 0; i < allBranches.size(); i += 1) {
if (allBranches.get(i).equals(currentBranchName)) {
allBranches.set(i, "*" + currentBranchName);
break;
}
}
}
if (workingFiles != null && stagedFiles != null) {
List<String> stagedFilesCopy = new ArrayList<>(stagedFiles);
for (File f : workingFiles) {
String fileName = f.getName();
stagedFilesCopy.remove(fileName);
}
for (String stagedFileName : stagedFilesCopy) {
if (!modifiedNotStaged.contains(stagedFileName)) {
modifiedNotStaged.add(stagedFileName + " (deleted)");
}
}
} else if (stagedFiles != null) {
for (String stagedFileName: stagedFiles) {
modifiedNotStaged.add(stagedFileName + " (deleted)");
}
}
if (fileNamesHead != null) {
if (workingFiles != null) {
for (File f : workingFiles) {
fileNamesHead.remove(f.getName());
}
}
for (String fileNameHead : fileNamesHead) {
if (removedFiles == null
|| !removedFiles.contains(fileNameHead)) {
modifiedNotStaged.add(fileNameHead + " (deleted)");
}
}
}
Collections.sort(untrackedFiles);
Collections.sort(modifiedNotStaged);
displayStatus(allBranches, stagedFiles, removedFiles,
untrackedFiles, modifiedNotStaged);
}
/** Displays information about branches collected by the STATUS method.
* @param allBranches - A list of all of the branches.
* @param stagedFiles - A list of all of the files staged for addition.
* @param removedFiles - A list of all of the files staged for removal.
* @param untrackedFiles - A list of all of the untracked files.
* @param modifiedNotStaged - A list of all of the files that have been
* modified but not staged for commit. */
public static void displayStatus(List<String> allBranches,
List<String> stagedFiles,
List<String> removedFiles,
List<String> untrackedFiles,
List<String> modifiedNotStaged) {
System.out.println("=== Branches ===");
displaySection(allBranches);
System.out.println("=== Staged Files ===");
displaySection(stagedFiles);
System.out.println("=== Removed Files ===");
displaySection(removedFiles);
System.out.println("=== Modifications Not Staged For Commit ===");
displaySection(modifiedNotStaged);
System.out.println("=== Untracked Files ===");
displaySection(untrackedFiles);
}
/** Prints out each individual section of the STATUS method. Each section
* is separated by a new line.
* @param section - The section of status to display. */
public static void displaySection(List<String> section) {
for (String s : section) {
System.out.println(s);
}
System.out.print(System.lineSeparator());
}
/** File does not exist error case. */
public static void noFile() {
System.out.println("File does not exist in that commit.");
System.exit(0);
}
/** Takes the version of the file as it exists in the head commit, the
* front of the current branch, and puts it in the working directory,
* overwriting the version of the file that's already there if there is
* one. The new version of the file is not staged.
* @param fileName - The name of the file to checkout. */
public static void checkout1(String fileName) {
Commit headCommit = getHeadCommit();
HashMap<String, String> trackedFiles = headCommit.getTrackedFiles();
if (trackedFiles.containsKey(fileName)) {
String fileNameSHA1 = trackedFiles.get(fileName);
File[] committedFiles = FILES.listFiles();
if (committedFiles != null) {
for (File f : committedFiles) {
if (fileNameSHA1.equals(f.getName())) {
byte[] fsContents = Utils.readContents(f);
File addToCWD = new File(fileName);
Utils.writeContents(addToCWD, (Object) fsContents);
}
}
}
} else {
noFile();
}
}
/** Commit does not exist error case. */
public static void noCommit() {
System.out.println("No commit with that id exists.");
System.exit(0);
}
/** Takes the version of the file as it exists in the commit with the
* given id, and puts it in the working directory, overwriting the
* version of the file that's already there if there is one. The new
* version of the file is not staged.
* @param fileName - The name of the file to checkout.
* @param commitID - The ID of the commit from which the file is taken. */
public static void checkout2(String commitID, String fileName) {
File[] allCommits = COMMITS.listFiles();
if (allCommits != null) {
boolean noCommitWithID = true;
for (File commitFile : allCommits) {
Commit commit = Utils.readObject(commitFile, Commit.class);
String commitSHA1;
if (commit.getTrackedFiles() != null) {
commitSHA1 = Utils.sha1(commit.getParent(),
commit.getMessage(),
commit.getTimestamp().toString(),
convertMapToByte(commit.getTrackedFiles()));
} else {
commitSHA1 = Utils.sha1(commit.getMessage(),
commit.getTimestamp().toString());
}
String commitSHA1Shorten = "";
if (commitID.length() < FULL_SHA1_LENGTH) {
commitSHA1Shorten
= (String) commitSHA1.subSequence(0, commitID.length());
}
boolean matchesShortenedID = !commitSHA1Shorten.isEmpty()
&& commitSHA1Shorten.equals(commitID);
if (commitSHA1.equals(commitID) || matchesShortenedID) {
noCommitWithID = false;
HashMap<String, String> trackedFiles = commit.getTrackedFiles();
if (trackedFiles.containsKey(fileName)) {
String fileNameSHA1 = trackedFiles.get(fileName);
File[] committedFiles = FILES.listFiles();
if (committedFiles != null) {
for (File f : committedFiles) {
if (fileNameSHA1.equals(f.getName())) {
byte[] fsContents = Utils.readContents(f);
File addToCWD = new File(fileName);
Utils.writeContents(addToCWD, (Object) fsContents);
}
}
}
} else {
noFile();
}
}
}
if (noCommitWithID) {
noCommit();
}
} else {
noCommit();
}
}
/** Takes all files in the commit at the head of the given branch, and
* puts them in the working directory, overwriting the versions of the
* files that are already there if they exist. Also, at the end of this
* command, the given branch will now be considered the current branch
* (HEAD). Any files that are tracked in the current branch but are not
* present in the checked-out branch are deleted. The staging area is
* cleared, unless the checked-out branch is the current branch.
* @param branchName - The name of the branch being checked-out. */
public static void checkout3(String branchName) {
handleErrorsCheckout3(branchName);
String pathToCheckedOutBranch = BRANCHES + "/" + branchName;
File checkedOutBranch = new File(pathToCheckedOutBranch);
String checkedOutCommitSHA1
= Utils.readContentsAsString(checkedOutBranch);
File[] allCommits = COMMITS.listFiles();
Commit checkedOutCommit = null;
if (allCommits != null) {
for (File f : allCommits) {
if (checkedOutCommitSHA1.equals(f.getName())) {
checkedOutCommit = Utils.readObject(f, Commit.class);
break;
}
}
Commit headCommit = getHeadCommit();
HashMap<String, String> trackedFilesHead
= headCommit.getTrackedFiles();
Set<String> headFiles;
if (trackedFilesHead == null) {
headFiles = new HashSet<>();
} else {
headFiles = trackedFilesHead.keySet();
}
if (checkedOutCommit != null) {
HashMap<String, String> trackedFilesCheckedOut
= checkedOutCommit.getTrackedFiles();
Set<String> checkedOutFiles;
if (trackedFilesCheckedOut != null) {
checkedOutFiles = trackedFilesCheckedOut.keySet();
} else {
checkedOutFiles = new HashSet<>();
}
for (String fileName : checkedOutFiles) {
String fileNameSHA1 = trackedFilesCheckedOut.get(fileName);
File f = new File(FILES + "/" + fileNameSHA1);
byte[] fsContents = Utils.readContents(f);
File fInCWD = new File(fileName);
Utils.writeContents(fInCWD, fsContents);
}
for (String fileName : headFiles) {
if (!checkedOutFiles.contains(fileName)) {
File f = new File(fileName);
f.delete();
}
}
} else {
for (String fileName : headFiles) {
File f = new File(fileName);
f.delete();
}
}
}
clearStagingArea();
Utils.writeContents(HEAD, pathToCheckedOutBranch);
}
/** Clear the staging area (addition stage and removal stage). */
public static void clearStagingArea() {
File[] stagedForAdd = STAGING_ADD.listFiles();
if (stagedForAdd != null) {
for (File f : stagedForAdd) {
f.delete();
}
}
File[] stagedForRemoval = STAGING_REMOVE.listFiles();
if (stagedForRemoval != null) {
for (File f : stagedForRemoval) {
f.delete();
}
}
}
/** Handles the following error cases for CHECKOUT3: If no branch with
* that name exists, print "No such branch exists". If that branch is
* the current branch, print "No need to checkout the current branch."
* If a working file is untracked in the current branch and would be
* overwritten by the checkout, print "There is an untracked file in
* the way; delete it, or add and commit it first." and exit.
* @param branchName - The name of the branch. */
public static void handleErrorsCheckout3(String branchName) {
File branchesDir = new File(BRANCHES.toString());
List<String> allBranchNames = Utils.plainFilenamesIn(branchesDir);
if (allBranchNames != null && !allBranchNames.contains(branchName)) {
System.out.println("No such branch exists.");
System.exit(0);
}
File head = new File(HEAD.toString());
String pathToBranch = Utils.readContentsAsString(head);
File currBranch = new File(pathToBranch);
if (branchName.equals(currBranch.getName())) {
System.out.println("No need to checkout the current branch.");
System.exit(0);
}
File checkedOutBranch = new File(BRANCHES + "/" + branchName);
String checkedOutCommitSHA1 = Utils.readContentsAsString(checkedOutBranch);
File checkedOutCommitFile
= new File(COMMITS + "/" + checkedOutCommitSHA1);
Commit checkedOutCommit
= Utils.readObject(checkedOutCommitFile, Commit.class);
if (checkedOutCommit != null) {
Commit headCommit = getHeadCommit();
HashMap<String, String> trackedFilesHead = headCommit.getTrackedFiles();
HashMap<String, String> trackedFilesCheckedOut
= checkedOutCommit.getTrackedFiles();
File cwd = new File(".");
File[] workingFiles = cwd.listFiles();
if (workingFiles != null) {
for (File f : workingFiles) {
String fileName = f.getName();
boolean notInHead = trackedFilesHead == null
|| !trackedFilesHead.containsKey(fileName);
boolean inCheckedOut = trackedFilesCheckedOut != null
&& trackedFilesCheckedOut.containsKey(fileName);