-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathIndex.java
More file actions
117 lines (86 loc) · 2.97 KB
/
Index.java
File metadata and controls
117 lines (86 loc) · 2.97 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
import java.util.*;
import java.io.*;
/**
* Index
*/
public class Index {
HashMap<String, String> hashes;
public Index()
{
hashes = new HashMap<String, String>();
}
public void initialize() throws Exception
{
File objects = new File("./objects");
if (!objects.exists())
objects.mkdirs();
File index = new File("./index");
if (!index.exists())
index.createNewFile();
}
// This method updates an existing blob in the index for edited files.
public void editBlob(String filename) throws Exception {
// Check if the file already exists in the hash map
for (String key : hashes.keySet()) {
if (hashes.get(key).equals(filename)) {
// File definitely should exist, let's update the entry
Blob blob = new Blob(filename);
hashes.put("blob : " + blob.getEncryption(), filename); // Update with new SHA1
writeToIndex();
return;
}
}
// If we reached here, it means the file was not in the index, hence it's not an edit but an addition
addBlob(filename);
}
// This method marks a file as deleted in the index.
public void deleteBlobMark(String filename) throws Exception {
// The 'filename' should be the original name of the file without any *deleted* prefix
hashes.put("*deleted* " + filename, null); // We store null as the value to indicate deletion
writeToIndex();
}
public void addBlob(String filename) throws Exception {
Blob blob = new Blob(filename);
hashes.put("blob : " + blob.getEncryption(), filename);
writeToIndex();
}
public void deleteBlob(String filename) throws Exception {
File tempFile = new File(filename);
if (tempFile.exists()) {
hashes.remove(filename);
writeToIndex();
} else {
System.out.println("file does not exist");
}
}
public void writeToIndex() throws Exception {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("index")));
for (String key : hashes.keySet()) {
String hash = hashes.get(key);
writer.println(key + " : " + hash);
}
writer.close();
}
// Method to get the entire hashes map
public HashMap<String, String> getFiles()
{
return hashes;
}
public void addDirectory (String folderName) throws Exception
{
Tree t = new Tree ();
t.addDirectory(folderName);
t.saveToObjects();
String entry = folderName + " : " + t.getEncryption();
boolean contains = false;
for (String key : hashes.keySet()) {
if (hashes.get(key).equals(entry)) {
contains = true;
}
}
if (!contains) {
hashes.put("tree: ", entry);
}
writeToIndex();
}
}