Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 938d997743e5c0afd8dd6bed1c0c29f5bc366d23 (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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*******************************************************************************
 * Copyright (c) 2000, 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.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.compare.patch.IFilePatchResult;
import org.eclipse.compare.patch.IHunk;
import org.eclipse.compare.patch.PatchConfiguration;
import org.eclipse.core.runtime.Assert;

/**
 * A Hunk describes a range of changed lines and some context lines.
 */
public class Hunk implements IHunk {
	private FilePatch2 fParent;
	private int fOldStart, fOldLength;
	private int fNewStart, fNewLength;
	private String[] fLines;
	private int hunkType;
	private String charset = null;

	public static Hunk createHunk(FilePatch2 parent, int[] oldRange, int[] newRange,
			List<String> lines, boolean hasLineAdditions, boolean hasLineDeletions, boolean hasContextLines) {
		int oldStart = 0;
		int oldLength = 0;
		int newStart = 0;
		int newLength = 0;
		if (oldRange[0] > 0)
			oldStart= oldRange[0]-1;	// line number start at 0!
		else
			oldStart= 0;
		oldLength= oldRange[1];
		if (newRange[0] > 0)
			newStart= newRange[0]-1;	// line number start at 0!
		else
			newStart= 0;
		newLength= newRange[1];
		int hunkType = FilePatch2.CHANGE;
		if (!hasContextLines) {
			if (hasLineAdditions && !hasLineDeletions) {
				hunkType = FilePatch2.ADDITION;
			} else if (!hasLineAdditions && hasLineDeletions) {
				hunkType = FilePatch2.DELETION;
			}
		}
		return new Hunk(parent, hunkType, oldStart, oldLength, newStart, newLength, lines.toArray(new String[lines.size()]));
	}

	public Hunk(FilePatch2 parent, int hunkType, int oldStart, int oldLength,
			int newStart, int newLength, String[] lines) {
		this.fParent = parent;
        if (this.fParent != null) {
            this.fParent.add(this);
        }
		this.hunkType = hunkType;
		this.fOldLength = oldLength;
		this.fOldStart = oldStart;
		this.fNewLength = newLength;
		this.fNewStart = newStart;
		this.fLines = lines;
	}

    public Hunk(FilePatch2 parent, Hunk toCopy) {
    	this(parent, toCopy.hunkType, toCopy.fOldStart, toCopy.fOldLength, toCopy.fNewStart, toCopy.fNewLength, toCopy.fLines);
    }

	/*
	 * Returns the contents of this hunk.
	 * Each line starts with a control character. Their meaning is as follows:
	 * <ul>
	 * <li>
	 * '+': add the line
	 * <li>
	 * '-': delete the line
	 * <li>
	 * ' ': no change, context line
	 * </ul>
	 */
	public String getContent() {
		StringBuilder sb= new StringBuilder();
		for (int i= 0; i < this.fLines.length; i++) {
			String line= this.fLines[i];
			sb.append(line.substring(0, LineReader.length(line)));
			sb.append('\n');
		}
		return sb.toString();
	}

	/*
	 * Returns a descriptive String for this hunk.
	 * It is in the form old_start,old_length -> new_start,new_length.
	 */
	String getDescription() {
		StringBuilder sb= new StringBuilder();
		sb.append(Integer.toString(this.fOldStart));
		sb.append(',');
		sb.append(Integer.toString(this.fOldLength));
		sb.append(" -> "); //$NON-NLS-1$
		sb.append(Integer.toString(this.fNewStart));
		sb.append(',');
		sb.append(Integer.toString(this.fNewLength));
		return sb.toString();
	}

	public String getRejectedDescription() {
		StringBuilder sb= new StringBuilder();
		sb.append("@@ -"); //$NON-NLS-1$
		sb.append(Integer.toString(this.fOldStart));
		sb.append(',');
		sb.append(Integer.toString(this.fOldLength));
		sb.append(" +"); //$NON-NLS-1$
		sb.append(Integer.toString(this.fNewStart));
		sb.append(',');
		sb.append(Integer.toString(this.fNewLength));
		sb.append(" @@"); //$NON-NLS-1$
		return sb.toString();
	}

	public int getHunkType(boolean reverse) {
		if (reverse) {
			if (this.hunkType == FilePatch2.ADDITION)
				return FilePatch2.DELETION;
			if (this.hunkType == FilePatch2.DELETION)
				return FilePatch2.ADDITION;
		}
		return this.hunkType;
	}

	void setHunkType(int hunkType) {
		this.hunkType = hunkType;
	}

	public String[] getLines() {
		return this.fLines;
	}

	@Override
	public String[] getUnifiedLines() {
		String[] ret = new String[this.fLines.length];
		System.arraycopy(this.fLines, 0, ret, 0, this.fLines.length);
		return ret;
	}

	/**
	 * Set the parent of this hunk. This method
	 * should only be invoked from {@link FilePatch2#add(Hunk)}
	 * @param diff the parent of this hunk
	 */
	void setParent(FilePatch2 diff) {
		if (this.fParent == diff)
			return;
		if (this.fParent != null)
			this.fParent.remove(this);
		this.fParent = diff;
	}

	public FilePatch2 getParent() {
		return this.fParent;
	}

	/*
	 * Tries to apply the given hunk on the specified lines.
	 * The parameter shift is added to the line numbers given
	 * in the hunk.
	 */
	public boolean tryPatch(PatchConfiguration configuration, List<String> lines, int shift, int fuzz) {
		boolean reverse = configuration.isReversed();
		int pos = getStart(reverse) + shift;
		List<String> contextLines = new ArrayList<>();
		boolean contextLinesMatched = true;
		boolean precedingLinesChecked = false;
		for (int i= 0; i < this.fLines.length; i++) {
			String s = this.fLines[i];
			Assert.isTrue(s.length() > 0);
			String line = s.substring(1);
			char controlChar = s.charAt(0);

			if (controlChar == ' ') {	// context lines

				if (pos < 0 || pos >= lines.size())
					return false;
				contextLines.add(line);
				if (linesMatch(configuration, line, lines.get(pos))) {
					pos++;
					continue;
				} else if (fuzz > 0) {
					// doesn't match, use the fuzz factor
					contextLinesMatched = false;
					pos++;
					continue;
				}
				return false;
			} else if (isDeletedDelimeter(controlChar, reverse)) {
				// deleted lines

				if (precedingLinesChecked && !contextLinesMatched && contextLines.size() > 0)
					// context lines inside hunk don't match
					return false;

				// check following context lines if exist
				// use the fuzz factor if needed
				if (!precedingLinesChecked
						&& !contextLinesMatched
						&& contextLines.size() >= fuzz
						&& !checkPrecedingContextLines(configuration, lines,
								fuzz, pos, contextLines))
					return false;
				// else if there is less or equal context line to the fuzz
				// factor we ignore them all and treat as matching

				precedingLinesChecked = true;
				contextLines.clear();
				contextLinesMatched = true;

				if (pos < 0 || pos >= lines.size()) // out of the file
					return false;
				if (linesMatch(configuration, line, lines.get(pos))) {
					pos++;
					continue; // line matched, continue with the next one
				}

				// We must remove all lines at once, return false if this
				// fails. In other words, all lines considered for deletion
				// must be found one by one.
				return false;
			} else if (isAddedDelimeter(controlChar, reverse)) {

				if (precedingLinesChecked && !contextLinesMatched && contextLines.size() > 0)
					return false;

				if (!precedingLinesChecked
						&& !contextLinesMatched
						&& contextLines.size() >= fuzz
						&& !checkPrecedingContextLines(configuration, lines,
								fuzz, pos, contextLines))
					return false;

				precedingLinesChecked = true;
				contextLines.clear();
				contextLinesMatched = true;

				// we don't have to do anything more for a 'try'
			} else
				Assert.isTrue(false, "tryPatch: unknown control character: " + controlChar); //$NON-NLS-1$
		}

		// check following context lines if exist
		if (!contextLinesMatched
				&& fuzz > 0
				&& contextLines.size() > fuzz
				&& !checkFollowingContextLines(configuration, lines, fuzz, pos,
						contextLines))
			return false;

		return true;
	}

	private boolean checkPrecedingContextLines(
			PatchConfiguration configuration, List<String> lines, int fuzz, int pos,
			List<String> contextLines) {
		// ignore from the beginning
		for (int j = fuzz; j < contextLines.size(); j++) {
			if (!linesMatch(configuration, contextLines.get(j),
							lines.get(pos - contextLines.size() + j)))
				return false;
		}
		return true;
	}

	private boolean checkFollowingContextLines(
			PatchConfiguration configuration, List<String> lines, int fuzz, int pos,
			List<String> contextLines) {
		if (!contextLines.isEmpty()) {
			// ignore from the end
			for (int j = 0; j < contextLines.size() - fuzz; j++) {
				if (!linesMatch(configuration, contextLines.get(j),
						lines.get(pos - contextLines.size() + j)))
					return false;
			}
		}
		return true;
	}

	public int getStart(boolean after) {
		if (after) {
			return this.fNewStart;
		}
		return this.fOldStart;
	}

	public void setStart(int start, boolean after) {
		if (after) {
			this.fNewStart = start;
		} else {
			this.fOldStart = start;
		}
	}

	public int getLength(boolean after) {
		if (after) {
			return this.fNewLength;
		}
		return this.fOldLength;
	}

	private int getShift(boolean reverse) {
		if (reverse) {
			return this.fOldLength - this.fNewLength;
		}
		return this.fNewLength - this.fOldLength;
	}

	int doPatch(PatchConfiguration configuration, List<String> lines, int shift, int fuzz) {
		boolean reverse = configuration.isReversed();
		int pos = getStart(reverse) + shift;
		List<String> contextLines = new ArrayList<>();
		boolean contextLinesMatched = true;
		boolean precedingLinesChecked = false;
		String lineDelimiter = getLineDelimiter(lines);

		for (int i= 0; i < this.fLines.length; i++) {
			String s= this.fLines[i];
			Assert.isTrue(s.length() > 0);
			String line= s.substring(1);
			char controlChar= s.charAt(0);
			if (controlChar == ' ') {
				// context lines
					Assert.isTrue(pos < lines.size(), "doPatch: inconsistency in context"); //$NON-NLS-1$
					contextLines.add(line);
					if (linesMatch(configuration, line, lines.get(pos))) {
						pos++;
						continue;
					} else if (fuzz > 0) {
						// doesn't match, use the fuzz factor
						contextLinesMatched = false;
						pos++;
						continue;
					}
					Assert.isTrue(false, "doPatch: context doesn't match"); //$NON-NLS-1$
//					pos++;
			} else if (isDeletedDelimeter(controlChar, reverse)) {
				// deleted lines
				if (precedingLinesChecked && !contextLinesMatched && contextLines.size() > 0)
					// context lines inside hunk don't match
					Assert.isTrue(false, "doPatch: context lines inside hunk don't match"); //$NON-NLS-1$

				// check following context lines if exist
				// use the fuzz factor if needed
				if (!precedingLinesChecked
						&& !contextLinesMatched
						&& contextLines.size() >= fuzz
						&& !checkPrecedingContextLines(configuration, lines,
								fuzz, pos, contextLines))
					Assert.isTrue(false, "doPatch: preceding context lines don't match, even though fuzz factor has been used"); //$NON-NLS-1$;
				// else if there is less or equal context line to the fuzz
				// factor we ignore them all and treat as matching

				precedingLinesChecked = true;
				contextLines.clear();
				contextLinesMatched = true;

				lines.remove(pos);
			} else if (isAddedDelimeter(controlChar, reverse)) {
				// added lines
				if (precedingLinesChecked && !contextLinesMatched && contextLines.size() > 0)
					Assert.isTrue(false, "doPatch: context lines inside hunk don't match"); //$NON-NLS-1$

				if (!precedingLinesChecked
						&& !contextLinesMatched
						&& contextLines.size() >= fuzz
						&& !checkPrecedingContextLines(configuration, lines,
								fuzz, pos, contextLines))
					Assert.isTrue(false, "doPatch: preceding context lines don't match, even though fuzz factor has been used"); //$NON-NLS-1$;

				precedingLinesChecked = true;
				contextLines.clear();
				contextLinesMatched = true;

				// if the line contains a delimiter, use a proper one
				if (line.length() > LineReader.length(line))
					line = line.substring(0, LineReader.length(line)) + lineDelimiter;

				if (getLength(reverse) == 0 && pos+1 < lines.size())
					lines.add(pos+1, line);
				else
					lines.add(pos, line);
				pos++;
			} else
				Assert.isTrue(false, "doPatch: unknown control character: " + controlChar); //$NON-NLS-1$
		}
		return getShift(reverse);
	}

	private boolean isDeletedDelimeter(char controlChar, boolean reverse) {
		return (!reverse && controlChar == '-') || (reverse && controlChar == '+');
	}

	private boolean isAddedDelimeter(char controlChar, boolean reverse) {
		return (reverse && controlChar == '-') || (!reverse && controlChar == '+');
	}

	/*
	 * Compares two strings.
	 * If fIgnoreWhitespace is true whitespace is ignored.
	 */
	private boolean linesMatch(PatchConfiguration configuration, String line1, String line2) {
		if (configuration.isIgnoreWhitespace())
			return stripWhiteSpace(line1).equals(stripWhiteSpace(line2));
		if (isIgnoreLineDelimiter()) {
			int l1= LineReader.length(line1);
			int l2= LineReader.length(line2);
			if (l1 != l2)
				return false;
			return line1.regionMatches(0, line2, 0, l1);
		}
		return line1.equals(line2);
	}

	private boolean isIgnoreLineDelimiter() {
		return true;
	}

	private String getLineDelimiter(List<String> lines) {
		if (lines.size() > 0) {
			// get a line separator from the file being patched
			String line0 = lines.get(0);
			return line0.substring(LineReader.length(line0));
		} else if (this.fLines.length > 0) {
			// if the file doesn't exist use a line separator from the patch
			return this.fLines[0].substring(LineReader.length(this.fLines[0]));
		}
		return System.getProperty("line.separator"); //$NON-NLS-1$
	}

	/*
	 * Returns the given string with all whitespace characters removed.
	 * Whitespace is defined by <code>Character.isWhitespace(...)</code>.
	 */
	private String stripWhiteSpace(String s) {
		StringBuilder sb= new StringBuilder();
		int l= s.length();
		for (int i= 0; i < l; i++) {
			char c= s.charAt(i);
			if (!Character.isWhitespace(c))
				sb.append(c);
		}
		return sb.toString();
	}

	public String getContents(boolean isAfterState, boolean reverse) {
		StringBuilder result= new StringBuilder();
		for (int i= 0; i<this.fLines.length; i++) {
			String line= this.fLines[i];
			String rest= line.substring(1);
			char c = line.charAt(0);
			if (c == ' ') {
				result.append(rest);
			} else if (isDeletedDelimeter(c, reverse) && !isAfterState) {
				result.append(rest);
			} else if (isAddedDelimeter(c, reverse) && isAfterState) {
				result.append(rest);
			}
		}
		return result.toString();
	}

	@Override
	public String getLabel() {
		return getDescription();
	}

	@Override
	public int getStartPosition() {
		return getStart(false);
	}

	@Override
	public InputStream getOriginalContents() {
		String contents = getContents(false, false);
		return asInputStream(contents);
	}

	@Override
	public InputStream getPatchedContents() {
		String contents = getContents(true, false);
		return asInputStream(contents);
	}

	private InputStream asInputStream(String contents) {
		String charSet = getCharset();
		return FileDiffResult.asInputStream(contents, charSet);
	}

	void setCharset(String charset) {
		this.charset = charset;
	}

	/**
	 * {@inheritDoc}
	 * @deprecated This method can be called before the first attempt to apply
	 *             the hunk when it is impossible to determine the encoding and
	 *             in this case it always returns null. Please see
	 *             {@link IFilePatchResult#getCharset()} as a proper way to
	 *             obtain charset.
	 */
	@Deprecated
	@Override
	public String getCharset() {
		return this.charset;
	}

}

Back to the top