View Javadoc
1   /*
2    * Copyright (C) 2011, Tomasz Zarna <Tomasz.Zarna@pl.ibm.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.api;
44  
45  import static org.eclipse.jgit.lib.Constants.HEAD;
46  
47  import java.io.BufferedOutputStream;
48  import java.io.IOException;
49  import java.io.OutputStream;
50  import java.util.List;
51  
52  import org.eclipse.jgit.api.errors.GitAPIException;
53  import org.eclipse.jgit.api.errors.JGitInternalException;
54  import org.eclipse.jgit.api.errors.NoHeadException;
55  import org.eclipse.jgit.diff.DiffEntry;
56  import org.eclipse.jgit.diff.DiffFormatter;
57  import org.eclipse.jgit.dircache.DirCacheIterator;
58  import org.eclipse.jgit.internal.JGitText;
59  import org.eclipse.jgit.lib.NullProgressMonitor;
60  import org.eclipse.jgit.lib.ObjectId;
61  import org.eclipse.jgit.lib.ObjectReader;
62  import org.eclipse.jgit.lib.ProgressMonitor;
63  import org.eclipse.jgit.lib.Repository;
64  import org.eclipse.jgit.treewalk.AbstractTreeIterator;
65  import org.eclipse.jgit.treewalk.CanonicalTreeParser;
66  import org.eclipse.jgit.treewalk.FileTreeIterator;
67  import org.eclipse.jgit.treewalk.filter.TreeFilter;
68  import org.eclipse.jgit.util.io.NullOutputStream;
69  
70  /**
71   * Show changes between commits, commit and working tree, etc.
72   *
73   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-diff.html"
74   *      >Git documentation about diff</a>
75   */
76  public class DiffCommand extends GitCommand<List<DiffEntry>> {
77  	private AbstractTreeIterator oldTree;
78  
79  	private AbstractTreeIterator newTree;
80  
81  	private boolean cached;
82  
83  	private TreeFilter pathFilter = TreeFilter.ALL;
84  
85  	private boolean showNameAndStatusOnly;
86  
87  	private OutputStream out;
88  
89  	private int contextLines = -1;
90  
91  	private String sourcePrefix;
92  
93  	private String destinationPrefix;
94  
95  	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
96  
97  	/**
98  	 * Constructor for DiffCommand
99  	 *
100 	 * @param repo
101 	 *            a {@link org.eclipse.jgit.lib.Repository} object.
102 	 */
103 	protected DiffCommand(Repository repo) {
104 		super(repo);
105 	}
106 
107 	/**
108 	 * {@inheritDoc}
109 	 * <p>
110 	 * Executes the {@code Diff} command with all the options and parameters
111 	 * collected by the setter methods (e.g. {@link #setCached(boolean)} of this
112 	 * class. Each instance of this class should only be used for one invocation
113 	 * of the command. Don't call this method twice on an instance.
114 	 */
115 	@Override
116 	public List<DiffEntry> call() throws GitAPIException {
117 		final DiffFormatter diffFmt;
118 		if (out != null && !showNameAndStatusOnly)
119 			diffFmt = new DiffFormatter(new BufferedOutputStream(out));
120 		else
121 			diffFmt = new DiffFormatter(NullOutputStream.INSTANCE);
122 		diffFmt.setRepository(repo);
123 		diffFmt.setProgressMonitor(monitor);
124 		try {
125 			if (cached) {
126 				if (oldTree == null) {
127 					ObjectId head = repo.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
128 					if (head == null)
129 						throw new NoHeadException(JGitText.get().cannotReadTree);
130 					CanonicalTreeParser p = new CanonicalTreeParser();
131 					try (ObjectReader reader = repo.newObjectReader()) {
132 						p.reset(reader, head);
133 					}
134 					oldTree = p;
135 				}
136 				newTree = new DirCacheIterator(repo.readDirCache());
137 			} else {
138 				if (oldTree == null)
139 					oldTree = new DirCacheIterator(repo.readDirCache());
140 				if (newTree == null)
141 					newTree = new FileTreeIterator(repo);
142 			}
143 
144 			diffFmt.setPathFilter(pathFilter);
145 
146 			List<DiffEntry> result = diffFmt.scan(oldTree, newTree);
147 			if (showNameAndStatusOnly)
148 				return result;
149 			else {
150 				if (contextLines >= 0)
151 					diffFmt.setContext(contextLines);
152 				if (destinationPrefix != null)
153 					diffFmt.setNewPrefix(destinationPrefix);
154 				if (sourcePrefix != null)
155 					diffFmt.setOldPrefix(sourcePrefix);
156 				diffFmt.format(result);
157 				diffFmt.flush();
158 				return result;
159 			}
160 		} catch (IOException e) {
161 			throw new JGitInternalException(e.getMessage(), e);
162 		} finally {
163 			diffFmt.close();
164 		}
165 	}
166 
167 	/**
168 	 * Whether to view the changes staged for the next commit
169 	 *
170 	 * @param cached
171 	 *            whether to view the changes staged for the next commit
172 	 * @return this instance
173 	 */
174 	public DiffCommand setCached(boolean cached) {
175 		this.cached = cached;
176 		return this;
177 	}
178 
179 	/**
180 	 * Set path filter
181 	 *
182 	 * @param pathFilter
183 	 *            parameter, used to limit the diff to the named path
184 	 * @return this instance
185 	 */
186 	public DiffCommand setPathFilter(TreeFilter pathFilter) {
187 		this.pathFilter = pathFilter;
188 		return this;
189 	}
190 
191 	/**
192 	 * Set old tree
193 	 *
194 	 * @param oldTree
195 	 *            the previous state
196 	 * @return this instance
197 	 */
198 	public DiffCommand setOldTree(AbstractTreeIterator oldTree) {
199 		this.oldTree = oldTree;
200 		return this;
201 	}
202 
203 	/**
204 	 * Set new tree
205 	 *
206 	 * @param newTree
207 	 *            the updated state
208 	 * @return this instance
209 	 */
210 	public DiffCommand setNewTree(AbstractTreeIterator newTree) {
211 		this.newTree = newTree;
212 		return this;
213 	}
214 
215 	/**
216 	 * Set whether to return only names and status of changed files
217 	 *
218 	 * @param showNameAndStatusOnly
219 	 *            whether to return only names and status of changed files
220 	 * @return this instance
221 	 */
222 	public DiffCommand setShowNameAndStatusOnly(boolean showNameAndStatusOnly) {
223 		this.showNameAndStatusOnly = showNameAndStatusOnly;
224 		return this;
225 	}
226 
227 	/**
228 	 * Set output stream
229 	 *
230 	 * @param out
231 	 *            the stream to write line data
232 	 * @return this instance
233 	 */
234 	public DiffCommand setOutputStream(OutputStream out) {
235 		this.out = out;
236 		return this;
237 	}
238 
239 	/**
240 	 * Set number of context lines instead of the usual three.
241 	 *
242 	 * @param contextLines
243 	 *            the number of context lines
244 	 * @return this instance
245 	 */
246 	public DiffCommand setContextLines(int contextLines) {
247 		this.contextLines = contextLines;
248 		return this;
249 	}
250 
251 	/**
252 	 * Set the given source prefix instead of "a/".
253 	 *
254 	 * @param sourcePrefix
255 	 *            the prefix
256 	 * @return this instance
257 	 */
258 	public DiffCommand setSourcePrefix(String sourcePrefix) {
259 		this.sourcePrefix = sourcePrefix;
260 		return this;
261 	}
262 
263 	/**
264 	 * Set the given destination prefix instead of "b/".
265 	 *
266 	 * @param destinationPrefix
267 	 *            the prefix
268 	 * @return this instance
269 	 */
270 	public DiffCommand setDestinationPrefix(String destinationPrefix) {
271 		this.destinationPrefix = destinationPrefix;
272 		return this;
273 	}
274 
275 	/**
276 	 * The progress monitor associated with the diff operation. By default, this
277 	 * is set to <code>NullProgressMonitor</code>
278 	 *
279 	 * @see NullProgressMonitor
280 	 * @param monitor
281 	 *            a progress monitor
282 	 * @return this instance
283 	 */
284 	public DiffCommand setProgressMonitor(ProgressMonitor monitor) {
285 		if (monitor == null) {
286 			monitor = NullProgressMonitor.INSTANCE;
287 		}
288 		this.monitor = monitor;
289 		return this;
290 	}
291 }