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
|
/*
* Copyright (C) 2018-2022, Andre Bossert <andre.bossert@siemens.com>
* Copyright (C) 2019, Tim Neumann <tim.neumann@advantest.com>
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.pgm;
import static org.eclipse.jgit.lib.Constants.HEAD;
import static org.eclipse.jgit.treewalk.TreeWalk.OperationType.CHECKOUT_OP;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.eclipse.jgit.diff.ContentSource;
import org.eclipse.jgit.diff.ContentSource.Pair;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.Side;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.dircache.DirCacheCheckout;
import org.eclipse.jgit.dircache.DirCacheCheckout.CheckoutMetadata;
import org.eclipse.jgit.dircache.DirCacheIterator;
import org.eclipse.jgit.errors.AmbiguousObjectException;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.NoWorkTreeException;
import org.eclipse.jgit.errors.RevisionSyntaxException;
import org.eclipse.jgit.internal.diffmergetool.DiffTools;
import org.eclipse.jgit.internal.diffmergetool.ExternalDiffTool;
import org.eclipse.jgit.internal.diffmergetool.FileElement;
import org.eclipse.jgit.internal.diffmergetool.PromptContinueHandler;
import org.eclipse.jgit.internal.diffmergetool.ToolException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.CoreConfig.EolStreamType;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.TextProgressMonitor;
import org.eclipse.jgit.lib.internal.BooleanTriState;
import org.eclipse.jgit.pgm.internal.CLIText;
import org.eclipse.jgit.pgm.opt.PathTreeFilterHandler;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.AbstractTreeIterator;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.FileTreeIterator;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.WorkingTreeIterator;
import org.eclipse.jgit.treewalk.WorkingTreeOptions;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.eclipse.jgit.util.FS.ExecutionResult;
import org.eclipse.jgit.util.SystemReader;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
@Command(name = "difftool", common = true, usage = "usage_DiffTool")
class DiffTool extends TextBuiltin {
private DiffFormatter diffFmt;
private DiffTools diffTools;
@Argument(index = 0, metaVar = "metaVar_treeish")
private AbstractTreeIterator oldTree;
@Argument(index = 1, metaVar = "metaVar_treeish")
private AbstractTreeIterator newTree;
private Optional<String> toolName = Optional.empty();
@Option(name = "--tool", aliases = {
"-t" }, metaVar = "metaVar_tool", usage = "usage_ToolForDiff")
void setToolName(String name) {
toolName = Optional.of(name);
}
@Option(name = "--cached", aliases = { "--staged" }, usage = "usage_cached")
private boolean cached;
private BooleanTriState prompt = BooleanTriState.UNSET;
@Option(name = "--prompt", usage = "usage_prompt")
void setPrompt(@SuppressWarnings("unused") boolean on) {
prompt = BooleanTriState.TRUE;
}
@Option(name = "--no-prompt", aliases = { "-y" }, usage = "usage_noPrompt")
void noPrompt(@SuppressWarnings("unused") boolean on) {
prompt = BooleanTriState.FALSE;
}
@Option(name = "--tool-help", usage = "usage_toolHelp")
private boolean toolHelp;
private boolean gui = false;
@Option(name = "--gui", aliases = { "-g" }, usage = "usage_DiffGuiTool")
void setGui(@SuppressWarnings("unused") boolean on) {
gui = true;
}
@Option(name = "--no-gui", usage = "usage_noGui")
void noGui(@SuppressWarnings("unused") boolean on) {
gui = false;
}
private BooleanTriState trustExitCode = BooleanTriState.UNSET;
@Option(name = "--trust-exit-code", usage = "usage_trustExitCode")
void setTrustExitCode(@SuppressWarnings("unused") boolean on) {
trustExitCode = BooleanTriState.TRUE;
}
@Option(name = "--no-trust-exit-code", usage = "usage_noTrustExitCode")
void noTrustExitCode(@SuppressWarnings("unused") boolean on) {
trustExitCode = BooleanTriState.FALSE;
}
@Option(name = "--", metaVar = "metaVar_paths", handler = PathTreeFilterHandler.class)
private TreeFilter pathFilter = TreeFilter.ALL;
private BufferedReader inputReader;
@Override
protected void init(Repository repository, String gitDir) {
super.init(repository, gitDir);
diffFmt = new DiffFormatter(new BufferedOutputStream(outs));
diffTools = new DiffTools(repository);
inputReader = new BufferedReader(new InputStreamReader(ins,
SystemReader.getInstance().getDefaultCharset()));
}
@Override
protected void run() {
try {
if (toolHelp) {
showToolHelp();
} else {
// get the changed files
List<DiffEntry> files = getFiles();
if (files.size() > 0) {
compare(files);
}
}
} catch (RevisionSyntaxException | IOException e) {
throw die(e.getMessage(), e);
} finally {
diffFmt.close();
}
}
private void informUserNoTool(List<String> tools) {
try {
StringBuilder toolNames = new StringBuilder();
for (String name : tools) {
toolNames.append(name + " "); //$NON-NLS-1$
}
outw.println(MessageFormat.format(
CLIText.get().diffToolPromptToolName, toolNames));
outw.flush();
} catch (IOException e) {
throw new IllegalStateException("Cannot output text", e); //$NON-NLS-1$
}
}
private class CountingPromptContinueHandler
implements PromptContinueHandler {
private final int fileIndex;
private final int fileCount;
private final String fileName;
public CountingPromptContinueHandler(int fileIndex, int fileCount,
String fileName) {
this.fileIndex = fileIndex;
this.fileCount = fileCount;
this.fileName = fileName;
}
@SuppressWarnings("boxing")
@Override
public boolean prompt(String toolToLaunchName) {
try {
boolean launchCompare = true;
outw.println(MessageFormat.format(CLIText.get().diffToolLaunch,
fileIndex, fileCount, fileName, toolToLaunchName)
+ " "); //$NON-NLS-1$
outw.flush();
BufferedReader br = inputReader;
String line = null;
if ((line = br.readLine()) != null) {
if (!line.equalsIgnoreCase("Y")) { //$NON-NLS-1$
launchCompare = false;
}
}
return launchCompare;
} catch (IOException e) {
throw new IllegalStateException("Cannot output text", e); //$NON-NLS-1$
}
}
}
private void compare(List<DiffEntry> files) throws IOException {
ContentSource.Pair sourcePair = new ContentSource.Pair(source(oldTree),
source(newTree));
try {
for (int fileIndex = 0; fileIndex < files.size(); fileIndex++) {
DiffEntry ent = files.get(fileIndex);
String filePath = ent.getNewPath();
if (filePath.equals(DiffEntry.DEV_NULL)) {
filePath = ent.getOldPath();
}
try {
FileElement local = createFileElement(
FileElement.Type.LOCAL, sourcePair, Side.OLD, ent);
FileElement remote = createFileElement(
FileElement.Type.REMOTE, sourcePair, Side.NEW, ent);
PromptContinueHandler promptContinueHandler = new CountingPromptContinueHandler(
fileIndex + 1, files.size(), filePath);
Optional<ExecutionResult> optionalResult = diffTools
.compare(local, remote, toolName, prompt, gui,
trustExitCode, promptContinueHandler,
this::informUserNoTool);
if (optionalResult.isPresent()) {
ExecutionResult result = optionalResult.get();
// TODO: check how to return the exit-code of the tool
// to jgit / java runtime ?
// int rc =...
Charset defaultCharset = SystemReader.getInstance()
.getDefaultCharset();
outw.println(
new String(result.getStdout().toByteArray(),
defaultCharset));
outw.flush();
errw.println(
new String(result.getStderr().toByteArray(),
defaultCharset));
errw.flush();
}
} catch (ToolException e) {
outw.println(e.getResultStdout());
outw.flush();
errw.println(e.getMessage());
errw.flush();
throw die(MessageFormat.format(
CLIText.get().diffToolDied, filePath, e), e);
}
}
} finally {
sourcePair.close();
}
}
private void showToolHelp() throws IOException {
Map<String, ExternalDiffTool> predefTools = diffTools
.getPredefinedTools(true);
StringBuilder availableToolNames = new StringBuilder();
StringBuilder notAvailableToolNames = new StringBuilder();
for (String name : predefTools.keySet()) {
if (predefTools.get(name).isAvailable()) {
availableToolNames.append(MessageFormat.format("\t\t{0}\n", name)); //$NON-NLS-1$
} else {
notAvailableToolNames.append(MessageFormat.format("\t\t{0}\n", name)); //$NON-NLS-1$
}
}
StringBuilder userToolNames = new StringBuilder();
Map<String, ExternalDiffTool> userTools = diffTools
.getUserDefinedTools();
for (String name : userTools.keySet()) {
userToolNames.append(MessageFormat.format("\t\t{0}.cmd {1}\n", //$NON-NLS-1$
name, userTools.get(name).getCommand()));
}
outw.println(MessageFormat.format(
CLIText.get().diffToolHelpSetToFollowing, availableToolNames,
userToolNames, notAvailableToolNames));
}
private List<DiffEntry> getFiles()
throws RevisionSyntaxException, AmbiguousObjectException,
IncorrectObjectTypeException, IOException {
diffFmt.setRepository(db);
if (cached) {
if (oldTree == null) {
ObjectId head = db.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
if (head == null) {
die(MessageFormat.format(CLIText.get().notATree, HEAD));
}
CanonicalTreeParser p = new CanonicalTreeParser();
try (ObjectReader reader = db.newObjectReader()) {
p.reset(reader, head);
}
oldTree = p;
}
newTree = new DirCacheIterator(db.readDirCache());
} else if (oldTree == null) {
oldTree = new DirCacheIterator(db.readDirCache());
newTree = new FileTreeIterator(db);
} else if (newTree == null) {
newTree = new FileTreeIterator(db);
}
TextProgressMonitor pm = new TextProgressMonitor(errw);
pm.setDelayStart(2, TimeUnit.SECONDS);
diffFmt.setProgressMonitor(pm);
diffFmt.setPathFilter(pathFilter);
List<DiffEntry> files = diffFmt.scan(oldTree, newTree);
return files;
}
private FileElement createFileElement(FileElement.Type elementType,
Pair pair, Side side, DiffEntry entry) throws NoWorkTreeException,
CorruptObjectException, IOException, ToolException {
String entryPath = side == Side.NEW ? entry.getNewPath()
: entry.getOldPath();
FileElement fileElement = new FileElement(entryPath, elementType,
db.getWorkTree());
if (!pair.isWorkingTreeSource(side) && !fileElement.isNullPath()) {
try (RevWalk revWalk = new RevWalk(db);
TreeWalk treeWalk = new TreeWalk(db,
revWalk.getObjectReader())) {
treeWalk.setFilter(
PathFilterGroup.createFromStrings(entryPath));
if (side == Side.NEW) {
newTree.reset();
treeWalk.addTree(newTree);
} else {
oldTree.reset();
treeWalk.addTree(oldTree);
}
if (treeWalk.next()) {
final EolStreamType eolStreamType = treeWalk
.getEolStreamType(CHECKOUT_OP);
final String filterCommand = treeWalk.getFilterCommand(
Constants.ATTR_FILTER_TYPE_SMUDGE);
WorkingTreeOptions opt = db.getConfig()
.get(WorkingTreeOptions.KEY);
CheckoutMetadata checkoutMetadata = new CheckoutMetadata(
eolStreamType, filterCommand);
DirCacheCheckout.getContent(db, entryPath,
checkoutMetadata, pair.open(side, entry), opt,
new FileOutputStream(
fileElement.createTempFile(null)));
} else {
throw new ToolException("Cannot find path '" + entryPath //$NON-NLS-1$
+ "' in staging area!", //$NON-NLS-1$
null);
}
}
}
return fileElement;
}
private ContentSource source(AbstractTreeIterator iterator) {
if (iterator instanceof WorkingTreeIterator) {
return ContentSource.create((WorkingTreeIterator) iterator);
}
return ContentSource.create(db.newObjectReader());
}
}
|