View Javadoc
1   /*
2    * Copyright (C) 2017, Matthias Sohn <matthias.sohn@sap.com> 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.pgm;
11  
12  import static java.util.function.Predicate.isEqual;
13  import static org.eclipse.jgit.lib.FileMode.EXECUTABLE_FILE;
14  import static org.eclipse.jgit.lib.FileMode.GITLINK;
15  import static org.eclipse.jgit.lib.FileMode.REGULAR_FILE;
16  import static org.eclipse.jgit.lib.FileMode.SYMLINK;
17  
18  import java.io.IOException;
19  import java.util.ArrayList;
20  import java.util.Arrays;
21  import java.util.List;
22  
23  import org.eclipse.jgit.dircache.DirCacheIterator;
24  import org.eclipse.jgit.errors.RevisionSyntaxException;
25  import org.eclipse.jgit.lib.Constants;
26  import org.eclipse.jgit.lib.FileMode;
27  import org.eclipse.jgit.lib.ObjectId;
28  import org.eclipse.jgit.revwalk.RevCommit;
29  import org.eclipse.jgit.revwalk.RevWalk;
30  import org.eclipse.jgit.treewalk.CanonicalTreeParser;
31  import org.eclipse.jgit.treewalk.TreeWalk;
32  import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
33  import org.eclipse.jgit.util.QuotedString;
34  import org.kohsuke.args4j.Option;
35  import org.kohsuke.args4j.spi.StopOptionHandler;
36  
37  @Command(common = true, usage = "usage_LsFiles")
38  class LsFiles extends TextBuiltin {
39  
40  	@Option(name = "--", metaVar = "metaVar_paths", handler = StopOptionHandler.class)
41  	private List<String> paths = new ArrayList<>();
42  
43  	@Override
44  	protected void run() {
45  		try (RevWalkRevWalk.html#RevWalk">RevWalk rw = new RevWalk(db);
46  				TreeWalk tw = new TreeWalk(db)) {
47  			final ObjectId head = db.resolve(Constants.HEAD);
48  			if (head == null) {
49  				return;
50  			}
51  			RevCommit c = rw.parseCommit(head);
52  			CanonicalTreeParser p = new CanonicalTreeParser();
53  			p.reset(rw.getObjectReader(), c.getTree());
54  			tw.reset(); // drop the first empty tree, which we do not need here
55  			if (!paths.isEmpty()) {
56  				tw.setFilter(PathFilterGroup.createFromStrings(paths));
57  			}
58  			tw.addTree(p);
59  			tw.addTree(new DirCacheIterator(db.readDirCache()));
60  			tw.setRecursive(true);
61  			while (tw.next()) {
62  				if (filterFileMode(tw, EXECUTABLE_FILE, GITLINK, REGULAR_FILE,
63  						SYMLINK)) {
64  					outw.println(
65  							QuotedString.GIT_PATH.quote(tw.getPathString()));
66  				}
67  			}
68  		} catch (RevisionSyntaxException | IOException e) {
69  			throw die(e.getMessage(), e);
70  		}
71  	}
72  
73  	private boolean filterFileMode(TreeWalk tw, FileMode... modes) {
74  		return Arrays.stream(modes).anyMatch(isEqual(tw.getFileMode(0))
75  				.or(isEqual(tw.getFileMode(1))));
76  	}
77  }