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