9
9
import java .nio .file .Files ;
10
10
import java .nio .file .Path ;
11
11
import java .nio .file .Paths ;
12
+ import java .text .MessageFormat ;
12
13
import java .util .AbstractMap ;
13
14
import java .util .ArrayList ;
14
15
import java .util .Arrays ;
@@ -22,47 +23,33 @@ public class BuildProject {
22
23
public static Path libDownloadPath ;
23
24
private static final String LIB_DEPS_DOWNLOAD_DIR = "_library_dependencies" ;
24
25
private static final String MAVEN_CMD = BuildProject .getMavenCommand ();
25
- private static final String GRADLE_CMD = BuildProject .getGradleCmd ();
26
+ private static final String GRADLE_CMD = BuildProject .getGradleCommand ();
26
27
27
28
/**
28
29
* Gets the maven command to be used for building the project.
29
30
*
30
31
* @return the maven command
31
32
*/
32
- private static String getMavenCommand () {
33
- Boolean isWindows = System .getProperty ("os.name" ).toLowerCase ().contains ("windows" );
34
- String mvnCommand ;
35
- if (isWindows ) {
36
- mvnCommand = new File (projectRootPom , "mvnw.cmd" ).exists () ? String .valueOf (new File (projectRootPom , "mvnw.cmd" )) : "mvn.cmd" ;
37
- } else {
38
- mvnCommand = new File (projectRootPom , "mvnw" ).exists () ? String .valueOf (new File (projectRootPom , "mvnw" )) : "mvn" ;
39
- }
40
- return mvnCommand ;
33
+ public static String getMavenCommand () {
34
+ String mvnSystemCommand = Arrays .stream (System .getenv ("PATH" ).split (System .getProperty ("path.separator" ))).map (path -> new File (path , System .getProperty ("os.name" ).toLowerCase ().contains ("windows" ) ? "mvn.cmd" : "mvn" )).filter (File ::exists ).findFirst ().map (File ::getAbsolutePath ).orElse (null );
35
+ File mvnWrapper = System .getProperty ("os.name" ).toLowerCase ().contains ("windows" ) ? new File (projectRootPom , "mvnw.cmd" ) : new File (projectRootPom , "mvnw" );
36
+ return commandExists (mvnWrapper ).getKey () ? mvnWrapper .toString () : mvnSystemCommand ;
41
37
}
42
38
43
39
/**
44
40
* Gets the gradle command to be used for building the project.
45
41
*
46
42
* @return the gradle command
47
43
*/
48
- private static String getGradleCmd () {
49
- String GRADLE_CMD ;
50
- String osName = System .getProperty ("os.name" ).toLowerCase ();
51
- boolean isWindows = osName .contains ("windows" );
52
- String gradleWrapper = isWindows ? "gradlew.bat" : "gradlew" ;
53
- String gradle = isWindows ? "gradle.bat" : "gradle" ;
54
-
55
- String gradleWrapperExists = new File (projectRootPom , gradleWrapper ).exists () ? "true" : "false" ;
44
+ public static String getGradleCommand () {
45
+ String gradleSystemCommand = Arrays .stream (System .getenv ("PATH" ).split (System .getProperty ("path.separator" ))).map (path -> new File (path , System .getProperty ("os.name" ).toLowerCase ().contains ("windows" ) ? "gradle.bat" : "gradle" )).filter (File ::exists ).findFirst ().map (File ::getAbsolutePath ).orElse (null );
46
+ File gradleWrapper = System .getProperty ("os.name" ).toLowerCase ().contains ("windows" ) ? new File (projectRootPom , "gradlew.bat" ) : new File (projectRootPom , "gradlew" );
56
47
57
- if (new File (projectRootPom , gradleWrapper ).exists ()) {
58
- GRADLE_CMD = String .valueOf (new File (projectRootPom , gradleWrapper ));
59
- } else {
60
- GRADLE_CMD = gradle ;
61
- }
62
- return GRADLE_CMD ;
48
+ return commandExists (gradleWrapper ).getKey () ? gradleWrapper .toString () : gradleSystemCommand ;
63
49
}
64
50
65
- public static Path tempInitScript ;
51
+ public static Path tempInitScript ;
52
+
66
53
static {
67
54
try {
68
55
tempInitScript = Files .createTempFile ("gradle-init-" , ".gradle" );
@@ -71,63 +58,39 @@ private static String getGradleCmd() {
71
58
}
72
59
}
73
60
74
- private static final String GRADLE_DEPENDENCIES_TASK = "allprojects { afterEvaluate { project -> task downloadDependencies(type: Copy) {\n " +
75
- " def configs = project.configurations.findAll { it.canBeResolved }\n \n " +
76
- " dependsOn configs\n " +
77
- " from configs\n " +
78
- " into project.hasProperty('outputDir') ? project.property('outputDir') : \" ${project.buildDir}/libs\" \n \n " +
79
- " doFirst {\n " +
80
- " println \" Downloading dependencies for project ${project.name} to: ${destinationDir}\" \n " +
81
- " configs.each { config ->\n " +
82
- " println \" Configuration: ${config.name}\" \n " +
83
- " config.resolvedConfiguration.resolvedArtifacts.each { artifact ->\n " +
84
- " println \" \t ${artifact.moduleVersion.id}:${artifact.extension}\" \n " +
85
- " }\n " +
86
- " }\n " +
87
- " }\n " +
88
- " }\n " +
89
- " }\n " +
90
- "}" ;
61
+ private static final String GRADLE_DEPENDENCIES_TASK = "allprojects { afterEvaluate { project -> task downloadDependencies(type: Copy) {\n " + " def configs = project.configurations.findAll { it.canBeResolved }\n \n " + " dependsOn configs\n " + " from configs\n " + " into project.hasProperty('outputDir') ? project.property('outputDir') : \" ${project.buildDir}/libs\" \n \n " + " doFirst {\n " + " println \" Downloading dependencies for project ${project.name} to: ${destinationDir}\" \n " + " configs.each { config ->\n " + " println \" Configuration: ${config.name}\" \n " + " config.resolvedConfiguration.resolvedArtifacts.each { artifact ->\n " + " println \" \t ${artifact.moduleVersion.id}:${artifact.extension}\" \n " + " }\n " + " }\n " + " }\n " + " }\n " + " }\n " + "}" ;
91
62
92
- private static AbstractMap .SimpleEntry <Boolean , String > commandExists (String command ) {
63
+ private static AbstractMap .SimpleEntry <Boolean , String > commandExists (File command ) {
93
64
StringBuilder output = new StringBuilder ();
65
+ if (!command .exists ()) {
66
+ return new AbstractMap .SimpleEntry <>(false , MessageFormat .format ("Command {0} does not exist." , command ));
67
+ }
94
68
try {
95
- Process process = new ProcessBuilder ().directory (new File (projectRootPom )).command (command , "--version" ).start ();
69
+ Process process = new ProcessBuilder ().directory (new File (projectRootPom )).command (String . valueOf ( command ) , "--version" ).start ();
96
70
// Read the output stream
97
- BufferedReader reader = new BufferedReader (
98
- new InputStreamReader (process .getInputStream ())
99
- );
71
+ BufferedReader reader = new BufferedReader (new InputStreamReader (process .getInputStream ()));
100
72
String line ;
101
73
while ((line = reader .readLine ()) != null ) {
102
74
output .append (line ).append ("\n " );
103
75
}
104
76
105
77
// Read the error stream
106
- BufferedReader errorReader = new BufferedReader (
107
- new InputStreamReader (process .getErrorStream ())
108
- );
78
+ BufferedReader errorReader = new BufferedReader (new InputStreamReader (process .getErrorStream ()));
109
79
while ((line = errorReader .readLine ()) != null ) {
110
80
output .append (line ).append ("\n " );
111
81
}
112
82
113
-
114
83
int exitCode = process .waitFor ();
115
- return new AbstractMap .SimpleEntry <>(
116
- exitCode == 0 ,
117
- output .toString ().trim ()
118
- );
84
+ return new AbstractMap .SimpleEntry <>(exitCode == 0 , output .toString ().trim ());
119
85
} catch (IOException | InterruptedException exceptions ) {
120
- return new AbstractMap .SimpleEntry <>(
121
- false ,
122
- exceptions .getMessage ()
123
- );
86
+ Log .error (exceptions .getMessage ());
87
+ return new AbstractMap .SimpleEntry <>(false , exceptions .getMessage ());
124
88
}
125
89
}
126
90
127
91
private static boolean buildWithTool (String [] buildCommand ) {
128
92
Log .info ("Building the project using " + buildCommand [0 ] + "." );
129
93
ProcessBuilder processBuilder = new ProcessBuilder ().directory (new File (projectRootPom )).command (buildCommand );
130
-
131
94
try {
132
95
Process process = processBuilder .start ();
133
96
BufferedReader reader = new BufferedReader (new InputStreamReader (process .getInputStream ()));
@@ -157,7 +120,6 @@ private static boolean isMavenInstalled() {
157
120
BufferedReader reader = new BufferedReader (new InputStreamReader (process .getInputStream ()));
158
121
String line = reader .readLine (); // Read the first line of the output
159
122
if (line != null && line .contains ("Apache Maven" )) {
160
- Log .info ("Maven is installed: " + line );
161
123
return true ;
162
124
}
163
125
} catch (IOException e ) {
@@ -179,11 +141,7 @@ private static boolean mavenBuild(String projectPath) {
179
141
Log .info ("Checking if Maven is installed." );
180
142
return false ;
181
143
}
182
- String [] mavenCommand = {
183
- MAVEN_CMD , "clean" , "compile" , "-f" , projectPath + "/pom.xml" , "-B" , "-V" , "-e" , "-Drat.skip" ,
184
- "-Dfindbugs.skip" , "-Dcheckstyle.skip" , "-Dpmd.skip=true" , "-Dspotbugs.skip" , "-Denforcer.skip" ,
185
- "-Dmaven.javadoc.skip" , "-DskipTests" , "-Dmaven.test.skip.exec" , "-Dlicense.skip=true" ,
186
- "-Drat.skip=true" , "-Dspotless.check.skip=true" };
144
+ String [] mavenCommand = {MAVEN_CMD , "clean" , "compile" , "-f" , projectPath + "/pom.xml" , "-B" , "-V" , "-e" , "-Drat.skip" , "-Dfindbugs.skip" , "-Dcheckstyle.skip" , "-Dpmd.skip=true" , "-Dspotbugs.skip" , "-Denforcer.skip" , "-Dmaven.javadoc.skip" , "-DskipTests" , "-Dmaven.test.skip.exec" , "-Dlicense.skip=true" , "-Drat.skip=true" , "-Dspotless.check.skip=true" };
187
145
188
146
return buildWithTool (mavenCommand );
189
147
}
@@ -193,8 +151,7 @@ public static boolean gradleBuild(String projectPath) {
193
151
String [] gradleCommand ;
194
152
if (GRADLE_CMD .equals ("gradlew" ) || GRADLE_CMD .equals ("gradlew.bat" )) {
195
153
gradleCommand = new String []{projectPath + File .separator + GRADLE_CMD , "clean" , "compileJava" , "-p" , projectPath };
196
- }
197
- else {
154
+ } else {
198
155
gradleCommand = new String []{GRADLE_CMD , "clean" , "compileJava" , "-p" , projectPath };
199
156
}
200
157
return buildWithTool (gradleCommand );
@@ -252,31 +209,38 @@ public static boolean downloadLibraryDependencies(String projectPath, String pro
252
209
}
253
210
File pomFile = new File (projectRoot , "pom.xml" );
254
211
if (pomFile .exists ()) {
212
+ if (MAVEN_CMD == null || !commandExists (new File (MAVEN_CMD )).getKey ()) {
213
+ String msg = MAVEN_CMD == null ?
214
+ "Could not find Maven or a valid Maven Wrapper" :
215
+ MessageFormat .format ("Could not verify that {0} exists" , MAVEN_CMD );
216
+ Log .error (msg );
217
+ throw new IllegalStateException ("Unable to execute Maven command. " +
218
+ (MAVEN_CMD == null ?
219
+ "Could not find Maven or a valid Maven Wrapper" :
220
+ "Attempt failed with message\n " + commandExists (new File (MAVEN_CMD )).getValue ()
221
+ ));
222
+ }
255
223
Log .info ("Found pom.xml in the project directory. Using Maven to download dependencies." );
256
- AbstractMap .SimpleEntry <Boolean , String > mavenCheck = commandExists (MAVEN_CMD );
257
- if (!mavenCheck .getKey ())
258
- throw new IllegalStateException ("Unable to execute Maven command. Attempt failed with message\n " + mavenCheck .getValue ());
259
-
260
- String [] mavenCommand = {
261
- MAVEN_CMD , "--no-transfer-progress" , "-f" ,
262
- Paths .get (projectRoot , "pom.xml" ).toString (),
263
- "dependency:copy-dependencies" ,
264
- "-DoutputDirectory=" + libDownloadPath .toString ()
265
- };
224
+ String [] mavenCommand = {MAVEN_CMD , "--no-transfer-progress" , "-f" , Paths .get (projectRoot , "pom.xml" ).toString (), "dependency:copy-dependencies" , "-DoutputDirectory=" + libDownloadPath .toString ()};
266
225
return buildWithTool (mavenCommand );
267
226
} else if (new File (projectRoot , "build.gradle" ).exists () || new File (projectRoot , "build.gradle.kts" ).exists ()) {
268
- Log .info ("Found build.gradle or build.gradle.kts in the project directory. Using gradle to download dependencies." );
269
- AbstractMap .SimpleEntry <Boolean , String > gradleCheck = commandExists (GRADLE_CMD );
270
- if (!gradleCheck .getKey ())
271
- throw new IllegalStateException ("Could not execute Gradle command. Attempt failed with message\n " + gradleCheck .getValue ());
272
-
273
- Log .info ("Found build.gradle[.kts] in the project directory. Using Gradle to download dependencies." );
227
+ if (GRADLE_CMD == null || !commandExists (new File (GRADLE_CMD )).getKey ()) {
228
+ String msg = GRADLE_CMD == null ?
229
+ "Could not find Gradle or valid Gradle Wrapper" :
230
+ MessageFormat .format ("Could not verify that {0} exists" , GRADLE_CMD );
231
+ Log .error (msg );
232
+ throw new IllegalStateException ("Unable to execute Maven command. " +
233
+ (GRADLE_CMD == null ?
234
+ "Could not find Gradle or valid Gradle Wrapper" :
235
+ "Attempt failed with message\n " + commandExists (new File (GRADLE_CMD )).getValue ()
236
+ ));
237
+ }
238
+ Log .info ("Found build.gradle or build.gradle.kts in the project directory. Using Gradle to download dependencies." );
274
239
tempInitScript = Files .writeString (tempInitScript , GRADLE_DEPENDENCIES_TASK );
275
240
String [] gradleCommand ;
276
241
if (GRADLE_CMD .equals ("gradlew" ) || GRADLE_CMD .equals ("gradlew.bat" )) {
277
242
gradleCommand = new String []{projectRoot + File .separator + GRADLE_CMD , "--init-script" , tempInitScript .toFile ().getAbsolutePath (), "downloadDependencies" , "-PoutputDir=" + libDownloadPath .toString ()};
278
- }
279
- else {
243
+ } else {
280
244
gradleCommand = new String []{GRADLE_CMD , "--init-script" , tempInitScript .toFile ().getAbsolutePath (), "downloadDependencies" , "-PoutputDir=" + libDownloadPath .toString ()};
281
245
}
282
246
return buildWithTool (gradleCommand );
@@ -288,10 +252,7 @@ public static void cleanLibraryDependencies() {
288
252
if (libDownloadPath != null ) {
289
253
Log .info ("Cleaning up library dependency directory: " + libDownloadPath );
290
254
try {
291
- Files .walk (libDownloadPath )
292
- .filter (Files ::isRegularFile )
293
- .map (Path ::toFile )
294
- .forEach (File ::delete );
255
+ Files .walk (libDownloadPath ).filter (Files ::isRegularFile ).map (Path ::toFile ).forEach (File ::delete );
295
256
Files .delete (libDownloadPath );
296
257
} catch (IOException e ) {
297
258
Log .error ("Error deleting library dependency directory: " + e .getMessage ());
0 commit comments