-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathNativeGitProvider.java
More file actions
389 lines (325 loc) · 12.4 KB
/
NativeGitProvider.java
File metadata and controls
389 lines (325 loc) · 12.4 KB
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package pl.project13.maven.git;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.maven.plugin.MojoExecutionException;
import org.jetbrains.annotations.NotNull;
import pl.project13.maven.git.log.LoggerBridge;
import java.io.*;
import java.util.Arrays;
public class NativeGitProvider extends GitDataProvider {
private transient ProcessRunner runner;
final File dotGitDirectory;
final File canonical;
private static final int REMOTE_COLS = 3;
@NotNull
public static NativeGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) {
return new NativeGitProvider(dotGitDirectory, loggerBridge);
}
NativeGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) {
super(loggerBridge);
this.dotGitDirectory = dotGitDirectory;
try {
this.canonical = dotGitDirectory.getCanonicalFile();
} catch (Exception ex) {
throw new RuntimeException(new MojoExecutionException("Passed a invalid directory, not a GIT repository: " + dotGitDirectory, ex));
}
}
@NotNull
public NativeGitProvider setVerbose(boolean verbose) {
super.verbose = verbose;
super.loggerBridge.setVerbose(verbose);
return this;
}
@Override
protected void init() throws MojoExecutionException {
// noop ...
}
@Override
protected String getBuildAuthorName() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%an\"");
}
@Override
protected String getBuildAuthorEmail() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%ae\"");
}
@Override
protected void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException {
}
@Override
protected String getBranchName() throws IOException {
return getBranch(canonical);
}
private String getBranch(File canonical) {
String branch = null;
try{
branch = tryToRunGitCommand(canonical, "symbolic-ref HEAD");
if (branch != null) {
branch = branch.replace("refs/heads/", "");
}
}catch(RuntimeException e){
// it seems that git repro is in 'DETACHED HEAD'-State, using Commid-Id as Branch
branch = getCommitId();
}
return branch;
}
@Override
protected String getGitDescribe() throws MojoExecutionException {
final String argumentsForGitDescribe = getArgumentsForGitDescribe(gitDescribe);
final String gitDescribe = tryToRunGitCommand(canonical, "describe" + argumentsForGitDescribe);
return gitDescribe;
}
private String getArgumentsForGitDescribe(GitDescribeConfig describeConfig) {
if (describeConfig == null) return "";
StringBuilder argumentsForGitDescribe = new StringBuilder();
if (describeConfig.isAlways()) {
argumentsForGitDescribe.append(" --always");
}
final String dirtyMark = describeConfig.getDirty();
if (dirtyMark != null && !dirtyMark.isEmpty()) {
argumentsForGitDescribe.append(" --dirty=" + dirtyMark);
}
final String matchOption = describeConfig.getMatch();
if (matchOption != null && !matchOption.isEmpty()) {
argumentsForGitDescribe.append(" --match=" + matchOption);
}
argumentsForGitDescribe.append(" --abbrev=" + describeConfig.getAbbrev());
if (describeConfig.getTags()) {
argumentsForGitDescribe.append(" --tags");
}
if (describeConfig.getForceLongFormat()) {
argumentsForGitDescribe.append(" --long");
}
return argumentsForGitDescribe.toString();
}
@Override
protected String getCommitId() {
return tryToRunGitCommand(canonical, "rev-parse HEAD");
}
@Override
protected String getAbbrevCommitId() throws MojoExecutionException {
// we could run: tryToRunGitCommand(canonical, "rev-parse --short="+abbrevLength+" HEAD");
// but minimum length for --short is 4, our abbrevLength could be 2
String commitId = getCommitId();
String abbrevCommitId = "";
if (commitId != null && !commitId.isEmpty()) {
abbrevCommitId = commitId.substring(0, abbrevLength);
}
return abbrevCommitId;
}
@Override
protected boolean isDirty() throws MojoExecutionException {
return !tryCheckEmptyRunGitCommand(canonical, "status -s");
}
@Override
protected String getCommitAuthorName() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%cn\"");
}
@Override
protected String getCommitAuthorEmail() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%ce\"");
}
@Override
protected String getCommitMessageFull() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%B\"");
}
@Override
protected String getCommitMessageShort() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%s\"");
}
@Override
protected String getCommitTime() {
return tryToRunGitCommand(canonical, "log -1 --pretty=format:\"%ci\"");
}
@Override
protected String getTags() throws MojoExecutionException {
final String branch = tryToRunGitCommand(canonical, "rev-parse --abbrev-ref HEAD");
String out = tryToRunGitCommand(canonical, "log -n 1 --pretty=format:'%d'");
String[] nms = out
.replaceAll("HEAD", "")
.replaceAll("\\)", "")
.replaceAll("\\(", "")
.replaceAll("'", "")
.replaceAll("tag: ", "")
.replaceAll(",", "")
.trim()
.split(" ");
ImmutableList<String> cleanTags = FluentIterable.from(Arrays.asList(nms)).
transform(new Function<String, String>() {
@Override public String apply(String input) {
return input.trim();
}
}).
filter(new Predicate<String>() {
@Override public boolean apply(String input) {
return !input.equals(branch);
}
}).toList();
return Joiner.on(",").join(cleanTags);
}
@Override
protected String getRemoteOriginUrl() throws MojoExecutionException {
return getOriginRemote(canonical);
}
@Override
protected void finalCleanUp() {
}
private String getOriginRemote(File directory) throws MojoExecutionException {
String remoteUrl = null;
try {
String remotes = runGitCommand(directory, "remote -v");
// welcome to text output parsing hell! - no `\n` is not enough
for (String line : Splitter.onPattern("\\((fetch|push)\\)?").split(remotes)) {
String trimmed = line.trim();
if (trimmed.startsWith("origin")) {
String[] splited = trimmed.split("\\s+");
if (splited.length != REMOTE_COLS - 1) { // because (fetch/push) was trimmed
throw new MojoExecutionException("Unsupported GIT output (verbose remote address): " + line);
}
remoteUrl = splited[1];
}
}
} catch (Exception e) {
throw new MojoExecutionException("Error while obtaining origin remote", e);
}
return remoteUrl;
}
private String tryToRunGitCommand(File directory, String gitCommand) {
String retValue = "";
try {
retValue = runGitCommand(directory, gitCommand);
} catch (MojoExecutionException ex) {
// do nothing
}
return retValue;
}
/**
* Runs a maven command and returns {@code true} if output was non empty.
* Can be used to short cut reading output from command when we know it may be a rather long one.
* */
private boolean tryCheckEmptyRunGitCommand(File directory, String gitCommand) {
try {
String env = System.getenv("GIT_PATH");
String exec = (env == null) ? "git" : env;
String command = String.format("%s %s", exec, gitCommand);
boolean empty = getRunner().runEmpty(directory, command);
return !empty;
} catch (IOException ex) {
return false;
// do nothing...
}
}
private String runGitCommand(File directory, String gitCommand) throws MojoExecutionException {
try {
final String env = System.getenv("GIT_PATH");
final String exec = (env == null) ? "git" : env;
final String command = String.format("%s %s", exec, gitCommand);
final String result = getRunner().run(directory, command.trim()).trim();
return result;
} catch (IOException ex) {
if (ex.getMessage().contains("exited with invalid status")) {
throw new RuntimeException("Failed to execute git command (`git " + gitCommand + "` @ " + directory +")!", ex);
} else {
throw new MojoExecutionException("Could not run GIT command - GIT is not installed or not exists in system path? " +
"Tried to run: 'git " + gitCommand + "'", ex);
}
}
}
private ProcessRunner getRunner() {
if (runner == null) {
runner = new JavaProcessRunner();
}
return runner;
}
public interface ProcessRunner {
/** Run a command and return the entire output as a String - naive, we know. */
String run(File directory, String command) throws IOException;
/** Run a command and return false if it contains at least one output line*/
boolean runEmpty(File directory, String command) throws IOException;
}
protected static class JavaProcessRunner implements ProcessRunner {
@Override
public String run(File directory, String command) throws IOException {
String output = "";
try {
ProcessBuilder builder = new ProcessBuilder(command.split("\\s"));
final Process proc = builder.directory(directory).start();
proc.waitFor();
final InputStream is = proc.getInputStream();
final InputStream err = proc.getErrorStream();
final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
final StringBuilder commandResult = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
commandResult.append(line);
}
if (proc.exitValue() != 0) {
final StringBuilder errMsg = readStderr(err);
final String message = String.format("Git command exited with invalid status [%d]: stdout: `%s`, stderr: `%s`", proc.exitValue(), output, errMsg.toString());
throw new IOException(message);
}
output = commandResult.toString();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
return output;
}
private StringBuilder readStderr(InputStream err) throws IOException {
String line;
final BufferedReader errReader = new BufferedReader(new InputStreamReader(err));
final StringBuilder errMsg = new StringBuilder();
while((line = errReader.readLine())!=null){
errMsg.append(line);
}
return errMsg;
}
// @Override
// public String run(File directory, String command) throws IOException {
// String output;
// try {
// final ProcessBuilder builder = new ProcessBuilder(command.split("\\s"));
// final Process proc = builder.directory(directory).start();
// proc.waitFor();
// InputStream is = proc.getInputStream();
// BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// final StringBuilder commandResult = new StringBuilder();
//
// String line;
// while ((line = reader.readLine()) != null) {
// commandResult.append(line);
// }
//
// output = commandResult.toString();
//
// if (proc.exitValue() != 0) {
// String message = String.format("Git command exited with invalid status [%d]: `%s`", proc.exitValue(), output);
// throw new IOException(message);
// }
// } catch (InterruptedException e) {
// throw new RuntimeException("Unable to attach to git process!", e);
// }
// return output;
// }
@Override
public boolean runEmpty(File directory, String command) throws IOException {
boolean empty = true;
try {
ProcessBuilder builder = new ProcessBuilder(Lists.asList("/bin/sh", "-c", command.split("\\s")));
final Process proc = builder.directory(directory).start();
proc.waitFor();
final InputStream is = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (reader.readLine() != null) {
empty = false;
}
} catch (InterruptedException ex) {
throw new IOException(ex);
}
return empty; // was non-empty
}
}
}