forked from pranachtarski/git-project-PRANAV
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGit.java
More file actions
465 lines (439 loc) · 16.5 KB
/
Git.java
File metadata and controls
465 lines (439 loc) · 16.5 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
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
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.zip.DeflaterOutputStream;
import java.nio.channels.*;;
public class Git implements GitInterface{
//if compressFiles is true, git will zip files before caching them
public static final boolean COMPRESS_FILES = false;
//test commit
public Git (){
initializeRepository();
}
//constructs a new repository
public void initializeRepository (){
File git = new File("./git/");
File objects = new File("./git/objects/");
File index = new File ("./git/index");
File head = new File("./git/HEAD");
//Checks if repository currently exists
if (git.exists() && objects.exists() && index.exists() && head.exists())
System.out.println ("Git Repository already exists");
else{
if (!git.exists())
git.mkdir();
if (!objects.exists())
objects.mkdir();
if (!index.exists()){
try {
index.createNewFile();}
catch (IOException e){
System.out.println ("Index creation failed");
e.printStackTrace();
}
}
if (!head.exists()) {
try {
head.createNewFile();}
catch (IOException e){
System.out.println ("Head creation failed");
e.printStackTrace();
}
}
}
}
//string filePath is part of blob to be hashed
//Uses HashFile for files
public void stage(String filePath) throws IOException{
File file = new File(filePath);
String filename = file.getName();
//checks if blob exits
if (!file.exists()){
throw new NullPointerException();
//im not sure that NullPointer is the right exception so feel free to swap it
}
if (file.isFile()){
HashFile(file, filename);
}
else{
String hashCode = Sha1Hash(file);
File file_objects = new File ("./git/objects/" + hashCode);
FileChannel source = null;
FileChannel destination = null;
File[] allFiles = file.listFiles();
for (File child : allFiles){
stage(child.getPath());
}
File file_combined = new File("./combined" + file.getName());
for (File child : allFiles){
try {
//write to objects directory
BufferedWriter output = new BufferedWriter(new FileWriter(file_combined));
output.write(child.getName());
output.newLine();
output.close();
}
catch (Exception e){
e.printStackTrace();
}
}
try {
source = new FileInputStream(file_combined).getChannel();
destination = new FileOutputStream(file_objects).getChannel();
destination.transferFrom(source, 0, source.size());
boolean bool1 = file_combined.delete();
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
//checks if entry exists already and deletes if so
List<String> indexLines = new ArrayList<>();
File indexFile = new File("./git/index");
try (BufferedReader reader = new BufferedReader(new FileReader(indexFile))) {
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(" ");
if (!parts[2].equals(file.getPath())) {
indexLines.add(line);
}
}
}
//write to index
try (BufferedWriter writer = new BufferedWriter(new FileWriter(indexFile))) {
for (String indexLine : indexLines) {
writer.write(indexLine);
writer.newLine();
}
writer.write("tree " + hashCode + " " + file.getPath());
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//string filePath is path of blob to be hashed
//returns true if blob hashes, returns false otherwise
public void HashFile (File file, String filename) throws FileNotFoundException, IOException{
//compresses the file
if (COMPRESS_FILES)
file = compress(file);
String hashCode = Sha1Hash(file);
//checks if file is already stored
File storedFile = new File("./git/objects/" + hashCode);
if (!storedFile.exists()){
try {
//write to objects directory
FileInputStream input = new FileInputStream(file);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(storedFile));
int data = input.read();
while (data != -1){
output.write(data);
data = input.read();
}
input.close();
output.close();
}
catch (Exception e){
e.printStackTrace();
}
}
//checks if entry exists already and deletes if so
List<String> indexLines = new ArrayList<>();
File indexFile = new File("./git/index");
try (BufferedReader reader = new BufferedReader(new FileReader(indexFile))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.contains(file.getPath())) {
indexLines.add(line);
}
}
}
// write to index
try (BufferedWriter writer = new BufferedWriter(new FileWriter(indexFile))) {
for (String indexLine : indexLines) {
writer.write(indexLine);
writer.newLine();
}
writer.write("blob " + hashCode + " " + file.getPath());
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
//returns hexadecimal SHA-1 hash for file
public String Sha1Hash (File file){
//implementation is copied from geeksforgeeks
//https://www.geeksforgeeks.org/sha-1-hash-in-java/
if (file.isFile()){
try {
MessageDigest digester = MessageDigest.getInstance("SHA-1");
byte[] sha1bytes = digester.digest(Files.readAllBytes(file.toPath()));
BigInteger sha1data = new BigInteger(1, sha1bytes);
String hash = sha1data.toString(16);
while (hash.length() < 40) {
hash = "0" + hash;
}
return hash;
}
catch (Exception e){
e.printStackTrace();
}
}
else if (file.isDirectory()) {
try {
File[] allFiles = file.listFiles();
if (allFiles == null) {
return null;
}
List<String> hashes = new ArrayList<>();
for (File child : allFiles) {
String childHash = Sha1Hash(child);
if (childHash != null) {
hashes.add(childHash);
}
}
Collections.sort(hashes);
MessageDigest digester = MessageDigest.getInstance("SHA-1");
for (String hash : hashes) {
digester.update(hash.getBytes());
}
byte[] sha1bytes = digester.digest();
BigInteger sha1data = new BigInteger(1, sha1bytes);
String hash = sha1data.toString(16);
while (hash.length() < 40) {
hash = "0" + hash;
}
return hash;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
//Compresses file
//If compression fails it will return input file
public File compress (File file){
try {
File compressedFile = File.createTempFile("compress", null);
FileInputStream input = new FileInputStream(file);
DeflaterOutputStream output = new DeflaterOutputStream(new FileOutputStream(compressedFile));
int data = input.read();
while (data != -1){
output.write(data);
data = input.read();
}
input.close();
output.close();
return compressedFile;
}
catch (IOException e){
e.printStackTrace();
}
return file;
}
//removes git folder
public void deleteRepository (){
File git = new File("git/");
if (git.exists()){
removeDirectory(git);
git.delete();
}
}
//recursively clears and deletes all files/directories in directory
public void removeDirectory (File directory){
if (!directory.isDirectory())
throw new IllegalArgumentException();
for (File childFile : directory.listFiles()){
if (childFile.isDirectory())
removeDirectory(childFile);
childFile.delete();
}
}
public String commit(String author, String message) {
//Gets the line from the head file
String parent;
try {
List<String> al = Files.readAllLines(Paths.get("./git/HEAD"));
if (al.isEmpty()) {
parent = "";
} else {
parent = al.get(0);
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Commit failed: HEAD file issue");
return null;
}
//creates the fileTree
List<String> fileTree = new ArrayList<String>();
try {
String parentFileTree="";
if (!parent.equals("")) {
for (String line : Files.readAllLines(Paths.get("./git/objects/" + parent))) {
if (line.startsWith("tree:")) {
parentFileTree = line.substring(6);
}
}
fileTree.addAll(0, Files.readAllLines(Paths.get("./git/objects/" + parentFileTree)));
}
fileTree.addAll(0, Files.readAllLines(Paths.get("./git/index")));
Collections.sort(fileTree);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Commit failed: index file issue");
return null;
}
//writes the contents of fileTree to the root tree file and gets its hash
File rootTree = new File("./git/objects/rootTree");
BufferedWriter output;
try {
output = new BufferedWriter(new FileWriter(rootTree));
for (int i = 0; i < fileTree.size(); i++) {
output.write(fileTree.get(i));
if (i < fileTree.size() - 1) {
output.write("\n");
}
}
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String rootTreeHash = Sha1Hash(rootTree);
//Adds the whole file tree for this commit to the objects folder
File bigTreeFile = new File("./git/objects/" + rootTreeHash);
if (!bigTreeFile.exists()) {
try {
Files.copy(rootTree.toPath(), bigTreeFile.toPath());
rootTree.delete();
} catch (IOException e) {
System.out.println("bigTreeFile creation failed");
e.printStackTrace();
}
}
//Creates the actual commit file
Date date = new Date();
StringBuilder commitText = new StringBuilder("");
commitText.append("parent: " + parent + "\n");
commitText.append("tree: " + rootTreeHash + "\n");
commitText.append("author: " + author + "\n");
commitText.append("date: " + date + "\n");
commitText.append("message: " + message);
MessageDigest digester;
String hash = "";
File commitFile = null;
try {
digester = MessageDigest.getInstance("SHA-1");
byte[] sha1bytes = digester.digest(commitText.toString().getBytes());
BigInteger sha1data = new BigInteger(1, sha1bytes);
hash = sha1data.toString(16);
while (hash.length() < 40) {
hash = "0" + hash;
}
commitFile = new File("./git/objects/" + hash);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedWriter commitWriter;
try {
commitWriter = new BufferedWriter(new FileWriter(commitFile));
commitWriter.write(commitText.toString());
commitWriter.close();
//updates the HEAD file
try (BufferedWriter headWriter = new BufferedWriter(new FileWriter("./git/HEAD"))) {
headWriter.write(hash);
}
//clears the index file
(new File("./git/index")).delete();
(new File("./git/index")).createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hash;
}
public void checkout(String commitHash) {
//clear workingRepo
File workingRepo = new File("./workingRepo/");
if (workingRepo.exists()) {
removeDirectory(workingRepo);
}
workingRepo.mkdir();
//Finds commit file
File commitFile = new File("./git/objects/" + commitHash);
if (!commitFile.exists()) {
System.out.println("WARNING: Commit " + commitHash + " does not exist.");
return;
}
//finds the tree hash
String treeHash = null;
try (BufferedReader reader = new BufferedReader(new FileReader(commitFile))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("tree: ")) {
treeHash = line.substring(6);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
return;
}
//finds tree file and restores the files into workingRepo
File treeFile = new File("./git/objects/" + treeHash);
try (BufferedReader treeReader = new BufferedReader(new FileReader(treeFile))) {
String line;
while ((line = treeReader.readLine()) != null) {
String[] parts = line.split(" ");
String type = parts[0];
String fileHash = parts[1];
String path = parts[2];
File objectFile = new File("./git/objects/" + fileHash);
File recreatePath = new File(path);
if (type.equals("blob")) {
remakeBlob(objectFile, recreatePath);
} else {
if (!recreatePath.exists()) {
recreatePath.mkdirs();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
//halpar method
private void remakeBlob(File source, File destination) {
try {
File parentDir = destination.getParentFile();
if (parentDir != null && !parentDir.exists()) {
parentDir.mkdirs();
}
Files.copy(source.toPath(), destination.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}