View Javadoc
1   /*
2    * Copyright (C) 2009, Christian Halstrick <christian.halstrick@sap.com>
3    * Copyright (C) 2009, Johannes E. Schindelin
4    * Copyright (C) 2009, Johannes Schindelin <johannes.schindelin@gmx.de> and others
5    *
6    * This program and the accompanying materials are made available under the
7    * terms of the Eclipse Distribution License v. 1.0 which is available at
8    * https://www.eclipse.org/org/documents/edl-v10.php.
9    *
10   * SPDX-License-Identifier: BSD-3-Clause
11   */
12  
13  package org.eclipse.jgit.pgm;
14  
15  import static java.lang.Integer.valueOf;
16  import static org.eclipse.jgit.lib.Constants.HEAD;
17  import static org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH;
18  
19  import java.io.BufferedOutputStream;
20  import java.io.IOException;
21  import java.text.MessageFormat;
22  import java.util.List;
23  import java.util.concurrent.TimeUnit;
24  
25  import org.eclipse.jgit.diff.DiffAlgorithm;
26  import org.eclipse.jgit.diff.DiffAlgorithm.SupportedAlgorithm;
27  import org.eclipse.jgit.diff.DiffEntry;
28  import org.eclipse.jgit.diff.DiffFormatter;
29  import org.eclipse.jgit.diff.RawTextComparator;
30  import org.eclipse.jgit.diff.RenameDetector;
31  import org.eclipse.jgit.dircache.DirCacheIterator;
32  import org.eclipse.jgit.errors.RevisionSyntaxException;
33  import org.eclipse.jgit.lib.ObjectId;
34  import org.eclipse.jgit.lib.ObjectReader;
35  import org.eclipse.jgit.lib.Repository;
36  import org.eclipse.jgit.lib.TextProgressMonitor;
37  import org.eclipse.jgit.pgm.internal.CLIText;
38  import org.eclipse.jgit.pgm.opt.PathTreeFilterHandler;
39  import org.eclipse.jgit.treewalk.AbstractTreeIterator;
40  import org.eclipse.jgit.treewalk.CanonicalTreeParser;
41  import org.eclipse.jgit.treewalk.FileTreeIterator;
42  import org.eclipse.jgit.treewalk.filter.TreeFilter;
43  import org.eclipse.jgit.util.io.ThrowingPrintWriter;
44  import org.kohsuke.args4j.Argument;
45  import org.kohsuke.args4j.Option;
46  
47  @Command(common = true, usage = "usage_ShowDiffs")
48  class Diff extends TextBuiltin {
49  	private DiffFormatter diffFmt;
50  
51  	@Argument(index = 0, metaVar = "metaVar_treeish")
52  	private AbstractTreeIterator oldTree;
53  
54  	@Argument(index = 1, metaVar = "metaVar_treeish")
55  	private AbstractTreeIterator newTree;
56  
57  	@Option(name = "--cached", aliases = { "--staged" }, usage = "usage_cached")
58  	private boolean cached;
59  
60  	@Option(name = "--", metaVar = "metaVar_paths", handler = PathTreeFilterHandler.class)
61  	private TreeFilter pathFilter = TreeFilter.ALL;
62  
63  	// BEGIN -- Options shared with Log
64  	@Option(name = "-p", usage = "usage_showPatch")
65  	boolean showPatch;
66  
67  	@Option(name = "-M", usage = "usage_detectRenames")
68  	private Boolean detectRenames;
69  
70  	@Option(name = "--no-renames", usage = "usage_noRenames")
71  	void noRenames(@SuppressWarnings("unused") boolean on) {
72  		detectRenames = Boolean.FALSE;
73  	}
74  
75  	@Option(name = "--algorithm", metaVar = "metaVar_diffAlg", usage = "usage_diffAlgorithm")
76  	void setAlgorithm(SupportedAlgorithm s) {
77  		diffFmt.setDiffAlgorithm(DiffAlgorithm.getAlgorithm(s));
78  	}
79  
80  	@Option(name = "-l", usage = "usage_renameLimit")
81  	private Integer renameLimit;
82  
83  	@Option(name = "--name-status", usage = "usage_nameStatus")
84  	private boolean showNameAndStatusOnly;
85  
86  	@Option(name = "--ignore-space-at-eol")
87  	void ignoreSpaceAtEol(@SuppressWarnings("unused") boolean on) {
88  		diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_TRAILING);
89  	}
90  
91  	@Option(name = "--ignore-leading-space")
92  	void ignoreLeadingSpace(@SuppressWarnings("unused") boolean on) {
93  		diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_LEADING);
94  	}
95  
96  	@Option(name = "-b", aliases = { "--ignore-space-change" })
97  	void ignoreSpaceChange(@SuppressWarnings("unused") boolean on) {
98  		diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_CHANGE);
99  	}
100 
101 	@Option(name = "-w", aliases = { "--ignore-all-space" })
102 	void ignoreAllSpace(@SuppressWarnings("unused") boolean on) {
103 		diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
104 	}
105 
106 	@Option(name = "-U", aliases = { "--unified" }, metaVar = "metaVar_linesOfContext")
107 	void unified(int lines) {
108 		diffFmt.setContext(lines);
109 	}
110 
111 	@Option(name = "--abbrev", metaVar = "metaVar_n")
112 	void abbrev(int lines) {
113 		diffFmt.setAbbreviationLength(lines);
114 	}
115 
116 	@Option(name = "--full-index")
117 	void abbrev(@SuppressWarnings("unused") boolean on) {
118 		diffFmt.setAbbreviationLength(OBJECT_ID_STRING_LENGTH);
119 	}
120 
121 	@Option(name = "--src-prefix", metaVar = "metaVar_prefix", usage = "usage_srcPrefix")
122 	void sourcePrefix(String path) {
123 		diffFmt.setOldPrefix(path);
124 	}
125 
126 	@Option(name = "--dst-prefix", metaVar = "metaVar_prefix", usage = "usage_dstPrefix")
127 	void dstPrefix(String path) {
128 		diffFmt.setNewPrefix(path);
129 	}
130 
131 	@Option(name = "--no-prefix", usage = "usage_noPrefix")
132 	void noPrefix(@SuppressWarnings("unused") boolean on) {
133 		diffFmt.setOldPrefix(""); //$NON-NLS-1$
134 		diffFmt.setNewPrefix(""); //$NON-NLS-1$
135 	}
136 
137 	// END -- Options shared with Log
138 
139 	/** {@inheritDoc} */
140 	@Override
141 	protected void init(Repository repository, String gitDir) {
142 		super.init(repository, gitDir);
143 		diffFmt = new DiffFormatter(new BufferedOutputStream(outs));
144 	}
145 
146 	/** {@inheritDoc} */
147 	@Override
148 	protected void run() {
149 		diffFmt.setRepository(db);
150 		try {
151 			if (cached) {
152 				if (oldTree == null) {
153 					ObjectId head = db.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
154 					if (head == null) {
155 						die(MessageFormat.format(CLIText.get().notATree, HEAD));
156 					}
157 					CanonicalTreeParser p = new CanonicalTreeParser();
158 					try (ObjectReader reader = db.newObjectReader()) {
159 						p.reset(reader, head);
160 					}
161 					oldTree = p;
162 				}
163 				newTree = new DirCacheIterator(db.readDirCache());
164 			} else if (oldTree == null) {
165 				oldTree = new DirCacheIterator(db.readDirCache());
166 				newTree = new FileTreeIterator(db);
167 			} else if (newTree == null) {
168 				newTree = new FileTreeIterator(db);
169 			}
170 
171 			TextProgressMonitor pm = new TextProgressMonitor(errw);
172 			pm.setDelayStart(2, TimeUnit.SECONDS);
173 			diffFmt.setProgressMonitor(pm);
174 			diffFmt.setPathFilter(pathFilter);
175 			if (detectRenames != null) {
176 				diffFmt.setDetectRenames(detectRenames.booleanValue());
177 			}
178 			if (renameLimit != null && diffFmt.isDetectRenames()) {
179 				RenameDetector rd = diffFmt.getRenameDetector();
180 				rd.setRenameLimit(renameLimit.intValue());
181 			}
182 
183 			if (showNameAndStatusOnly) {
184 				nameStatus(outw, diffFmt.scan(oldTree, newTree));
185 				outw.flush();
186 			} else {
187 				diffFmt.format(oldTree, newTree);
188 				diffFmt.flush();
189 			}
190 		} catch (RevisionSyntaxException | IOException e) {
191 			throw die(e.getMessage(), e);
192 		} finally {
193 			diffFmt.close();
194 		}
195 	}
196 
197 	static void nameStatus(ThrowingPrintWriter out, List<DiffEntry> files)
198 			throws IOException {
199 		for (DiffEntry ent : files) {
200 			switch (ent.getChangeType()) {
201 			case ADD:
202 				out.println("A\t" + ent.getNewPath()); //$NON-NLS-1$
203 				break;
204 			case DELETE:
205 				out.println("D\t" + ent.getOldPath()); //$NON-NLS-1$
206 				break;
207 			case MODIFY:
208 				out.println("M\t" + ent.getNewPath()); //$NON-NLS-1$
209 				break;
210 			case COPY:
211 				out.format("C%1$03d\t%2$s\t%3$s", valueOf(ent.getScore()), // //$NON-NLS-1$
212 						ent.getOldPath(), ent.getNewPath());
213 				out.println();
214 				break;
215 			case RENAME:
216 				out.format("R%1$03d\t%2$s\t%3$s", valueOf(ent.getScore()), // //$NON-NLS-1$
217 						ent.getOldPath(), ent.getNewPath());
218 				out.println();
219 				break;
220 			}
221 		}
222 	}
223 }