-
Notifications
You must be signed in to change notification settings - Fork 64
/
GitConfigStore.java
250 lines (227 loc) · 7.86 KB
/
GitConfigStore.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
* Copyright (c) 2014 Red Hat, Inc. and others
*
* Red Hat licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package io.vertx.config.git;
import io.vertx.config.spi.ConfigStore;
import io.vertx.config.spi.utils.FileSet;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.*;
import org.eclipse.jgit.util.FS;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.eclipse.jgit.api.TransportConfigCallback;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author <a href="http://escoffier.me">Clement Escoffier</a>
*/
public class GitConfigStore implements ConfigStore {
private final static Logger LOGGER
= LoggerFactory.getLogger(GitConfigStore.class);
private final Vertx vertx;
private final File path;
private final List<FileSet> filesets = new ArrayList<>();
private final String url;
private final String branch;
private final String remote;
private final Git git;
private final CredentialsProvider credentialProvider;
private final TransportConfigCallback transportConfigCallback;
public GitConfigStore(Vertx vertx, JsonObject configuration) {
this.vertx = vertx;
String path = Objects.requireNonNull(configuration.getString("path"),
"The `path` configuration is required.");
this.path = new File(path);
if (this.path.isFile()) {
throw new IllegalArgumentException("The `path` must not be a file");
}
JsonArray filesets = Objects.requireNonNull(configuration
.getJsonArray("filesets"),
"The `filesets` element is required.");
for (Object o : filesets) {
JsonObject json = (JsonObject) o;
FileSet set = new FileSet(vertx, this.path, json);
this.filesets.add(set);
}
// Git repository
url = Objects.requireNonNull(configuration.getString("url"),
"The `url` configuration (Git repository location) is required.");
branch = configuration.getString("branch", "master");
remote = configuration.getString("remote", "origin");
if (Objects.nonNull(configuration.getString("user")) &&
Objects.nonNull(configuration.getString("password"))) {
credentialProvider = new UsernamePasswordCredentialsProvider(
configuration.getString("user"), configuration.getString("password"));
} else {
credentialProvider = null;
}
if(Objects.nonNull(configuration.getString("idRsaKeyPath"))){
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session ) {
}
@Override
protected JSch createDefaultJSch(FS fs ) throws JSchException {
JSch defaultJSch = super.createDefaultJSch( fs );
defaultJSch.setConfig("StrictHostKeyChecking", "no");
defaultJSch.addIdentity(configuration.getString("idRsaKeyPath"));
return defaultJSch;
}
};
transportConfigCallback = new TransportConfigCallback() {
@Override
public void configure( Transport transport ) {
SshTransport sshTransport = ( SshTransport )transport;
sshTransport.setSshSessionFactory( sshSessionFactory );
}
};
}else {
transportConfigCallback = null;
}
try {
git = initializeGit();
} catch (Exception e) {
throw new VertxException("Unable to initialize the Git repository", e);
}
}
private Git initializeGit() throws IOException, GitAPIException {
if (path.isDirectory()) {
Git git = Git.open(path);
String current = git.getRepository().getBranch();
if (branch.equalsIgnoreCase(current)) {
PullResult pull = git.pull().setRemote(remote).setCredentialsProvider(credentialProvider)
.setTransportConfigCallback(transportConfigCallback).call();
if (!pull.isSuccessful()) {
LOGGER.warn("Unable to pull the branch + '" + branch +
"' from the remote repository '" + remote + "'");
}
return git;
} else {
git.checkout().
setName(branch).
setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
setStartPoint(remote + "/" + branch).
call();
return git;
}
} else {
return Git.cloneRepository()
.setURI(url)
.setBranch(branch)
.setRemote(remote)
.setDirectory(path)
.setCredentialsProvider(credentialProvider)
.setTransportConfigCallback(transportConfigCallback)
.call();
}
}
@Override
public void get(Handler<AsyncResult<Buffer>> completionHandler) {
update() // Update repository
.compose(v -> read()) // Read files
.compose(this::compute) // Compute the merged json
.setHandler(completionHandler); // Forward
}
private Future<Buffer> compute(List<File> files) {
Future<Buffer> result = Future.future();
List<Future> futures = new ArrayList<>();
for (FileSet set : filesets) {
Future<JsonObject> future = Future.future();
set.buildConfiguration(files, json -> {
if (json.failed()) {
future.fail(json.cause());
} else {
future.complete(json.result());
}
});
futures.add(future);
}
CompositeFuture.all(futures).setHandler(cf -> {
if (cf.failed()) {
result.fail(cf.cause());
} else {
JsonObject json = new JsonObject();
futures.stream().map(f -> (JsonObject) f.result())
.forEach(json::mergeIn);
result.complete(Buffer.buffer(json.encode()));
}
});
return result;
}
private Future<Void> update() {
Future<Void> result = Future.future();
vertx.executeBlocking(
future -> {
PullResult call;
try {
call = git.pull().setRemote(remote).setRemoteBranchName(branch).call();
} catch (GitAPIException e) {
future.fail(e);
return;
}
if (call.isSuccessful()) {
future.complete();
} else {
if (call.getMergeResult() != null) {
future.fail("Unable to merge repository - Conflicts: "
+ call.getMergeResult().getCheckoutConflicts());
} else {
future.fail("Unable to rebase repository - Conflicts: "
+ call.getRebaseResult().getConflicts());
}
}
},
result.completer()
);
return result;
}
private Future<List<File>> read() {
Future<List<File>> result = Future.future();
vertx.executeBlocking(
fut -> {
try {
fut.complete(FileSet.traverse(path).stream().sorted().collect(Collectors.toList()));
} catch (Throwable e) {
fut.fail(e);
}
},
result.completer());
return result;
}
@Override
public void close(Handler<Void> completionHandler) {
vertx.runOnContext(v -> {
if (git != null) {
git.close();
}
completionHandler.handle(null);
});
}
}