1
2
3
4
5
6
7
8
9
10 package org.eclipse.jgit.ant.tasks;
11
12 import java.io.File;
13 import java.io.IOException;
14
15 import org.apache.tools.ant.BuildException;
16 import org.apache.tools.ant.Project;
17 import org.apache.tools.ant.Task;
18 import org.apache.tools.ant.types.DirSet;
19 import org.apache.tools.ant.types.FileSet;
20 import org.apache.tools.ant.types.resources.Union;
21 import org.eclipse.jgit.api.AddCommand;
22 import org.eclipse.jgit.api.Git;
23 import org.eclipse.jgit.api.errors.GitAPIException;
24 import org.eclipse.jgit.lib.Repository;
25 import org.eclipse.jgit.lib.RepositoryCache;
26 import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
27 import org.eclipse.jgit.util.FS;
28
29
30
31
32
33
34
35 public class GitAddTask extends Task {
36
37 private File src;
38 private Union path;
39
40
41
42
43
44
45
46 public void setSrc(File src) {
47 this.src = src;
48 }
49
50
51
52
53
54
55
56 public void addFileset(FileSet set) {
57 getPath().add(set);
58 }
59
60
61
62
63
64
65
66 public void addDirset(DirSet set) {
67 getPath().add(set);
68 }
69
70 private synchronized Union getPath() {
71 if (path == null) {
72 path = new Union();
73 path.setProject(getProject());
74 }
75 return path;
76 }
77
78
79 @Override
80 public void execute() throws BuildException {
81 if (src == null) {
82 throw new BuildException("Repository path not specified.");
83 }
84 if (!RepositoryCache.FileKey.isGitRepository(new File(src, ".git"),
85 FS.DETECTED)) {
86 throw new BuildException("Specified path (" + src
87 + ") is not a git repository.");
88 }
89
90 AddCommand gitAdd;
91 try (Repository repo = new FileRepositoryBuilder().readEnvironment()
92 .findGitDir(src).build();
93 Git git = new Git(repo);) {
94 gitAdd = git.add();
95 } catch (IOException e) {
96 throw new BuildException("Could not access repository " + src, e);
97 }
98
99 try {
100 String prefix = src.getCanonicalPath();
101 String[] allFiles = getPath().list();
102
103 for (String file : allFiles) {
104 String toAdd = translateFilePathUsingPrefix(file, prefix);
105 log("Adding " + toAdd, Project.MSG_VERBOSE);
106 gitAdd.addFilepattern(toAdd);
107 }
108 gitAdd.call();
109 } catch (IOException | GitAPIException e) {
110 throw new BuildException("Could not add files to index." + src, e);
111 }
112
113 }
114
115 private String translateFilePathUsingPrefix(String file, String prefix)
116 throws IOException {
117 if (file.equals(prefix)) {
118 return ".";
119 }
120 return new File(file).getCanonicalPath().substring(prefix.length() + 1);
121 }
122
123 }