forked from fishsticks89/hw-topics-git-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGit.java
More file actions
409 lines (356 loc) · 14.2 KB
/
Git.java
File metadata and controls
409 lines (356 loc) · 14.2 KB
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
/**
* I have neither given nor received unauthorized aid on this assignment.
* Thank you to .
* Majestic King Dylan
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.security.NoSuchAlgorithmException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.io.IOException;
import util.Terminate;
public class Git implements GitInterface{
//initializes a repository
public Git(){
initGit();
}
// Adds a Blob in `objects` to the `index` file
private static void addBlobToIndex(String path, String sha) {
var indexFile = new DirectoryFile("./git/index");
var line = new DirectoryLine(false, sha, path);
indexFile.addIfNotExist(line);
}
// Adds the blob to the tree, then rehashes it
// and renames the tree to it's new hash
private static void registerBlob(String blobPath, String blobHash) {
addBlobToIndex(blobPath, blobHash);
var index = getIndex();
var treePath = DirUtil.up(blobPath);
System.out.println("treepath: \"" + treePath +"\"");
if (treePath.equals("")) // don't need a tree if blob is in root
return;
var treeIndex = index.lineWithNameAndType(treePath, false);
String treeSha;
if (treeIndex == -1) {
// create new tree
File newTree = new File("./git/objects/new_tree");
try {
if (newTree.exists())
newTree.delete();
newTree.createNewFile();
} catch (Exception e) {
Terminate.exception(e);
}
treeSha = "new_tree";
} else {
var treeLine = index.getLine(treeIndex);
treeSha = treeLine.hash;
}
DirectoryFile tree = new DirectoryFile("./git/objects/" + treeSha);
int existingBlobLineIndex = tree.lineWithHash(blobHash);
var blobLine = new DirectoryLine(false, blobHash, DirUtil.last(blobPath));
if (existingBlobLineIndex != -1) {
tree.setLine(existingBlobLineIndex, blobLine);
} else {
tree.addIfNotExist(blobLine);
}
registerTree(tree.getFile(), treePath);
}
// Renames the tree to it's new hash wherever it is referenced
// Does the same for all the trees it changes
private static void registerTree(File tree, String treePath) {
var index = getIndex();
// move the tree to it's new hash
var newHash = Sha.shaFile(tree.getAbsolutePath());
tree.renameTo(new File("./git/objects/" + newHash));
// make sure the tree is inserted with the right hash in index
var treeLineIndexInIndex = index.lineWithNameAndType(treePath, false);
var idealTreeLineInIndex = new DirectoryLine(true, newHash, treePath);
if (treeLineIndexInIndex == -1) {
index.addIfNotExist(idealTreeLineInIndex);
} else {
index.setLine(treeLineIndexInIndex, idealTreeLineInIndex);
}
// if there's no parent tree, the tree is fully registered in just index
if (DirUtil.up(treePath).equals(""))
return; // no parent tree
// find parent tree
var parentTreeLine = index.lineWithNameAndType(DirUtil.up(treePath), false);
String parentTreeSha;
if (parentTreeLine == -1) {
// create new tree
File newTree = new File("./git/objects/new_tree");
try {
if (newTree.exists())
newTree.delete();
newTree.createNewFile();
} catch (Exception e) {
Terminate.exception(e);
}
parentTreeSha = "new_tree";
} else {
var treeLine = index.getLine(parentTreeLine);
parentTreeSha = treeLine.hash;
}
DirectoryFile parentTree = new DirectoryFile("./git/objects/" + parentTreeSha);
var lineInParent = parentTree.lineWithNameAndType(treePath, false);
var idealLineInParent = new DirectoryLine(true, newHash, DirUtil.last(treePath));
if (lineInParent == -1) {
parentTree.addIfNotExist(idealLineInParent);
} else {
parentTree.setLine(lineInParent, idealLineInParent);
}
registerTree(parentTree.getFile(), DirUtil.up(treePath));
}
//adds a file to git
//filePath denotes path of file to store
public static void addBlob (String filePath){
addBlob(new File(filePath));
}
// Adds a file to Git
public static void addBlob(File inFile) {
if (!inFile.isFile())
throw new Error("Blob does not exist");
File storingFile = new File("./git/objects/" + Sha.shaFile(inFile.getPath()));
storingFile.delete();
registerBlob(inFile.getPath(), storingFile.getName());
try {
storingFile.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(storingFile, true));
BufferedReader br = new BufferedReader(new FileReader(inFile));
while (br.ready()) {
bw.write(br.readLine());
bw.newLine();
}
br.close();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Adds all blobs in a directory
// dirPath is path of directory to add
public static void addDir(String dirPath) throws NoSuchAlgorithmException {
addDir(new File(dirPath));
}
// Adds all the blobs in a directory
public static void addDir(File dir) throws NoSuchAlgorithmException {
if (!dir.exists() || !dir.isDirectory()) {
throw new Error("This is not an existing directory");
}
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
addDir(file.getPath()); // todo: is this a relative path
} else {
addBlob(file.getPath());
}
}
}
//non-static stage reference
public void stage (String filePath){
stageStatic(filePath);
}
//static stage reference
//filePath is path of file to stage
public static void stageStatic (String filePath){
File file = new File(filePath);
if (!file.exists())
throw new Error("File does not exist");
if (file.isDirectory()){
try {
addDir(file);
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
else if (file.isFile())
addBlob(file);
}
public String commit (String commitMesage, String authorName){
return commitStatic (commitMesage, authorName);
}
//creates a commit with no commitMessage
//records current system user and time automatically
public static String commit(){
return commitStatic("", System.getProperty("user.name"));
}
//creates a commit with message commitMessage
//records current system user and time automatically
public static String commit(String commitMessage){
return commitStatic(commitMessage, System.getProperty("user.name"));
}
public static String commitStatic (String commitMesage, String authorName){
try {
File commitTemp = File.createTempFile("currentCommit", null);
BufferedWriter writer = new BufferedWriter(new FileWriter(commitTemp));
// commit current tree;
writer.append("tree: " + commitStagedFiles());
writer.newLine();
// add parent to commit
String parentHash = Files.readString(new File("./git/HEAD").toPath());
writer.append("parent: " + parentHash);
writer.newLine();
// add author
writer.append("author: " + authorName);
writer.newLine();
// add date
writer.append("date: " + java.time.LocalDate.now());
writer.newLine();
// author message
writer.append("message: " + commitMesage);
writer.close();
String commitSHA = Sha.shaFile(commitTemp);
//copy temp commit into objects folder
File commitBlob = new File("./git/objects/" + commitSHA);
Files.copy(commitTemp.toPath(),commitBlob.toPath(), StandardCopyOption.REPLACE_EXISTING);
//write into head to track HEAD commit
BufferedWriter HEADwriter = new BufferedWriter(new FileWriter("./git/HEAD"));
HEADwriter.append(commitSHA);
HEADwriter.close();
return Sha.shaFile(commitTemp);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Creates a listing of all staged files in the index.
//Returns Sha of commited files listing
public static String commitStagedFiles (){
File index = new File("./git/index");
String filesSHA = Sha.shaFile(index);
File commitedFiles = new File("./git/objects/" + filesSHA);
try {
Files.copy(index.toPath(),commitedFiles.toPath(), StandardCopyOption.REPLACE_EXISTING);
//wipe the index 😈😈
FileWriter indexWiper = new FileWriter(index, false);
indexWiper.close();
}
catch (IOException e){
e.printStackTrace();
}
return filesSHA;
}
//Returns working directory to state at commit
public void checkout(String commitHash){
File commit = new File("git/objects/" + commitHash);
if (!commit.exists())
throw new Error("Commit not found");
clearWorkingRepository();
try {
// recursively checks out all commits infront of this one
BufferedReader reader = new BufferedReader(new FileReader(commit));
String treeSha = reader.readLine().substring(6);
File tree = new File("git/objects/" + treeSha);
String nextCommitSha = reader.readLine().substring(8);
if (!nextCommitSha.equals(""))
checkout(nextCommitSha);
reader.close();
//i know this implementation is terrible but its late and when i wake up
//ill think of a better solution and then not implement it :) sorry michael
//recreates file structure at this point (ONLY DIRS)
BufferedReader dirReader = new BufferedReader(new FileReader(tree));
while (dirReader.ready()){
String treeRead = dirReader.readLine();
boolean isFile = treeRead.substring(0,4).equals("blob");
String hash = treeRead.substring(5,45);
String filePath = treeRead.substring (46);
if(!isFile){
File dir = new File(filePath);
if(!dir.exists())
dir.mkdirs();
}
}
dirReader.close();
BufferedReader fileReader = new BufferedReader(new FileReader(tree));
while (fileReader.ready()){
String treeRead = fileReader.readLine();
boolean isFile = treeRead.substring(0,4).equals("blob");
String hash = treeRead.substring(5,45);
String filePath = treeRead.substring (46);
if(isFile){
File file = new File(filePath);
file.createNewFile();
File fileStuff = new File("git/objects/" + hash);
Files.copy(fileStuff.toPath(),file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
fileReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//cleans up working repository so commit can be checked out
private void clearWorkingRepository(){
try {
BufferedReader reader = new BufferedReader(new FileReader("git/HEAD"));
clearWorkingRepository(new File("git/objects/" + reader.readLine()));
reader.close();
} catch (Exception e) {e.printStackTrace();}
}
//deletes all files in commitLog, and any commits behind it
private void clearWorkingRepository(File commitLog){
try{
//recursively clears all commits
BufferedReader reader = new BufferedReader(new FileReader(commitLog));
String treeSha = reader.readLine().substring(6);
File tree = new File("git/objects/" + treeSha);
String nextCommitSha = reader.readLine().substring(8);
if (!nextCommitSha.equals(""))
clearWorkingRepository(new File("git/objects/" + nextCommitSha));
reader.close();
//clears the trees
BufferedReader treeReader = new BufferedReader(new FileReader(tree));
while (treeReader.ready()){
File delFile = new File(treeReader.readLine().substring(46));
if (delFile.exists()){
if(delFile.isDirectory())
DirUtil.deleteDir(delFile);
else
delFile.delete();
}
}
treeReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Creates repository
public static void initGit() {
File gitDir = new File("git");
File objDir = new File("./git/objects/");
File readMe = new File("README.md");
if (!gitDir.exists()) {
gitDir.mkdir();
}
if (!objDir.exists()) {
objDir.mkdir();
}
if (!readMe.exists()) {
try {
readMe.createNewFile();
}
catch (IOException e) {e.printStackTrace();}
}
getIndex();
getHEAD();
}
private static DirectoryFile getIndex() {
return new DirectoryFile("./git/index");
}
private static DirectoryFile getHEAD(){
return new DirectoryFile("./git/HEAD");
}
// Deletes `git` folder
public static void resetGit() {
File gitDir = new File("git/");
if (gitDir.exists()) {
DirUtil.deleteDir(gitDir);
gitDir.delete();
}
}
}