View Javadoc
1   /*
2    * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.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.RefDatabase.ALL;
46  
47  import java.io.IOException;
48  import java.text.MessageFormat;
49  import java.util.ArrayList;
50  import java.util.List;
51  import java.util.Map;
52  
53  import org.eclipse.jgit.api.errors.GitAPIException;
54  import org.eclipse.jgit.api.errors.JGitInternalException;
55  import org.eclipse.jgit.api.errors.NoHeadException;
56  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
57  import org.eclipse.jgit.errors.MissingObjectException;
58  import org.eclipse.jgit.internal.JGitText;
59  import org.eclipse.jgit.lib.AnyObjectId;
60  import org.eclipse.jgit.lib.Constants;
61  import org.eclipse.jgit.lib.ObjectId;
62  import org.eclipse.jgit.lib.Ref;
63  import org.eclipse.jgit.lib.Repository;
64  import org.eclipse.jgit.revwalk.RevCommit;
65  import org.eclipse.jgit.revwalk.RevWalk;
66  import org.eclipse.jgit.revwalk.filter.AndRevFilter;
67  import org.eclipse.jgit.revwalk.filter.MaxCountRevFilter;
68  import org.eclipse.jgit.revwalk.filter.SkipRevFilter;
69  import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
70  import org.eclipse.jgit.treewalk.filter.PathFilter;
71  import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
72  import org.eclipse.jgit.treewalk.filter.TreeFilter;
73  
74  /**
75   * A class used to execute a {@code Log} command. It has setters for all
76   * supported options and arguments of this command and a {@link #call()} method
77   * to finally execute the command. Each instance of this class should only be
78   * used for one invocation of the command (means: one call to {@link #call()})
79   * <p>
80   * Examples (<code>git</code> is a {@link Git} instance):
81   * <p>
82   * Get newest 10 commits, starting from the current branch:
83   *
84   * <pre>
85   * ObjectId head = repository.resolve(Constants.HEAD);
86   *
87   * Iterable&lt;RevCommit&gt; commits = git.log().add(head).setMaxCount(10).call();
88   * </pre>
89   * <p>
90   *
91   * <p>
92   * Get commits only for a specific file:
93   *
94   * <pre>
95   * git.log().add(head).addPath(&quot;dir/filename.txt&quot;).call();
96   * </pre>
97   * <p>
98   *
99   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-log.html"
100  *      >Git documentation about Log</a>
101  */
102 public class LogCommand extends GitCommand<Iterable<RevCommit>> {
103 	private RevWalk walk;
104 
105 	private boolean startSpecified = false;
106 
107 	private final List<PathFilter> pathFilters = new ArrayList<PathFilter>();
108 
109 	private int maxCount = -1;
110 
111 	private int skip = -1;
112 
113 	/**
114 	 * @param repo
115 	 */
116 	protected LogCommand(Repository repo) {
117 		super(repo);
118 		walk = new RevWalk(repo);
119 	}
120 
121 	/**
122 	 * Executes the {@code Log} command with all the options and parameters
123 	 * collected by the setter methods (e.g. {@link #add(AnyObjectId)},
124 	 * {@link #not(AnyObjectId)}, ..) of this class. Each instance of this class
125 	 * should only be used for one invocation of the command. Don't call this
126 	 * method twice on an instance.
127 	 *
128 	 * @return an iteration over RevCommits
129 	 * @throws NoHeadException
130 	 *             of the references ref cannot be resolved
131 	 */
132 	public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
133 		checkCallable();
134 		if (pathFilters.size() > 0)
135 			walk.setTreeFilter(AndTreeFilter.create(
136 					PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));
137 		if (skip > -1 && maxCount > -1)
138 			walk.setRevFilter(AndRevFilter.create(SkipRevFilter.create(skip),
139 					MaxCountRevFilter.create(maxCount)));
140 		else if (skip > -1)
141 			walk.setRevFilter(SkipRevFilter.create(skip));
142 		else if (maxCount > -1)
143 			walk.setRevFilter(MaxCountRevFilter.create(maxCount));
144 		if (!startSpecified) {
145 			try {
146 				ObjectId headId = repo.resolve(Constants.HEAD);
147 				if (headId == null)
148 					throw new NoHeadException(
149 							JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
150 				add(headId);
151 			} catch (IOException e) {
152 				// all exceptions thrown by add() shouldn't occur and represent
153 				// severe low-level exception which are therefore wrapped
154 				throw new JGitInternalException(
155 						JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD,
156 						e);
157 			}
158 		}
159 		setCallable(false);
160 		return walk;
161 	}
162 
163 	/**
164 	 * Mark a commit to start graph traversal from.
165 	 *
166 	 * @see RevWalk#markStart(RevCommit)
167 	 * @param start
168 	 * @return {@code this}
169 	 * @throws MissingObjectException
170 	 *             the commit supplied is not available from the object
171 	 *             database. This usually indicates the supplied commit is
172 	 *             invalid, but the reference was constructed during an earlier
173 	 *             invocation to {@link RevWalk#lookupCommit(AnyObjectId)}.
174 	 * @throws IncorrectObjectTypeException
175 	 *             the object was not parsed yet and it was discovered during
176 	 *             parsing that it is not actually a commit. This usually
177 	 *             indicates the caller supplied a non-commit SHA-1 to
178 	 *             {@link RevWalk#lookupCommit(AnyObjectId)}.
179 	 * @throws JGitInternalException
180 	 *             a low-level exception of JGit has occurred. The original
181 	 *             exception can be retrieved by calling
182 	 *             {@link Exception#getCause()}. Expect only
183 	 *             {@code IOException's} to be wrapped. Subclasses of
184 	 *             {@link IOException} (e.g. {@link MissingObjectException}) are
185 	 *             typically not wrapped here but thrown as original exception
186 	 */
187 	public LogCommand add(AnyObjectId start) throws MissingObjectException,
188 			IncorrectObjectTypeException {
189 		return add(true, start);
190 	}
191 
192 	/**
193 	 * Same as {@code --not start}, or {@code ^start}
194 	 *
195 	 * @param start
196 	 * @return {@code this}
197 	 * @throws MissingObjectException
198 	 *             the commit supplied is not available from the object
199 	 *             database. This usually indicates the supplied commit is
200 	 *             invalid, but the reference was constructed during an earlier
201 	 *             invocation to {@link RevWalk#lookupCommit(AnyObjectId)}.
202 	 * @throws IncorrectObjectTypeException
203 	 *             the object was not parsed yet and it was discovered during
204 	 *             parsing that it is not actually a commit. This usually
205 	 *             indicates the caller supplied a non-commit SHA-1 to
206 	 *             {@link RevWalk#lookupCommit(AnyObjectId)}.
207 	 * @throws JGitInternalException
208 	 *             a low-level exception of JGit has occurred. The original
209 	 *             exception can be retrieved by calling
210 	 *             {@link Exception#getCause()}. Expect only
211 	 *             {@code IOException's} to be wrapped. Subclasses of
212 	 *             {@link IOException} (e.g. {@link MissingObjectException}) are
213 	 *             typically not wrapped here but thrown as original exception
214 	 */
215 	public LogCommand not(AnyObjectId start) throws MissingObjectException,
216 			IncorrectObjectTypeException {
217 		return add(false, start);
218 	}
219 
220 	/**
221 	 * Adds the range {@code since..until}
222 	 *
223 	 * @param since
224 	 * @param until
225 	 * @return {@code this}
226 	 * @throws MissingObjectException
227 	 *             the commit supplied is not available from the object
228 	 *             database. This usually indicates the supplied commit is
229 	 *             invalid, but the reference was constructed during an earlier
230 	 *             invocation to {@link RevWalk#lookupCommit(AnyObjectId)}.
231 	 * @throws IncorrectObjectTypeException
232 	 *             the object was not parsed yet and it was discovered during
233 	 *             parsing that it is not actually a commit. This usually
234 	 *             indicates the caller supplied a non-commit SHA-1 to
235 	 *             {@link RevWalk#lookupCommit(AnyObjectId)}.
236 	 * @throws JGitInternalException
237 	 *             a low-level exception of JGit has occurred. The original
238 	 *             exception can be retrieved by calling
239 	 *             {@link Exception#getCause()}. Expect only
240 	 *             {@code IOException's} to be wrapped. Subclasses of
241 	 *             {@link IOException} (e.g. {@link MissingObjectException}) are
242 	 *             typically not wrapped here but thrown as original exception
243 	 */
244 	public LogCommand addRange(AnyObjectId since, AnyObjectId until)
245 			throws MissingObjectException, IncorrectObjectTypeException {
246 		return not(since).add(until);
247 	}
248 
249 	/**
250 	 * Add all refs as commits to start the graph traversal from.
251 	 *
252 	 * @see #add(AnyObjectId)
253 	 * @return {@code this}
254 	 * @throws IOException
255 	 *             the references could not be accessed
256 	 */
257 	public LogCommand all() throws IOException {
258 		Map<String, Ref> refs = getRepository().getRefDatabase().getRefs(ALL);
259 		for (Ref ref : refs.values()) {
260 			if(!ref.isPeeled())
261 				ref = getRepository().peel(ref);
262 
263 			ObjectId objectId = ref.getPeeledObjectId();
264 			if (objectId == null)
265 				objectId = ref.getObjectId();
266 			RevCommit commit = null;
267 			try {
268 				commit = walk.parseCommit(objectId);
269 			} catch (MissingObjectException e) {
270 				// ignore: the ref points to an object that does not exist;
271 				// it should be ignored as traversal starting point.
272 			} catch (IncorrectObjectTypeException e) {
273 				// ignore: the ref points to an object that is not a commit
274 				// (e.g. a tree or a blob);
275 				// it should be ignored as traversal starting point.
276 			}
277 			if (commit != null)
278 				add(commit);
279 		}
280 		return this;
281 	}
282 
283 	/**
284 	 * Show only commits that affect any of the specified paths. The path must
285 	 * either name a file or a directory exactly and use <code>/</code> (slash)
286 	 * as separator. Note that regex expressions or wildcards are not supported.
287 	 *
288 	 * @param path
289 	 *            a repository-relative path (with <code>/</code> as separator)
290 	 * @return {@code this}
291 	 */
292 	public LogCommand addPath(String path) {
293 		checkCallable();
294 		pathFilters.add(PathFilter.create(path));
295 		return this;
296 	}
297 
298 	/**
299 	 * Skip the number of commits before starting to show the commit output.
300 	 *
301 	 * @param skip
302 	 *            the number of commits to skip
303 	 * @return {@code this}
304 	 */
305 	public LogCommand setSkip(int skip) {
306 		checkCallable();
307 		this.skip = skip;
308 		return this;
309 	}
310 
311 	/**
312 	 * Limit the number of commits to output.
313 	 *
314 	 * @param maxCount
315 	 *            the limit
316 	 * @return {@code this}
317 	 */
318 	public LogCommand setMaxCount(int maxCount) {
319 		checkCallable();
320 		this.maxCount = maxCount;
321 		return this;
322 	}
323 
324 	private LogCommand add(boolean include, AnyObjectId start)
325 			throws MissingObjectException, IncorrectObjectTypeException,
326 			JGitInternalException {
327 		checkCallable();
328 		try {
329 			if (include) {
330 				walk.markStart(walk.lookupCommit(start));
331 				startSpecified = true;
332 			} else
333 				walk.markUninteresting(walk.lookupCommit(start));
334 			return this;
335 		} catch (MissingObjectException e) {
336 			throw e;
337 		} catch (IncorrectObjectTypeException e) {
338 			throw e;
339 		} catch (IOException e) {
340 			throw new JGitInternalException(MessageFormat.format(
341 					JGitText.get().exceptionOccurredDuringAddingOfOptionToALogCommand
342 					, start), e);
343 		}
344 	}
345 }