Skip to main content
summaryrefslogtreecommitdiffstats
blob: ab64d83a3e488640dfe7075d47d72181ccf15cc0 (plain) (blame)
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
/*******************************************************************************
 * Copyright (c) 2006, 2011 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.compare.internal.core.patch;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.eclipse.compare.internal.core.ComparePlugin;
import org.eclipse.compare.internal.core.Messages;
import org.eclipse.compare.patch.IFilePatchResult;
import org.eclipse.compare.patch.IHunk;
import org.eclipse.compare.patch.PatchConfiguration;
import org.eclipse.compare.patch.ReaderCreator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.osgi.util.NLS;

public class FileDiffResult implements IFilePatchResult {
	private FilePatch2 fDiff;
	private boolean fMatches= false;
	private boolean fDiffProblem;
	private String fErrorMessage;
	private Map<Hunk, HunkResult> fHunkResults = new HashMap<>();
	private List<String> fBeforeLines, fAfterLines;
	private final PatchConfiguration configuration;
	private String charset;

	public FileDiffResult(FilePatch2 diff, PatchConfiguration configuration) {
		super();
		this.fDiff = diff;
		this.configuration = configuration;
	}

	public PatchConfiguration getConfiguration() {
		return this.configuration;
	}

	public boolean canApplyHunk(Hunk hunk) {
		HunkResult result = getHunkResult(hunk);
		return result.isOK() && !this.fDiffProblem;
	}

	/**
	 * Refreshes the state of the diff to {no matches, no problems} and checks to see what hunks contained
	 * by this Diff can actually be applied.
	 *
	 * Checks to see:
	 * 1) if the target file specified in fNewPath exists and is patchable
	 * 2) which hunks contained by this diff can actually be applied to the file
	 * @param content the contents being patched or <code>null</code> for an addition
	 * @param monitor a progress monitor or <code>null</code> if no progress monitoring is desired
	 */
	public void refresh(ReaderCreator content, IProgressMonitor monitor) {
		this.fMatches= false;
		this.fDiffProblem= false;
		boolean create= false;
		this.charset = Utilities.getCharset(content);
		//If this diff is an addition, make sure that it doesn't already exist
		boolean exists = targetExists(content);
		if (this.fDiff.getDiffType(getConfiguration().isReversed()) == FilePatch2.ADDITION) {
			if ((!exists || isEmpty(content)) && canCreateTarget(content)) {
				this.fMatches= true;
			} else {
				// file already exists
				this.fDiffProblem= true;
				this.fErrorMessage= Messages.FileDiffResult_0;
			}
			create= true;
		} else { //This diff is not an addition, try to find a match for it
			//Ensure that the file described by the path exists and is modifiable
			if (exists) {
				this.fMatches= true;
			} else {
				// file doesn't exist
				this.fDiffProblem= true;
				this.fErrorMessage= Messages.FileDiffResult_1;
			}
		}

		if (this.fDiffProblem) {
			// We couldn't find the target file or the patch is trying to add a
			// file that already exists but we need to initialize the hunk
			// results for display
			this.fBeforeLines = new ArrayList<>(getLines(content, false));
			this.fAfterLines = this.fMatches ? new ArrayList<>() : this.fBeforeLines;
			IHunk[] hunks = this.fDiff.getHunks();
			for (int i = 0; i < hunks.length; i++) {
				Hunk hunk = (Hunk) hunks[i];
				hunk.setCharset(getCharset());
				HunkResult result = getHunkResult(hunk);
				result.setMatches(false);
			}
		} else {
			// If this diff has no problems discovered so far, try applying the patch
			patch(getLines(content, create), monitor);
		}

		if (containsProblems()) {
			if (this.fMatches) {
				// Check to see if we have at least one hunk that matches
				this.fMatches = false;
				IHunk[] hunks = this.fDiff.getHunks();
				for (int i = 0; i < hunks.length; i++) {
					Hunk hunk = (Hunk) hunks[i];
					HunkResult result = getHunkResult(hunk);
					if (result.isOK()) {
						this.fMatches = true;
						break;
					}
				}
			}
		}
	}

	protected boolean canCreateTarget(ReaderCreator content) {
		return true;
	}

	protected boolean targetExists(ReaderCreator content) {
		return content != null && content.canCreateReader();
	}

	protected List<String> getLines(ReaderCreator content, boolean create) {
		List<String> lines = LineReader.load(content, create);
		return lines;
	}

	protected boolean isEmpty(ReaderCreator content) {
		if (content == null)
			return true;
		return LineReader.load(content, false).isEmpty();
	}

	/*
	 * Tries to patch the given lines with the specified Diff.
	 * Any hunk that couldn't be applied is returned in the list failedHunks.
	 */
	public void patch(List<String> lines, IProgressMonitor monitor) {
		this.fBeforeLines = new ArrayList<>();
		this.fBeforeLines.addAll(lines);
		if (getConfiguration().getFuzz() != 0) {
			calculateFuzz(this.fBeforeLines, monitor);
		}
		int shift= 0;
		IHunk[] hunks = this.fDiff.getHunks();
		for (int i = 0; i < hunks.length; i++) {
			Hunk hunk = (Hunk) hunks[i];
			hunk.setCharset(getCharset());
			HunkResult result = getHunkResult(hunk);
			result.setShift(shift);
			if (result.patch(lines)) {
				shift = result.getShift();
			}
		}
		this.fAfterLines = lines;
	}

	public boolean getDiffProblem() {
		return this.fDiffProblem;
	}

	/**
	 * Returns whether this Diff has any problems
	 * @return true if this Diff or any of its children Hunks have a problem, false if it doesn't
	 */
	public boolean containsProblems() {
		if (this.fDiffProblem)
			return true;
		for (Iterator<HunkResult> iterator = this.fHunkResults.values().iterator(); iterator.hasNext();) {
			HunkResult result = iterator.next();
			if (!result.isOK())
				return true;
		}
		return false;
	}

	public String getLabel() {
		String label= getTargetPath().toString();
		if (this.fDiffProblem)
			return NLS.bind(Messages.FileDiffResult_2, new String[] {label, this.fErrorMessage});
		return label;
	}

	@Override
	public boolean hasMatches() {
		return this.fMatches;
	}

	/**
	 * Return the lines of the target file with all matched hunks applied.
	 * @return the lines of the target file with all matched hunks applied
	 */
	public List<String> getLines() {
		return this.fAfterLines;
	}

	/**
	 * Calculate the fuzz factor that will allow the most hunks to be matched.
	 * @param lines the lines of the target file
	 * @param monitor a progress monitor
	 * @return the fuzz factor or <code>-1</code> if no hunks could be matched
	 */
	public int calculateFuzz(List<String> lines, IProgressMonitor monitor) {
		if (monitor == null)
			monitor = new NullProgressMonitor();
		this.fBeforeLines = new ArrayList<>(lines);
		// TODO: What about deletions?
		if (this.fDiff.getDiffType(getConfiguration().isReversed()) == FilePatch2.ADDITION) {
			// Additions don't need to adjust the fuzz factor
			// TODO: What about the after lines?
			return -1;
		}
		int shift= 0;
		int highestFuzz = -1; // the maximum fuzz factor for all hunks
		String name = getTargetPath() != null ? getTargetPath().lastSegment() : ""; //$NON-NLS-1$
		IHunk[] hunks = this.fDiff.getHunks();
		for (int j = 0; j < hunks.length; j++) {
			Hunk h = (Hunk) hunks[j];
			monitor.subTask(NLS.bind(Messages.FileDiffResult_3, new String[] {name, Integer.toString(j + 1)}));
			HunkResult result = getHunkResult(h);
			result.setShift(shift);
			int fuzz = result.calculateFuzz(lines, monitor);
			shift = result.getShift();
			if (fuzz > highestFuzz)
				highestFuzz = fuzz;
			monitor.worked(1);
		}
		this.fAfterLines = lines;
		return highestFuzz;
	}

	public IPath getTargetPath() {
		return this.fDiff.getStrippedPath(getConfiguration().getPrefixSegmentStripCount(), getConfiguration().isReversed());
	}

	private HunkResult getHunkResult(Hunk hunk) {
		HunkResult result = this.fHunkResults.get(hunk);
		if (result == null) {
			result = new HunkResult(this, hunk);
			this.fHunkResults.put(hunk, result);
		}
		return result;
	}

	public List<Hunk> getFailedHunks() {
		List<Hunk> failedHunks = new ArrayList<>();
		IHunk[] hunks = this.fDiff.getHunks();
		for (int i = 0; i < hunks.length; i++) {
			HunkResult result = this.fHunkResults.get(hunks[i]);
			if (result != null && !result.isOK())
				failedHunks.add(result.getHunk());
		}
		return failedHunks;
	}

	public FilePatch2 getDiff() {
		return this.fDiff;
	}

	public List<String> getBeforeLines() {
		return this.fBeforeLines;
	}

	public List<String> getAfterLines() {
		return this.fAfterLines;
	}

	public HunkResult[] getHunkResults() {
		// return hunk results in the same order as hunks are placed in file diff
		List<HunkResult> results = new ArrayList<>();
		IHunk[] hunks = this.fDiff.getHunks();
		for (int i = 0; i < hunks.length; i++) {
			HunkResult result = this.fHunkResults.get(hunks[i]);
			if (result != null) {
				results.add(result);
			}
		}
		return results.toArray(new HunkResult[results.size()]);
	}

	@Override
	public InputStream getOriginalContents() {
		String contents = LineReader.createString(isPreserveLineDelimeters(), getBeforeLines());
		return asInputStream(contents, getCharset());
	}

	@Override
	public InputStream getPatchedContents() {
		String contents = LineReader.createString(isPreserveLineDelimeters(), getLines());
		return asInputStream(contents, getCharset());
	}

	@Override
	public String getCharset() {
		return this.charset;
	}

	public boolean isPreserveLineDelimeters() {
		return false;
	}

	@Override
	public IHunk[] getRejects() {
		List<Hunk> failedHunks = getFailedHunks();
		return failedHunks.toArray(new IHunk[failedHunks.size()]);
	}

	@Override
	public boolean hasRejects() {
		return getFailedHunks().size() > 0;
	}

	public static InputStream asInputStream(String contents, String charSet) {
		byte[] bytes = null;
		if (charSet != null) {
			try {
				bytes = contents.getBytes(charSet);
			} catch (UnsupportedEncodingException e) {
				ComparePlugin.log(e);
			}
		}
		if (bytes == null) {
			bytes = contents.getBytes();
		}
		return new ByteArrayInputStream(bytes);
	}

}

Back to the top