-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.java
239 lines (208 loc) · 8.39 KB
/
Utils.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
package gitlet;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;
/** Assorted utilities.
*
* Give this file a good read as it provides several useful utility functions
* to save you some time.
*
* @author P. N. Hilfinger
*/
class Utils {
/** The length of a complete SHA-1 UID as a hexadecimal numeral. */
static final int UID_LENGTH = 40;
/* SHA-1 HASH VALUES. */
/** Returns the SHA-1 hash of the concatenation of VALS, which may
* be any mixture of byte arrays and Strings. */
static String sha1(Object... vals) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
for (Object val : vals) {
if (val instanceof byte[]) {
md.update((byte[]) val);
} else if (val instanceof String) {
md.update(((String) val).getBytes(StandardCharsets.UTF_8));
} else {
throw new IllegalArgumentException("improper type to sha1");
}
}
Formatter result = new Formatter();
for (byte b : md.digest()) {
result.format("%02x", b);
}
return result.toString();
} catch (NoSuchAlgorithmException excp) {
throw new IllegalArgumentException("System does not support SHA-1");
}
}
/** Returns the SHA-1 hash of the concatenation of the strings in
* VALS. */
static String sha1(List<Object> vals) {
return sha1(vals.toArray(new Object[vals.size()]));
}
/* FILE DELETION */
/** Deletes FILE if it exists and is not a directory. Returns true
* if FILE was deleted, and false otherwise. Refuses to delete FILE
* and throws IllegalArgumentException unless the directory designated by
* FILE also contains a directory named .gitlet. */
static boolean restrictedDelete(File file) {
if (!(new File(file.getParentFile(), ".gitlet")).isDirectory()) {
throw new IllegalArgumentException("not .gitlet working directory");
}
if (!file.isDirectory()) {
return file.delete();
} else {
return false;
}
}
/** Deletes the file named FILE if it exists and is not a directory.
* Returns true if FILE was deleted, and false otherwise. Refuses
* to delete FILE and throws IllegalArgumentException unless the
* directory designated by FILE also contains a directory named .gitlet. */
static boolean restrictedDelete(String file) {
return restrictedDelete(new File(file));
}
/* READING AND WRITING FILE CONTENTS */
/** Return the entire contents of FILE as a byte array. FILE must
* be a normal file. Throws IllegalArgumentException
* in case of problems. */
static byte[] readContents(File file) {
if (!file.isFile()) {
throw new IllegalArgumentException("must be a normal file");
}
try {
return Files.readAllBytes(file.toPath());
} catch (IOException excp) {
throw new IllegalArgumentException(excp.getMessage());
}
}
/** Return the entire contents of FILE as a String. FILE must
* be a normal file. Throws IllegalArgumentException
* in case of problems. */
static String readContentsAsString(File file) {
return new String(readContents(file), StandardCharsets.UTF_8);
}
/** Write the result of concatenating the bytes in CONTENTS to FILE,
* creating or overwriting it as needed. Each object in CONTENTS may be
* either a String or a byte array. Throws IllegalArgumentException
* in case of problems. */
static void writeContents(File file, Object... contents) {
try {
if (file.isDirectory()) {
throw
new IllegalArgumentException("cannot overwrite directory");
}
BufferedOutputStream str =
new BufferedOutputStream(Files.newOutputStream(file.toPath()));
for (Object obj : contents) {
if (obj instanceof byte[]) {
str.write((byte[]) obj);
} else {
str.write(((String) obj).getBytes(StandardCharsets.UTF_8));
}
}
str.close();
} catch (IOException | ClassCastException excp) {
throw new IllegalArgumentException(excp.getMessage());
}
}
/** Return an object of type T read from FILE, casting it to EXPECTEDCLASS.
* Throws IllegalArgumentException in case of problems. */
static <T extends Serializable> T readObject(File file,
Class<T> expectedClass) {
try {
ObjectInputStream in =
new ObjectInputStream(new FileInputStream(file));
T result = expectedClass.cast(in.readObject());
in.close();
return result;
} catch (IOException | ClassCastException
| ClassNotFoundException excp) {
throw new IllegalArgumentException(excp.getMessage());
}
}
/** Write OBJ to FILE. */
static void writeObject(File file, Serializable obj) {
writeContents(file, serialize(obj));
}
/* DIRECTORIES */
/** Filter out all but plain files. */
private static final FilenameFilter PLAIN_FILES =
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return new File(dir, name).isFile();
}
};
/** Returns a list of the names of all plain files in the directory DIR, in
* lexicographic order as Java Strings. Returns null if DIR does
* not denote a directory. */
static List<String> plainFilenamesIn(File dir) {
String[] files = dir.list(PLAIN_FILES);
if (files == null) {
return null;
} else {
Arrays.sort(files);
return Arrays.asList(files);
}
}
/** Returns a list of the names of all plain files in the directory DIR, in
* lexicographic order as Java Strings. Returns null if DIR does
* not denote a directory. */
static List<String> plainFilenamesIn(String dir) {
return plainFilenamesIn(new File(dir));
}
/* OTHER FILE UTILITIES */
/** Return the concatentation of FIRST and OTHERS into a File designator,
* analogous to the {@link java.nio.file.Paths.#get(String, String[])}
* method. */
static File join(String first, String... others) {
return Paths.get(first, others).toFile();
}
/** Return the concatentation of FIRST and OTHERS into a File designator,
* analogous to the {@link java.nio.file.Paths.#get(String, String[])}
* method. */
static File join(File first, String... others) {
return Paths.get(first.getPath(), others).toFile();
}
/* SERIALIZATION UTILITIES */
/** Returns a byte array containing the serialized contents of OBJ. */
static byte[] serialize(Serializable obj) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream objectStream = new ObjectOutputStream(stream);
objectStream.writeObject(obj);
objectStream.close();
return stream.toByteArray();
} catch (IOException excp) {
throw error("Internal error serializing commit.");
}
}
/* MESSAGES AND ERROR REPORTING */
/** Return a GitletException whose message is composed from MSG and ARGS as
* for the String.format method. */
static GitletException error(String msg, Object... args) {
return new GitletException(String.format(msg, args));
}
/** Print a message composed from MSG and ARGS as for the String.format
* method, followed by a newline. */
static void message(String msg, Object... args) {
System.out.printf(msg, args);
System.out.println();
}
}