-
Notifications
You must be signed in to change notification settings - Fork 114
/
Change.java
357 lines (311 loc) · 13.6 KB
/
Change.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
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
/*
* Copyright 2017 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.centraldogma.common;
import static com.linecorp.centraldogma.internal.Util.validateDirPath;
import static com.linecorp.centraldogma.internal.Util.validateFilePath;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.io.IOError;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.linecorp.centraldogma.internal.Jackson;
import com.linecorp.centraldogma.internal.Util;
import com.linecorp.centraldogma.internal.jsonpatch.JsonPatch;
import com.linecorp.centraldogma.internal.jsonpatch.ReplaceMode;
import difflib.DiffUtils;
import difflib.Patch;
/**
* A modification of an individual {@link Entry}.
*/
@JsonDeserialize(as = DefaultChange.class)
public interface Change<T> {
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#UPSERT_TEXT}.
*
* <p>Note that you should use {@link #ofJsonUpsert(String, String)} if the specified {@code path} ends with
* {@code ".json"}. The {@link #ofJsonUpsert(String, String)} will check that the given {@code text} is a
* valid JSON.
*
* @param path the path of the file
* @param text the content of the file
* @throws ChangeFormatException if the path ends with {@code ".json"}
*/
static Change<String> ofTextUpsert(String path, String text) {
requireNonNull(text, "text");
validateFilePath(path, "path");
if (EntryType.guessFromPath(path) == EntryType.JSON) {
throw new ChangeFormatException("invalid file type: " + path +
" (expected: a non-JSON file). Use Change.ofJsonUpsert() instead");
}
return new DefaultChange<>(path, ChangeType.UPSERT_TEXT, text);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#UPSERT_JSON}.
*
* @param path the path of the file
* @param jsonText the content of the file
*
* @throws ChangeFormatException if the specified {@code jsonText} is not a valid JSON
*/
static Change<JsonNode> ofJsonUpsert(String path, String jsonText) {
requireNonNull(jsonText, "jsonText");
final JsonNode jsonNode;
try {
jsonNode = Jackson.readTree(jsonText);
} catch (IOException e) {
throw new ChangeFormatException("failed to read a value as a JSON tree", e);
}
return new DefaultChange<>(path, ChangeType.UPSERT_JSON, jsonNode);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#UPSERT_JSON}.
*
* @param path the path of the file
* @param jsonNode the content of the file
*/
static Change<JsonNode> ofJsonUpsert(String path, JsonNode jsonNode) {
requireNonNull(jsonNode, "jsonNode");
return new DefaultChange<>(path, ChangeType.UPSERT_JSON, jsonNode);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#REMOVE}.
*
* @param path the path of the file to remove
*/
static Change<Void> ofRemoval(String path) {
return new DefaultChange<>(path, ChangeType.REMOVE, null);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#RENAME}.
*
* @param oldPath the old path of the file
* @param newPath the new path of the file
*/
static Change<String> ofRename(String oldPath, String newPath) {
validateFilePath(oldPath, "oldPath");
validateFilePath(newPath, "newPath");
return new DefaultChange<>(oldPath, ChangeType.RENAME, newPath);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#APPLY_TEXT_PATCH}.
*
* <p>Note that you should use {@link #ofJsonPatch(String, String, String)} if the specified {@code path}
* ends with {@code ".json"}. The {@link #ofJsonUpsert(String, String)} will check that
* the given {@code oldText} and {@code newText} are valid JSONs.
*
* @param path the path of the file
* @param oldText the old content of the file
* @param newText the new content of the file
* @throws ChangeFormatException if the path ends with {@code ".json"}
*/
static Change<String> ofTextPatch(String path, @Nullable String oldText, String newText) {
validateFilePath(path, "path");
requireNonNull(newText, "newText");
if (EntryType.guessFromPath(path) == EntryType.JSON) {
throw new ChangeFormatException("invalid file type: " + path +
" (expected: a non-JSON file). Use Change.ofJsonPatch() instead");
}
final List<String> oldLineList = oldText == null ? Collections.emptyList()
: Util.stringToLines(oldText);
final List<String> newLineList = Util.stringToLines(newText);
final Patch<String> patch = DiffUtils.diff(oldLineList, newLineList);
final List<String> unifiedDiff = DiffUtils.generateUnifiedDiff(path, path, oldLineList, patch, 3);
return new DefaultChange<>(path, ChangeType.APPLY_TEXT_PATCH, String.join("\n", unifiedDiff));
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#APPLY_TEXT_PATCH}.
*
* <p>Note that you should use {@link #ofJsonPatch(String, String)} if the specified {@code path}
* ends with {@code ".json"}. The {@link #ofJsonUpsert(String, String)} will check that
* the given {@code textPatch} is a valid JSON.
*
* @param path the path of the file
* @param textPatch the patch in
* <a href="https://en.wikipedia.org/wiki/Diff_utility#Unified_format">unified format</a>
* @throws ChangeFormatException if the path ends with {@code ".json"}
*/
static Change<String> ofTextPatch(String path, String textPatch) {
validateFilePath(path, "path");
requireNonNull(textPatch, "textPatch");
if (EntryType.guessFromPath(path) == EntryType.JSON) {
throw new ChangeFormatException("invalid file type: " + path +
" (expected: a non-JSON file). Use Change.ofJsonPatch() instead");
}
return new DefaultChange<>(path, ChangeType.APPLY_TEXT_PATCH, textPatch);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#APPLY_JSON_PATCH}.
*
* @param path the path of the file
* @param oldJsonText the old content of the file
* @param newJsonText the new content of the file
*
* @throws ChangeFormatException if the specified {@code oldJsonText} or {@code newJsonText} is
* not a valid JSON
*/
static Change<JsonNode> ofJsonPatch(String path, @Nullable String oldJsonText, String newJsonText) {
requireNonNull(newJsonText, "newJsonText");
final JsonNode oldJsonNode;
final JsonNode newJsonNode;
try {
oldJsonNode = oldJsonText == null ? Jackson.nullNode
: Jackson.readTree(oldJsonText);
newJsonNode = Jackson.readTree(newJsonText);
} catch (IOException e) {
throw new ChangeFormatException("failed to read a value as a JSON tree", e);
}
return new DefaultChange<>(path, ChangeType.APPLY_JSON_PATCH,
JsonPatch.generate(oldJsonNode, newJsonNode, ReplaceMode.SAFE).toJson());
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#APPLY_JSON_PATCH}.
*
* @param path the path of the file
* @param oldJsonNode the old content of the file
* @param newJsonNode the new content of the file
*/
static Change<JsonNode> ofJsonPatch(String path, @Nullable JsonNode oldJsonNode, JsonNode newJsonNode) {
requireNonNull(newJsonNode, "newJsonNode");
if (oldJsonNode == null) {
oldJsonNode = Jackson.nullNode;
}
return new DefaultChange<>(path, ChangeType.APPLY_JSON_PATCH,
JsonPatch.generate(oldJsonNode, newJsonNode, ReplaceMode.SAFE).toJson());
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#APPLY_JSON_PATCH}.
*
* @param path the path of the file
* @param jsonPatchText the patch in <a href="https://tools.ietf.org/html/rfc6902">JSON patch format</a>
*
* @throws ChangeFormatException if the specified {@code jsonPatchText} is not a valid JSON
*/
static Change<JsonNode> ofJsonPatch(String path, String jsonPatchText) {
requireNonNull(jsonPatchText, "jsonPatchText");
final JsonNode jsonPatchNode;
try {
jsonPatchNode = Jackson.readTree(jsonPatchText);
} catch (IOException e) {
throw new ChangeFormatException("failed to read a value as a JSON tree", e);
}
return ofJsonPatch(path, jsonPatchNode);
}
/**
* Returns a newly-created {@link Change} whose type is {@link ChangeType#APPLY_JSON_PATCH}.
*
* @param path the path of the file
* @param jsonPatchNode the patch in <a href="https://tools.ietf.org/html/rfc6902">JSON patch format</a>
*/
static Change<JsonNode> ofJsonPatch(String path, JsonNode jsonPatchNode) {
requireNonNull(jsonPatchNode, "jsonPatchNode");
return new DefaultChange<>(path, ChangeType.APPLY_JSON_PATCH, jsonPatchNode);
}
/**
* Creates a {@link List} of upsert {@link Change}s from all files under the specified directory
* recursively.
*
* @param sourcePath the path to the import directory
* @param targetPath the target directory path of the imported {@link Change}s
*
* @throws IOError if I/O error occurs
*/
static List<Change<?>> fromDirectory(Path sourcePath, String targetPath) {
requireNonNull(sourcePath, "sourcePath");
validateDirPath(targetPath, "targetPath");
if (!Files.isDirectory(sourcePath)) {
throw new IllegalArgumentException("sourcePath: " + sourcePath + " (must be a directory)");
}
final String finalTargetPath;
if (!targetPath.endsWith("/")) {
finalTargetPath = targetPath + '/';
} else {
finalTargetPath = targetPath;
}
try (Stream<Path> s = Files.find(sourcePath, Integer.MAX_VALUE, (p, a) -> a.isRegularFile())) {
final int baseLength = sourcePath.toString().length() + 1;
return s.map(sourceFilePath -> {
final String targetFilePath =
finalTargetPath +
sourceFilePath.toString().substring(baseLength).replace(File.separatorChar, '/');
return fromFile(sourceFilePath, targetFilePath);
}).collect(Collectors.toList());
} catch (IOException e) {
throw new IOError(e);
}
}
/**
* Creates a new {@link Change} from the file at the specified location.
*
* @param sourcePath the path to the regular file to import
* @param targetPath the target path of the imported {@link Change}
*/
static Change<?> fromFile(Path sourcePath, String targetPath) {
requireNonNull(sourcePath, "sourcePath");
validateFilePath(targetPath, "targetPath");
if (!Files.isRegularFile(sourcePath)) {
throw new IllegalArgumentException("sourcePath: " + sourcePath + " (must be a regular file)");
}
if (targetPath.endsWith("/")) {
throw new IllegalArgumentException("targetPath: " + targetPath + " (must be a regular file path)");
}
final EntryType entryType = EntryType.guessFromPath(targetPath);
final String content;
try {
content = new String(Files.readAllBytes(sourcePath), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new IOError(e);
}
switch (entryType) {
case JSON:
return ofJsonUpsert(targetPath, content);
case TEXT:
return ofTextUpsert(targetPath, content);
default:
throw new Error("unexpected entry type: " + entryType);
}
}
/**
* Returns the type of the {@link Change}.
*/
@JsonProperty
ChangeType type();
/**
* Returns the path of the {@link Change}.
*/
@JsonProperty
String path();
/**
* Returns the content of the {@link Change}, which depends on the {@link #type()}.
*/
@Nullable
@JsonProperty
T content();
/**
* Returns the textual representation of {@link #content()}.
*/
@Nullable
String contentAsText();
}