-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTree.java
More file actions
464 lines (385 loc) · 14 KB
/
Tree.java
File metadata and controls
464 lines (385 loc) · 14 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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
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.Formatter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
//traversal: given file name of tree read thru each line of file
// does the line contain the target file
//sepearate the trees and the blobs
/// if it does we're odne
// if it doesnt we have another
// if its a file we havent deleted and were looking for save it in the list
// if its a tree go back and check thtat tree
enum EntryType {
BLOB("blob"),
TREE("tree"),
UNKNOWN("");
private final String label;
EntryType(String label) {
this.label = label;
}
// A method to determine the type based on the input string
public static EntryType fromString(String input) {
for (EntryType type : values()) {
if (input.startsWith(type.label)) {
return type;
}
}
return UNKNOWN;
}
}
public class Tree {
private Map<String, String> fileSHA1Map = new HashMap<>();
// Constructor and other methods ...
// Method to get the SHA1 of a file by its name
public String getFileSHA1(String fileName) {
return fileSHA1Map.get(fileName);
}
// Method to load a file and its SHA1 into the map (you may already have a
// similar method)
public void addFileSHA1(String fileName, String sha1) {
fileSHA1Map.put(fileName, sha1);
}
// might need a hashmap but made it with arraylist
private ArrayList<String> blobList;
private ArrayList<String> treeList;
String encryption = "";
File tree;
private Index index;
public Tree() throws IOException {
blobList = new ArrayList<String>();
treeList = new ArrayList<String>();
initialize();
}
public Tree(Index index) throws Exception {
if (index == null) {
this.index = new Index();
} else {
this.index = index;
}
// Initialize lists and potentially load existing tree contents
this.blobList = new ArrayList<>();
this.treeList = new ArrayList<>();
this.initialize();
// Loop over the files in the index
for (Map.Entry<String, String> fileEntry : index.getFiles().entrySet()) {
String key = fileEntry.getKey();
String value = fileEntry.getValue();
if (key.startsWith("*deleted*")) {
// Do not include deleted files in the tree
continue;
}
if (key.startsWith("*edited*")) {
// Replace the file's SHA1 with the new one
String filename = key.replace("*edited*", "");
updateFileInTree(filename, value); // This method needs to be implemented
} else {
// Add or update the file in the tree
addFileToTree(key, value); // This method needs to be implemented
}
}
// Save the updated tree
this.saveToObjects();
}
// find file, one line of code, if file is not the target file, add it to a list
// point to tree before that,
// point to all files before that
// Method to add a file to the tree
private void addFileToTree(String filename, String sha1) throws IOException {
String treeEntry = "blob : " + sha1 + " : " + filename;
addToTree(treeEntry);
}
// Method to update a file in the tree
private void updateFileInTree(String filename, String newSha1) throws Exception {
// Find the existing entry for the file
String existingEntry = findLine(filename, tree);
if (existingEntry != null) {
// Remove the old entry
deleteTree(existingEntry);
// Add the new entry
addFileToTree(filename, newSha1);
} else {
// If the file wasn't part of the tree yet, just add it
addFileToTree(filename, newSha1);
}
}
private void loadTreeContents() throws IOException {
tree = new File("./tree");
// blobList.clear(); // Clear the blobList
// treeList.clear(); // Clear the treeList
if (tree.exists()) {
BufferedReader br = new BufferedReader(new FileReader(tree));
String line;
while ((line = br.readLine()) != null) {
EntryType type = EntryType.fromString(line);
if (type == EntryType.BLOB && !blobList.contains(line)) {
blobList.add(line);
} else if (type == EntryType.TREE && !treeList.contains(line)) {
treeList.add(line);
}
}
br.close();
}
}
public boolean hasFile(String filePath) {
for (String blobEntry : blobList) {
// Extract the file path part from the blob entry. Assuming the format "blob :
// sha1 : path"
String[] parts = blobEntry.split(" : ");
if (parts.length > 2 && parts[2].equals(filePath)) {
return true;
}
}
return false;
}
public void saveToObjects() throws Exception {
loadTreeContents(); // Make sure to have the latest tree contents
String treeContent = "";
treeContent += Utils.arrayListToFileFormat(blobList);
treeContent += Utils.arrayListToFileFormat(treeList);
encryption = Utils.stringtoSHA(treeContent);
Utils.writeToFile("./objects/" + encryption, treeContent);
Utils.writeToFile("./tree", treeContent);
}
public String getEncryption() {
return encryption;
}
// fixed method addToTree
public boolean addToTree(String input) throws IOException {
if (!entryExists(input)) {
EntryType type = EntryType.fromString(input);
switch (type) {
case BLOB:
if (!blobList.contains(input)) {
blobList.add(input);
}
break;
case TREE:
if (!treeList.contains(input)) {
treeList.add(input);
}
break;
default:
// Handle an unrecognized type if necessary
return false;
}
saveListsToFile();
return true;
}
return false;
}
// checks if input line appears in our tree
private boolean entryExists(String inputLine) throws IOException {
return blobList.contains(inputLine) || treeList.contains(inputLine);
}
private void saveListsToFile() throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("./tree"))) {
for (String blob : blobList) {
bw.write(blob);
bw.newLine();
}
for (String t : treeList) {
bw.write(t);
bw.newLine();
}
}
}
public void addDirectory(String directory) throws Exception {
File directoryFile = new File(directory);
if (!directoryFile.isDirectory()) {
throw new Exception(directory + " is an invalid directory path.");
}
for (File file : directoryFile.listFiles()) {
if (file.isFile()) {
String filePath = directory + "/" + file.getName();
Blob blob = new Blob(filePath); // optional
addToTree("blob : " + blob.getEncryption() + " : " + filePath);
} else if (file.isDirectory()) {
Tree subTree = new Tree();
String tempPath = file.getPath();
subTree.addDirectory(tempPath);
subTree.saveToObjects();
addToTree("tree : " + subTree.getEncryption() + " : " + tempPath);
}
}
}
public void initialize() throws IOException {
File objects = new File("./objects");
if (!objects.exists()) {
objects.mkdirs();
}
tree = new File("tree");
if (!tree.exists()) {
tree.createNewFile();
} else {
loadTreeContents(); // Load tree contents here.
}
}
public void rename(File fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String str = "";
while (br.ready()) {
str += br.readLine() + "\n";
}
str = str.trim();// get rid of extra line
br.close();
// converting to sha1
String sha1 = encryptPassword(str);
// printing to objects folder
String dirName = "./objects/";
File dir = new File(dirName);// create this directory (File class java)
// dir.mkdir();
File newFile = new File(dir, sha1);
PrintWriter pw = new PrintWriter(newFile);
pw.print(str);
pw.close();
}
public String encryptPassword(String password) {
String sha1 = "";
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(password.getBytes("UTF-8"));
sha1 = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return sha1;
}
private String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
public boolean deleteTree(String input) throws Exception {
File inputFile = new File("tree");
File tempFile = new File("myTempFile.txt");
String lineToRemove = "";
if (!entryExists2(input, tree)) {
return false;
}
lineToRemove = findLine(input, tree);
System.out.println("remove: " + lineToRemove);// test: correct
String type = lineToRemove.substring(0, 4);
if (type.equals("blob")) {
blobList.remove(lineToRemove);
} else if (type.equals("tree")) {
treeList.remove(lineToRemove);
}
printList(tempFile);
boolean successful = tempFile.renameTo(inputFile);
return successful;
}
private boolean entryExists2(String input, File tree2) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(tree));
while (br.ready()) {
String str = br.readLine();
if (str.contains(input)) {
br.close();
return true;
}
}
br.close();
return false;
}
private void printList(File fileName) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter(fileName));
for (int i = 0; i < blobList.size(); i++) {
String str = blobList.get(i);
if (treeList.size() != 0 && i == blobList.size() - 1) {
pw.println(str);
} else if (i != blobList.size() - 1) {
pw.println(str);
} else {
pw.print(str);
}
}
for (int i = 0; i < treeList.size(); i++) {
String str = treeList.get(i);
if (i != treeList.size() - 1) {
pw.println(str);
} else {
pw.print(str);
}
}
pw.close();
}
// Method to load the Tree from a SHA1 file location
public void loadFromSHA1(String fileLocation) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(fileLocation)));
this.parseAndAddBlobs(content);
}
private void parseAndAddBlobs(String content) {
String[] blobEntries = content.split("\\r?\\n");
for (String blobEntry : blobEntries) {
this.blobList.add(blobEntry);
}
}
private String findLine(String input, File tree2) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(tree));
while (br.ready()) {
String str = br.readLine();
if (str.contains(input)) {
br.close();
return str;
}
}
br.close();
throw new Exception("line not found", null);
}
public static String findTreeFromCommit(String commitSHA) throws Exception {
boolean isInTree = false;
ArrayList<String> commits = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("./objects/" + commitSHA));
while (br.ready()) {
commits.add(br.readLine());
}
br.close();
return commits.get(0);
}
public static ArrayList<String> traverseForFile(String targetFilePath, String treeSHA) throws Exception {
boolean foundFile = false;
ArrayList<String> currentTree = new ArrayList<String>();
ArrayList<String> trees = new ArrayList<String>();
ArrayList<String> blobs = new ArrayList<String>();
BufferedReader br2 = new BufferedReader(new FileReader("./objects/" + treeSHA));
while (br2.ready()) {
currentTree.add(br2.readLine());
}
br2.close();
for (String s : currentTree) {
String firstWord = s.substring(0, s.indexOf(" "));
if (firstWord.equals("blob")) {
if (!s.contains(targetFilePath)) {
blobs.add(s);
} else {
foundFile = true;
}
} else {
trees.add(s);
}
}
if (trees.size() != 0) {
blobs.addAll(traverseForFile(targetFilePath, trees.get(0)));
}
return blobs;
}
}