Skip to main content
summaryrefslogtreecommitdiffstats
blob: 35cd6fba810dfd81409c0f455d04e2e0ae84d287 (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
/*******************************************************************************
 * Copyright (c) 2009 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Krzysztof Poglodzinski (intuicje@gmail.com) - initial API and implementation
 *     Mariusz Tanski (mariusztanski@gmail.com) - initial API and implementation
 *     Kacper Zdanowicz (kacper.zdanowicz@gmail.com) - initial API and implementation
 *     IBM Corportation - initial API and implementation
 *******************************************************************************/
package org.eclipse.compare.internal;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.eclipse.compare.internal.merge.DocumentMerger.Diff;
import org.eclipse.compare.rangedifferencer.RangeDifference;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Display;

import com.ibm.icu.text.DateFormat;

public class UnifiedDiffFormatter {

	private static final char RIGHT_CONTRIBUTOR = 'R';
	private static final char LEFT_CONTRIBUTOR = 'L';

	private final static int NUMBER_OF_CONTEXT_LINES = 3;

	public static final String INDEX_MARKER = "Index: "; //$NON-NLS-1$
	public static final String DELIMITER = "==================================================================="; //$NON-NLS-1$
	public static final String OLD_FILE_PREFIX = "--- "; //$NON-NLS-1$
	public static final String NEW_FILE_PREFIX = "+++ "; //$NON-NLS-1$
	public static final String OLD_LINE_PREFIX = "-"; //$NON-NLS-1$
	public static final String NEW_LINE_PREFIX = "+"; //$NON-NLS-1$
	public static final String CONTEXT_LINE_PREFIX = " "; //$NON-NLS-1$
	public static final String RANGE_INFORMATION_PREFIX = "@@ -"; //$NON-NLS-1$
	public static final String RANGE_INFORMATION_AFFIX = " @@"; //$NON-NLS-1$

	private List fAllDiffs;
	private IDocument leftDoc;
	private IDocument rightDoc;
	private String oldPath;
	private String newPath;
	private boolean rightToLeft;

	public UnifiedDiffFormatter(List allDiffs, IDocument leftDoc,
			IDocument rightDoc, String oldPath, String newPath,
			boolean rightToLeft) {
		this.fAllDiffs = allDiffs;
		this.leftDoc = leftDoc;
		this.rightDoc = rightDoc;
		this.oldPath = oldPath;
		this.newPath = newPath;
		this.rightToLeft = rightToLeft;
	}

	/**
	 * Generates diff and writes it into the clipboard.
	 * 
	 * GNU diff command has default line format different than Eclipse has.
	 * This issue is the subject of bug 259636.
	 * 
	 * @throws IOException
	 */
	public void generateDiffToClipboard() throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(bos);

		generateDiff(ps);
		ps.close();

		TextTransfer plainTextTransfer = TextTransfer.getInstance();
		Clipboard clipboard = new Clipboard(Display.getDefault());
		clipboard.setContents(new String[] { bos.toString() },
				new Transfer[] { plainTextTransfer });
		clipboard.dispose();
		bos.close();
	}

	/**
	 * Generates diff and writes it into the given file.
	 * 
	 * GNU diff command has default line format different than Eclipse has.
	 * This issue is the subject of bug 259636.
	 * 
	 * @param file file where diff will be written
	 * @throws IOException
	 */
	public void generateDiff(File file) throws IOException {
		FileOutputStream fos = null;
		PrintStream ps = null;
		try {
			fos = new FileOutputStream(file);
			try {
				ps = new PrintStream(fos);
				generateDiff(ps);
				if (ps.checkError()) {
					throw new IOException("Error while writing patch file: " //$NON-NLS-1$
							+ file);
				}
			} finally {
				if (ps != null) {
					ps.close();
				}
			}
		} finally {
			if (fos != null) {
				fos.close();
			}
		}
	}

	/**
	 * Generates diff and writes it into the given output.
	 * 
	 * GNU diff command has default line format different than Eclipse has.
	 * This issue is the subject of bug 259636.
	 * 
	 * @param output output to which diff will be written
	 */
	private void generateDiff(PrintStream output) {
		generateDiff(output, false);
	}

	/**
	 * Generates diff in the specified format and writes it into the given output.
	 * 
	 * GNU diff command has default line format different than Eclipse has.
	 * This issue is the subject of bug 259636.
	 * 
	 * @param output output to which diff will be written
	 * @param strictUnixFormat determinates if the format should be fully compatible with the Unix one.
	 */
	private void generateDiff(PrintStream output, boolean strictUnixFormat) {
		// If the first block isn't the only one, or first block is different
		if (fAllDiffs.size() > 1 || isPartDifferent(0)) {
			output.println(INDEX_MARKER + oldPath);
			output.println(DELIMITER);
			Date oldDate = Calendar.getInstance().getTime();
			Date newDate = Calendar.getInstance().getTime();
			String oldDateFormat = DateFormat.getDateTimeInstance().format(oldDate);
			String newDateFormat = DateFormat.getDateTimeInstance().format(newDate);
			output.println(OLD_FILE_PREFIX + oldPath + '\t'
					+ oldDateFormat + " -0000"); //$NON-NLS-1$
			output.println(NEW_FILE_PREFIX + newPath + '\t'
					+ newDateFormat + " -0000"); //$NON-NLS-1$

			boolean firstHunk = true;
			Hunk currentHunk = null;

			int currentLineNumberOld = 0;
			int currentLineNumberNew = 0;

			for (int i = 0; i < fAllDiffs.size(); i++) {

				List oldPart = getPart(i, LEFT_CONTRIBUTOR);
				List newPart = getPart(i, RIGHT_CONTRIBUTOR);

				if (isPartDifferent(i)) {
					// This part has some changes
					if (firstHunk) {
						// Hunk will start with changed block
						currentHunk = new Hunk(0, 0, strictUnixFormat);
						firstHunk = false;
					}
					if (i == (fAllDiffs.size() - 1)) {
						// If it is the last part
						currentHunk.addPartRangeToOld(oldPart, 0, oldPart
								.size(), true);
						currentHunk.addPartRangeToNew(newPart, 0, newPart
								.size(), true);
					} else {
						currentHunk.addPartRangeToOld(oldPart, 0, oldPart
								.size(), false);
						currentHunk.addPartRangeToNew(newPart, 0, newPart
								.size(), false);
					}
				} else {
					if (firstHunk) {
						// Hunk will start with context
						currentHunk = new Hunk((oldPart.size() - 1) - NUMBER_OF_CONTEXT_LINES,
								(oldPart.size() - 1) - NUMBER_OF_CONTEXT_LINES, strictUnixFormat);
						firstHunk = false;
						currentHunk.addPartRangeToBoth(oldPart,
								(oldPart.size() - 1) - NUMBER_OF_CONTEXT_LINES, oldPart.size(), false);
					} else {
						if (i == (fAllDiffs.size() - 1)) {
							// If it is the last part
							currentHunk.addPartRangeToBoth(oldPart, 0, NUMBER_OF_CONTEXT_LINES, true);
						} else {
							if (oldPart.size() - 1 < 2*NUMBER_OF_CONTEXT_LINES) {
								// Context too short to start new hunk
								currentHunk.addPartRangeToBoth(oldPart, 0,
										oldPart.size(), false);
							} else {
								// Context long enough to start new hunk
								currentHunk.addPartRangeToBoth(oldPart, 0, NUMBER_OF_CONTEXT_LINES,
										false);
								currentHunk.printTo(output);
								currentHunk = new Hunk(currentLineNumberOld
										+ (oldPart.size() - 1) - NUMBER_OF_CONTEXT_LINES,
										currentLineNumberNew + (oldPart.size() - 1)
										- NUMBER_OF_CONTEXT_LINES, strictUnixFormat);
								currentHunk.addPartRangeToBoth(oldPart,
										(oldPart.size() - 1) - NUMBER_OF_CONTEXT_LINES,
										oldPart.size(), false);
							}
						}
					}
				}
				currentLineNumberOld += oldPart.size();
				currentLineNumberNew += newPart.size();
			}
			// Print the last hunk
			currentHunk.printTo(output);
		}
	}

	private List getPart(int i, char side) {
		try {
			String s = extract(i, side).replaceAll("\r\n", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
			s.replaceAll("\r", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
			List diffLines = new ArrayList(Arrays
					.asList(s.split("\n", -1))); //$NON-NLS-1$
			return diffLines;
		} catch (BadLocationException e) {
			CompareUIPlugin.log(e);
		}
		return null;
	}

	private String extract(int i, char side) throws BadLocationException {
		Diff diff = ((Diff) fAllDiffs.get(i));
		if (side == LEFT_CONTRIBUTOR && !rightToLeft
				|| side == RIGHT_CONTRIBUTOR && rightToLeft) {
			return leftDoc.get(diff.getPosition(LEFT_CONTRIBUTOR).offset, diff
					.getPosition(LEFT_CONTRIBUTOR).length);
		}
		return rightDoc.get(diff.getPosition(RIGHT_CONTRIBUTOR).offset, diff
				.getPosition(RIGHT_CONTRIBUTOR).length);
	}

	private boolean isPartDifferent(int i) {
		Diff diff = ((Diff) fAllDiffs.get(i));
		if (diff.getKind() == RangeDifference.CHANGE) {
			return true;
		}
		return false;
	}

	private class Hunk {
		private int oldStart;
		private int oldLength;
		private int newStart;
		private int newLength;
		private boolean strictUnixFormat;
		private boolean printNoNewlineMarker;
		List lines;

		public Hunk(int oldStart, int newStart, boolean strictUnixFormat) {
			if (oldStart < 0)
				oldStart = 0;
			if (newStart < 0)
				newStart = 0;
			this.oldStart = oldStart;
			this.newStart = newStart;
			this.oldLength = 0;
			this.newLength = 0;
			this.strictUnixFormat = strictUnixFormat;
			printNoNewlineMarker = false;
			lines = new ArrayList();
		}

		public void addPartRangeToOld(List part, int start, int end,
				boolean lastPart) {
			if (start < 0)
				start = 0;
			if (strictUnixFormat) {
				//in strictUnixFormat, if last line ends with newline character
				//add additional empty line
				if ((lastPart) && part.size() != 1)
					end = Math.min(end, part.size());
				else
					end = Math.min(end, part.size() - 1);
				for (int lineNr = start; lineNr < end; lineNr++) {
					lines.add(OLD_LINE_PREFIX + part.get(lineNr));
					oldLength++;
				}
			}
			else {
				//in not strictUnixFormat, if last line doesn't end with newline character
				//add an marker saying about this
				end = Math.min(end, part.size() - 1);
				for (int lineNr = start; lineNr < end; lineNr++) {
					lines.add(OLD_LINE_PREFIX + part.get(lineNr));
					oldLength++;
				}
				if (!part.get(part.size() - 1).toString().equals(""))	//$NON-NLS-1$
				{
					//part doesn't end with newline character
					//don't cut the last line, because it isn't empty
					lines.add(OLD_LINE_PREFIX + part.get(part.size() - 1));
					oldLength++;
					printNoNewlineMarker = true;
				}
			}
		}

		public void addPartRangeToNew(List part, int start, int end,
				boolean lastPart) {
			if (start < 0)
				start = 0;
			if (strictUnixFormat) {
				//in strictUnixFormat, if last line ends with newline character
				//add additional empty line
				if ((lastPart) && part.size() != 1)
					end = Math.min(end, part.size());
				else
					end = Math.min(end, part.size() - 1);
				for (int lineNr = start; lineNr < end; lineNr++) {
					lines.add(NEW_LINE_PREFIX + part.get(lineNr));
					newLength++;
				}
			}
			else {
				//in not strictUnixFormat, if last line doesn't end with newline character
				//add an marker saying about this
				end = Math.min(end, part.size() - 1);
				for (int lineNr = start; lineNr < end; lineNr++) {
					lines.add(NEW_LINE_PREFIX + part.get(lineNr));
					newLength++;
				}
				if (!part.get(part.size() - 1).toString().equals("")) {	//$NON-NLS-1$
					//part doesn't end with newline character
					//don't cut the last line, because it isn't empty
					lines.add(NEW_LINE_PREFIX + part.get(part.size() - 1));
					newLength++;
					printNoNewlineMarker = true;
				}
			}
		}

		public void addPartRangeToBoth(List part, int start, int end,
				boolean lastPart) {
			if (start < 0)
				start = 0;
			if (strictUnixFormat) {
				//in strictUnixFormat, if last line ends with newline character
				//add additional empty line
				if (lastPart)
					end = Math.min(end, part.size());
				else
					end = Math.min(end, part.size() - 1);
				for (int lineNr = start; lineNr < end; lineNr++) {
					lines.add(CONTEXT_LINE_PREFIX + part.get(lineNr));
					oldLength++;
					newLength++;
				}
			}
			else {
				//in not strictUnixFormat, if last line doesn't end with newline character
				//add an marker saying about this
				end = Math.min(end, part.size() - 1);
				for (int lineNr = start; lineNr < end; lineNr++) {
					lines.add(CONTEXT_LINE_PREFIX + part.get(lineNr));
					oldLength++;
					newLength++;
				}
				if (!part.get(part.size() - 1).toString().equals("")) {	//$NON-NLS-1$
					//part doesn't end with newline character
					//don't cut the last line, because it isn't empty
					lines.add(CONTEXT_LINE_PREFIX + part.get(part.size() - 1));
					oldLength++;
					newLength++;
					printNoNewlineMarker = true;
				}
			}
		}

		private void printMarkerTo(PrintStream output) {
			if (oldLength == 0)
			{
				//all lines are new lines
				oldStart = -1;
			}
			if (newLength == 0) {
				//all lines are old lines
				newStart = -1;
			}
			output.println(RANGE_INFORMATION_PREFIX + (oldStart+1) + "," + oldLength + " +" + (newStart+1) //$NON-NLS-1$ //$NON-NLS-2$
					+ "," + newLength + RANGE_INFORMATION_AFFIX); //$NON-NLS-1$
		}

		public void printTo(PrintStream output) {
			printMarkerTo(output);
			for (int i = 0; i < lines.size(); i++) {
				output.println(lines.get(i));
			}
			if (printNoNewlineMarker) {
				output.println("\\ No newline at end of file");	//$NON-NLS-1$
			}
		}
	}

}

Back to the top