View Javadoc
1   /*
2    * Copyright (C) 2011, GitHub Inc. and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.api;
11  
12  import java.io.IOException;
13  import java.text.MessageFormat;
14  import java.util.ArrayList;
15  import java.util.Collection;
16  import java.util.Collections;
17  import java.util.List;
18  
19  import org.eclipse.jgit.api.errors.GitAPIException;
20  import org.eclipse.jgit.api.errors.InvalidRefNameException;
21  import org.eclipse.jgit.api.errors.JGitInternalException;
22  import org.eclipse.jgit.internal.JGitText;
23  import org.eclipse.jgit.lib.Constants;
24  import org.eclipse.jgit.lib.ReflogEntry;
25  import org.eclipse.jgit.lib.Repository;
26  import org.eclipse.jgit.revwalk.RevCommit;
27  import org.eclipse.jgit.revwalk.RevWalk;
28  
29  /**
30   * Command class to list the stashed commits in a repository.
31   *
32   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-stash.html"
33   *      >Git documentation about Stash</a>
34   */
35  public class StashListCommand extends GitCommand<Collection<RevCommit>> {
36  
37  	/**
38  	 * Create a new stash list command
39  	 *
40  	 * @param repo a {@link org.eclipse.jgit.lib.Repository} object.
41  	 */
42  	public StashListCommand(Repository repo) {
43  		super(repo);
44  	}
45  
46  	/** {@inheritDoc} */
47  	@Override
48  	public Collection<RevCommit> call() throws GitAPIException,
49  			InvalidRefNameException {
50  		checkCallable();
51  
52  		try {
53  			if (repo.exactRef(Constants.R_STASH) == null)
54  				return Collections.emptyList();
55  		} catch (IOException e) {
56  			throw new InvalidRefNameException(MessageFormat.format(
57  					JGitText.get().cannotRead, Constants.R_STASH), e);
58  		}
59  
60  		final ReflogCommandhtml#ReflogCommand">ReflogCommand refLog = new ReflogCommand(repo);
61  		refLog.setRef(Constants.R_STASH);
62  		final Collection<ReflogEntry> stashEntries = refLog.call();
63  		if (stashEntries.isEmpty())
64  			return Collections.emptyList();
65  
66  		final List<RevCommit> stashCommits = new ArrayList<>(
67  				stashEntries.size());
68  		try (RevWalkvWalk.html#RevWalk">RevWalk walk = new RevWalk(repo)) {
69  			for (ReflogEntry entry : stashEntries) {
70  				try {
71  					stashCommits.add(walk.parseCommit(entry.getNewId()));
72  				} catch (IOException e) {
73  					throw new JGitInternalException(MessageFormat.format(
74  							JGitText.get().cannotReadCommit, entry.getNewId()),
75  							e);
76  				}
77  			}
78  		}
79  		return stashCommits;
80  	}
81  }