Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 82b27b9d34a1dc0e83a1f14462ec88232b858ad5 (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
/*******************************************************************************
 *  Copyright (c) 2011, 2016 GitHub Inc. and others.
 *  All rights reserved. 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:
 *    Kevin Sawicki (GitHub Inc.) - initial API and implementation
 *    Tobias Pfeifer (SAP AG) - customizable font and color for the first header line - https://bugs.eclipse.org/397723
 *******************************************************************************/
package org.eclipse.egit.ui.internal.commit;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.egit.core.internal.CompareCoreUtils;
import org.eclipse.egit.ui.internal.UIText;
import org.eclipse.egit.ui.internal.commit.DiffRegionFormatter.DiffRegion.Type;
import org.eclipse.egit.ui.internal.history.FileDiff;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Region;
import org.eclipse.jgit.annotations.NonNull;
import org.eclipse.jgit.diff.DiffEntry;
import org.eclipse.jgit.diff.DiffEntry.ChangeType;
import org.eclipse.jgit.diff.DiffFormatter;
import org.eclipse.jgit.diff.EditList;
import org.eclipse.jgit.diff.RawText;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.osgi.util.NLS;

/**
 * Diff region formatter class that builds up a list of
 * {@link DiffRegion} instances as each {@link FileDiff} is being written to
 * an {@link IDocument}.
 */
public class DiffRegionFormatter extends DiffFormatter {

	/**
	 * A text {@link Region} describing an interesting region in a unified diff.
	 */
	public static class DiffRegion extends Region {

		/** Constant {@value} indicating that no line number exists. */
		public static final int NO_LINE = -1;

		/**
		 * The type of a {@link DiffRegion}.
		 */
		public enum Type {

			/** Added line. */
			ADD,

			/** Removed line. */
			REMOVE,

			/** Hunk line. */
			HUNK,

			/** Headline. */
			HEADLINE,

			/** Header (after HEADLINE). */
			HEADER,

			/** A context line in a hunk. */
			CONTEXT,

			/** Other line. */
			OTHER,

		}

		private final @NonNull Type type;

		private final int aLine;

		private final int bLine;

		/**
		 * @param offset
		 * @param length
		 */
		public DiffRegion(int offset, int length) {
			this(offset, length, NO_LINE, NO_LINE, Type.OTHER);
		}

		/**
		 * @param offset
		 * @param length
		 * @param aLine
		 * @param bLine
		 * @param type
		 */
		public DiffRegion(int offset, int length, int aLine, int bLine,
				@NonNull Type type) {
			super(offset, length);
			this.type = type;
			this.aLine = aLine;
			this.bLine = bLine;
		}

		/**
		 * @return the {@link Type} of the region
		 */
		public @NonNull Type getType() {
			return type;
		}

		/**
		 * Returns the first logical line number of the region.
		 *
		 * @param side
		 *            to get the line number of
		 * @return the line number; -1 indicates that the range has no line
		 *         number for the given side.
		 */
		public int getLine(@NonNull DiffEntry.Side side) {
			if (DiffEntry.Side.NEW.equals(side)) {
				return bLine;
			}
			return aLine;
		}

		@Override
		public boolean equals(Object object) {
			return super.equals(object);
		}

		@Override
		public int hashCode() {
			return super.hashCode();
		}
	}

	/**
	 * Region giving access to the {@link FileDiff} and its {@link Repository}
	 * that generated the content.
	 */
	public static class FileDiffRegion extends Region {

		private final FileDiff diff;

		private final Repository repository;

		/**
		 * Creates a new {@link FileDiffRegion}.
		 *
		 * @param repository
		 *            the {@link FileDiff} belongs to
		 * @param fileDiff
		 *            the range belongs to
		 * @param start
		 *            of the range
		 * @param length
		 *            of the range
		 */
		public FileDiffRegion(Repository repository, FileDiff fileDiff,
				int start, int length) {
			super(start, length);
			this.diff = fileDiff;
			this.repository = repository;
		}

		/**
		 * Retrieves the {@link FileDiff}.
		 *
		 * @return the {@link FileDiff}
		 */
		public FileDiff getDiff() {
			return diff;
		}

		/**
		 * Retrieves the {@link Repository}.
		 *
		 * @return the {@link Repository}
		 */
		public Repository getRepository() {
			return repository;
		}

		@Override
		public boolean equals(Object object) {
			return super.equals(object);
		}

		@Override
		public int hashCode() {
			return super.hashCode();
		}

		@Override
		public String toString() {
			return "[FileDiffRange " + (diff == null ? "null" : diff.getPath()) //$NON-NLS-1$ //$NON-NLS-2$
					+ ' ' + super.toString() + ']';
		}
	}

	private static class DocumentOutputStream extends OutputStream {

		private String charset;

		private IDocument document;

		private int offset;

		private StringBuilder lineBuffer = new StringBuilder();

		public DocumentOutputStream(IDocument document, int offset) {
			this.document = document;
			this.offset = offset;
		}

		private void write(String content) throws IOException {
			try {
				this.document.replace(this.offset, 0, content);
				this.offset += content.length();
			} catch (BadLocationException e) {
				throw new IOException(e.getMessage());
			}
		}

		@Override
		public void write(byte[] b, int off, int len) throws IOException {
			if (charset == null)
				lineBuffer.append(new String(b, off, len, "UTF-8")); //$NON-NLS-1$
			else
				lineBuffer.append(new String(b, off, len, charset));
		}

		@Override
		public void write(byte[] b) throws IOException {
			write(b, 0, b.length);
		}

		@Override
		public void write(int b) throws IOException {
			write(new byte[] { (byte) b });
		}

		@Override
		public void flush() throws IOException {
			flushLine();
		}

		protected void flushLine() throws IOException {
			if (lineBuffer.length() > 0) {
				write(lineBuffer.toString());
				lineBuffer.setLength(0);
			}
		}
	}

	private DocumentOutputStream stream;

	private List<DiffRegion> regions = new ArrayList<>();

	private List<FileDiffRegion> fileRegions = new ArrayList<>();

	private final int maxLines;

	private int linesWritten;

	private int lastNewLine;

	private int[] maximumLineNumbers = new int[] { DiffRegion.NO_LINE,
			DiffRegion.NO_LINE };

	/**
	 * @param document
	 * @param offset
	 */
	public DiffRegionFormatter(IDocument document, int offset) {
		this(document, offset, -1);
	}

	/**
	 * @param document
	 */
	public DiffRegionFormatter(IDocument document) {
		this(document, document.getLength(), -1);
	}

	/**
	 * @param document
	 * @param offset
	 * @param maxLines
	 */
	public DiffRegionFormatter(IDocument document, int offset,
			int maxLines) {
		super(new DocumentOutputStream(document, offset));
		this.stream = (DocumentOutputStream) getOutputStream();
		this.maxLines = maxLines;
		this.lastNewLine = DiffRegion.NO_LINE;
	}

	/**
	 * Write diff
	 *
	 * @param repository
	 * @param diff
	 * @return this formatter
	 * @throws IOException
	 */
	public DiffRegionFormatter write(Repository repository, FileDiff diff)
			throws IOException {
		this.stream.charset = CompareCoreUtils.getResourceEncoding(repository,
				diff.getPath());
		int start = stream.offset;
		diff.outputDiff(null, repository, this, true);
		flush();
		fileRegions
				.add(new FileDiffRegion(repository, diff, start,
						stream.offset - start));
		return this;
	}

	/**
	 * Get diff regions, sorted by offset
	 *
	 * @return non-null but possibly empty array
	 */
	public DiffRegion[] getRegions() {
		return this.regions.toArray(new DiffRegion[this.regions.size()]);
	}

	/**
	 * Gets the file diff regions, sorted by offset.
	 *
	 * @return the regions; non-null but possibly empty
	 */
	public FileDiffRegion[] getFileRegions() {
		return this.fileRegions
				.toArray(new FileDiffRegion[this.fileRegions.size()]);
	}

	/**
	 * Retrieves the maximum line numbers for hunk lines.
	 *
	 * @return an array with two elements, index 0 being the maximum old line
	 *         number and index 1 the maximum new line number
	 */
	public int[] getMaximumLineNumbers() {
		return maximumLineNumbers.clone();
	}

	/**
	 * Create and add a new {@link DiffRegion} without line number information,
	 * coalescing it with the previous region,if any, if that has the same type
	 * and the two regions are adjacent.
	 *
	 * @param type
	 *            the {@link Type}
	 * @param start
	 *            start offset
	 * @param end
	 *            end offset
	 * @return added range
	 */
	protected DiffRegion addRegion(@NonNull Type type, int start, int end) {
		return addRegion(type, start, end, DiffRegion.NO_LINE,
				DiffRegion.NO_LINE);
	}

	/**
	 * Create and add a new {@link DiffRegion}, coalescing it with the previous
	 * region,if any, if that has the same type and the two regions are
	 * adjacent.
	 *
	 * @param type
	 *            the {@link Type}
	 * @param start
	 *            start offset
	 * @param end
	 *            end offset
	 * @param aLine
	 *            line number in the old version, or {@link DiffRegion#NO_LINE}
	 * @param bLine
	 *            line number in the new version, or {@link DiffRegion#NO_LINE}
	 * @return added range
	 */
	protected DiffRegion addRegion(@NonNull Type type, int start, int end,
			int aLine, int bLine) {
		maximumLineNumbers[0] = Math.max(aLine, maximumLineNumbers[0]);
		maximumLineNumbers[1] = Math.max(bLine, maximumLineNumbers[1]);
		if (bLine != DiffRegion.NO_LINE) {
			lastNewLine = bLine;
		}
		if (!regions.isEmpty()) {
			DiffRegion last = regions.get(regions.size() - 1);
			if (last.getType().equals(type)
					&& start == last.getOffset() + last.getLength()) {
				regions.remove(regions.size() - 1);
				start = last.getOffset();
				aLine = last.getLine(DiffEntry.Side.OLD);
				bLine = last.getLine(DiffEntry.Side.NEW);
			}
		}
		DiffRegion range = new DiffRegion(start, end - start, aLine, bLine,
				type);
		regions.add(range);
		return range;
	}

	@Override
	protected void writeHunkHeader(int aStartLine, int aEndLine,
			int bStartLine, int bEndLine) throws IOException {
		int start = stream.offset;
		if (!regions.isEmpty()) {
			DiffRegion last = regions.get(regions.size() - 1);
			int lastEnd = last.getOffset() + last.getLength();
			if (last.getType().equals(Type.HEADLINE) && lastEnd < start) {
				addRegion(Type.HEADER, lastEnd, start);
			}
		}
		super.writeHunkHeader(aStartLine, aEndLine, bStartLine, bEndLine);
		stream.flushLine();
		addRegion(Type.HUNK, start, stream.offset);
		lastNewLine = bStartLine - 1;
	}

	@Override
	protected void writeLine(char prefix, RawText text, int cur)
			throws IOException {
		if (maxLines > 0 && linesWritten > maxLines) {
			if (linesWritten == maxLines + 1) {
				int start = stream.offset;
				stream.flushLine();
				stream.write(
						NLS.bind(UIText.DiffStyleRangeFormatter_diffTruncated,
								Integer.valueOf(maxLines)));
				stream.write("\n"); //$NON-NLS-1$
				addRegion(Type.HEADLINE, start, stream.offset);
				linesWritten++;
			}
			return;
		}

		int start = stream.offset;
		super.writeLine(prefix, text, cur);
		stream.flushLine();
		if (prefix == ' ') {
			addRegion(Type.CONTEXT, start, stream.offset, cur, ++lastNewLine);
		} else if (prefix == '+') {
			addRegion(Type.ADD, start, stream.offset, DiffRegion.NO_LINE, cur);

		} else {
			addRegion(Type.REMOVE, start, stream.offset, cur,
					DiffRegion.NO_LINE);
		}
		linesWritten++;
	}

	/**
	 * @see org.eclipse.jgit.diff.DiffFormatter#formatGitDiffFirstHeaderLine(ByteArrayOutputStream
	 *      o, ChangeType type, String oldPath, String newPath)
	 */
	@Override
	protected void formatGitDiffFirstHeaderLine(ByteArrayOutputStream o,
			final ChangeType type, final String oldPath, final String newPath)
			throws IOException {
		stream.flushLine();
		int offset = stream.offset;
		int start = o.size();
		super.formatGitDiffFirstHeaderLine(o, type, oldPath, newPath);
		int end = o.size();
		addRegion(Type.HEADLINE, offset + start, offset + end);
	}

	@Override
	public void format(final EditList edits, final RawText a, final RawText b)
			throws IOException {
		// Flush header before formatting of edits begin
		stream.flushLine();
		super.format(edits, a, b);
	}
}

Back to the top