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
|
/*
* 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.internal.diffmergetool;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.lib.internal.BooleanTriState;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FS.ExecutionResult;
import org.eclipse.jgit.util.StringUtils;
/**
* Manages merge tools.
*/
public class MergeTools {
private final FS fs;
private final File gitDir;
private final File workTree;
private final MergeToolConfig config;
private final Repository repo;
private final Map<String, ExternalMergeTool> predefinedTools;
private final Map<String, ExternalMergeTool> userDefinedTools;
/**
* Creates the external merge-tools manager for given repository.
*
* @param repo
* the repository
*/
public MergeTools(Repository repo) {
this(repo, repo.getConfig());
}
/**
* Creates the external diff-tools manager for given configuration.
*
* @param config
* the git configuration
*/
public MergeTools(StoredConfig config) {
this(null, config);
}
private MergeTools(Repository repo, StoredConfig config) {
this.repo = repo;
this.config = config.get(MergeToolConfig.KEY);
this.gitDir = repo == null ? null : repo.getDirectory();
this.fs = repo == null ? FS.DETECTED : repo.getFS();
this.workTree = repo == null ? null : repo.getWorkTree();
predefinedTools = setupPredefinedTools();
userDefinedTools = setupUserDefinedTools(predefinedTools);
}
/**
* Merge two versions of a file with optional base file.
*
* @param localFile
* The local/left version of the file.
* @param remoteFile
* The remote/right version of the file.
* @param mergedFile
* The file for the result.
* @param baseFile
* The base version of the file. May be null.
* @param tempDir
* The tmepDir used for the files. May be null.
* @param toolName
* Optionally the name of the tool to use. If not given the
* default tool will be used.
* @param prompt
* Optionally a flag whether to prompt the user before compare.
* If not given the default will be used.
* @param gui
* A flag whether to prefer a gui tool.
* @param promptHandler
* The handler to use when needing to prompt the user if he wants
* to continue.
* @param noToolHandler
* The handler to use when needing to inform the user, that no
* tool is configured.
* @return the optional result of executing the tool if it was executed
* @throws ToolException
* when the tool fails
*/
public Optional<ExecutionResult> merge(FileElement localFile,
FileElement remoteFile, FileElement mergedFile,
FileElement baseFile, File tempDir, Optional<String> toolName,
BooleanTriState prompt, boolean gui,
PromptContinueHandler promptHandler,
InformNoToolHandler noToolHandler) throws ToolException {
String toolNameToUse;
if (toolName == null) {
throw new ToolException(JGitText.get().diffToolNullError);
}
if (toolName.isPresent()) {
toolNameToUse = toolName.get();
} else {
toolNameToUse = getDefaultToolName(gui);
if (StringUtils.isEmptyOrNull(toolNameToUse)) {
noToolHandler.inform(new ArrayList<>(predefinedTools.keySet()));
toolNameToUse = getFirstAvailableTool();
}
}
if (StringUtils.isEmptyOrNull(toolNameToUse)) {
throw new ToolException(JGitText.get().diffToolNotGivenError);
}
boolean doPrompt;
if (prompt != BooleanTriState.UNSET) {
doPrompt = prompt == BooleanTriState.TRUE;
} else {
doPrompt = isInteractive();
}
if (doPrompt) {
if (!promptHandler.prompt(toolNameToUse)) {
return Optional.empty();
}
}
ExternalMergeTool tool = getTool(toolNameToUse);
if (tool == null) {
throw new ToolException(
"External merge tool is not defined: " + toolNameToUse); //$NON-NLS-1$
}
return Optional.of(merge(localFile, remoteFile, mergedFile, baseFile,
tempDir, tool));
}
/**
* Merge two versions of a file with optional base file.
*
* @param localFile
* the local file element
* @param remoteFile
* the remote file element
* @param mergedFile
* the merged file element
* @param baseFile
* the base file element (can be null)
* @param tempDir
* the temporary directory (needed for backup and auto-remove,
* can be null)
* @param tool
* the selected tool
* @return the execution result from tool
* @throws ToolException
* if the tool failed
*/
public ExecutionResult merge(FileElement localFile, FileElement remoteFile,
FileElement mergedFile, FileElement baseFile, File tempDir,
ExternalMergeTool tool) throws ToolException {
FileElement backup = null;
ExecutionResult result = null;
try {
// create additional backup file (copy worktree file)
backup = createBackupFile(mergedFile,
tempDir != null ? tempDir : workTree);
// prepare the command (replace the file paths)
String command = ExternalToolUtils.prepareCommand(
tool.getCommand(baseFile != null), localFile, remoteFile,
mergedFile, baseFile);
// prepare the environment
Map<String, String> env = ExternalToolUtils.prepareEnvironment(
gitDir, localFile, remoteFile, mergedFile, baseFile);
boolean trust = tool.getTrustExitCode() == BooleanTriState.TRUE;
// execute the tool
CommandExecutor cmdExec = new CommandExecutor(fs, trust);
result = cmdExec.run(command, workTree, env);
// keep backup as .orig file
if (backup != null) {
keepBackupFile(mergedFile.getPath(), backup);
}
return result;
} catch (IOException | InterruptedException e) {
throw new ToolException(e);
} finally {
// always delete backup file (ignore that it was may be already
// moved to keep-backup file)
if (backup != null) {
backup.cleanTemporaries();
}
// if the tool returns an error and keepTemporaries is set to true,
// then these temporary files will be preserved
if (!((result == null) && config.isKeepTemporaries())) {
// delete the files
localFile.cleanTemporaries();
remoteFile.cleanTemporaries();
if (baseFile != null) {
baseFile.cleanTemporaries();
}
// delete temporary directory if needed
if (config.isWriteToTemp() && (tempDir != null)
&& tempDir.exists()) {
tempDir.delete();
}
}
}
}
private FileElement createBackupFile(FileElement from, File toParentDir)
throws IOException {
FileElement backup = null;
Path path = Paths.get(from.getPath());
if (Files.exists(path)) {
backup = new FileElement(from.getPath(), FileElement.Type.BACKUP);
Files.copy(path, backup.createTempFile(toParentDir).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
return backup;
}
/**
* Create temporary directory.
*
* @return the created temporary directory if (mergetol.writeToTemp == true)
* or null if not configured or false.
* @throws IOException
* if an IO error occurred
*/
public File createTempDirectory() throws IOException {
return config.isWriteToTemp()
? Files.createTempDirectory("jgit-mergetool-").toFile() //$NON-NLS-1$
: null;
}
/**
* Get user defined tool names.
*
* @return the user defined tool names
*/
public Set<String> getUserDefinedToolNames() {
return userDefinedTools.keySet();
}
/**
* Get predefined tool names
*
* @return the predefined tool names
*/
public Set<String> getPredefinedToolNames() {
return predefinedTools.keySet();
}
/**
* Get all tool names.
*
* @return the all tool names (default or available tool name is the first
* in the set)
*/
public Set<String> getAllToolNames() {
String defaultName = getDefaultToolName(false);
if (defaultName == null) {
defaultName = getFirstAvailableTool();
}
return ExternalToolUtils.createSortedToolSet(defaultName,
getUserDefinedToolNames(), getPredefinedToolNames());
}
/**
* Provides {@link Optional} with the name of an external merge tool if
* specified in git configuration for a path.
*
* The formed git configuration results from global rules as well as merged
* rules from info and worktree attributes.
*
* Triggers {@link TreeWalk} until specified path found in the tree.
*
* @param path
* path to the node in repository to parse git attributes for
* @return name of the difftool if set
* @throws ToolException
* if the tool failed
*/
public Optional<String> getExternalToolFromAttributes(final String path)
throws ToolException {
return ExternalToolUtils.getExternalToolFromAttributes(repo, path,
ExternalToolUtils.KEY_MERGE_TOOL);
}
/**
* Checks the availability of the predefined tools in the system.
*
* @return set of predefined available tools
*/
public Set<String> getPredefinedAvailableTools() {
Map<String, ExternalMergeTool> defTools = getPredefinedTools(true);
Set<String> availableTools = new LinkedHashSet<>();
for (Entry<String, ExternalMergeTool> elem : defTools.entrySet()) {
if (elem.getValue().isAvailable()) {
availableTools.add(elem.getKey());
}
}
return availableTools;
}
/**
* Get user defined tools
*
* @return the user defined tools
*/
public Map<String, ExternalMergeTool> getUserDefinedTools() {
return Collections.unmodifiableMap(userDefinedTools);
}
/**
* Get predefined tools map.
*
* @param checkAvailability
* true: for checking if tools can be executed; ATTENTION: this
* check took some time, do not execute often (store the map for
* other actions); false: availability is NOT checked:
* isAvailable() returns default false is this case!
* @return the predefined tools with optionally checked availability (long
* running operation)
*/
public Map<String, ExternalMergeTool> getPredefinedTools(
boolean checkAvailability) {
if (checkAvailability) {
for (ExternalMergeTool tool : predefinedTools.values()) {
PreDefinedMergeTool predefTool = (PreDefinedMergeTool) tool;
predefTool.setAvailable(ExternalToolUtils.isToolAvailable(fs,
gitDir, workTree, predefTool.getPath()));
}
}
return Collections.unmodifiableMap(predefinedTools);
}
/**
* Get first available tool name.
*
* @return the name of first available predefined tool or null
*/
public String getFirstAvailableTool() {
String name = null;
for (ExternalMergeTool tool : predefinedTools.values()) {
if (ExternalToolUtils.isToolAvailable(fs, gitDir, workTree,
tool.getPath())) {
name = tool.getName();
break;
}
}
return name;
}
/**
* Is interactive merge (prompt enabled) ?
*
* @return is interactive (config prompt enabled) ?
*/
public boolean isInteractive() {
return config.isPrompt();
}
/**
* Get the default (gui-)tool name.
*
* @param gui
* use the diff.guitool setting ?
* @return the default tool name
*/
public String getDefaultToolName(boolean gui) {
return gui ? config.getDefaultGuiToolName()
: config.getDefaultToolName();
}
private ExternalMergeTool getTool(final String name) {
ExternalMergeTool tool = userDefinedTools.get(name);
if (tool == null) {
tool = predefinedTools.get(name);
}
return tool;
}
private void keepBackupFile(String mergedFilePath, FileElement backup)
throws IOException {
if (config.isKeepBackup()) {
Path backupPath = backup.getFile().toPath();
Files.move(backupPath,
backupPath.resolveSibling(
Paths.get(mergedFilePath).getFileName() + ".orig"), //$NON-NLS-1$
StandardCopyOption.REPLACE_EXISTING);
}
}
private Map<String, ExternalMergeTool> setupPredefinedTools() {
Map<String, ExternalMergeTool> tools = new TreeMap<>();
for (CommandLineMergeTool tool : CommandLineMergeTool.values()) {
tools.put(tool.name(), new PreDefinedMergeTool(tool));
}
return tools;
}
private Map<String, ExternalMergeTool> setupUserDefinedTools(
Map<String, ExternalMergeTool> predefTools) {
Map<String, ExternalMergeTool> tools = new TreeMap<>();
Map<String, ExternalMergeTool> userTools = config.getTools();
for (String name : userTools.keySet()) {
ExternalMergeTool userTool = userTools.get(name);
// if mergetool.<name>.cmd is defined we have user defined tool
if (userTool.getCommand() != null) {
tools.put(name, userTool);
} else if (userTool.getPath() != null) {
// if mergetool.<name>.path is defined we just overload the path
// of predefined tool
PreDefinedMergeTool predefTool = (PreDefinedMergeTool) predefTools
.get(name);
if (predefTool != null) {
predefTool.setPath(userTool.getPath());
if (userTool.getTrustExitCode() != BooleanTriState.UNSET) {
predefTool
.setTrustExitCode(userTool.getTrustExitCode());
}
}
}
}
return tools;
}
}
|