-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJmake.java
More file actions
242 lines (218 loc) · 8.38 KB
/
Jmake.java
File metadata and controls
242 lines (218 loc) · 8.38 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
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.Optional;
/**
* Simple build script for Java
* <p>
* To use:
* <ul>
* <li>Copy this file into your top level project
* <li>Verify all source code is under dirctory named "src"
* <li>Create a directory named "lib"
* <li>Add all jar dependencies to the lib folder
* <li>From the top level project folder, run {@code java Jmake.java} or
* {@code java Jmake.java package.MainClass}
* <ul>
* <p>
*
* @author dummh
*
*/
public class Jmake {
/**
* Main method
* <p>
* To create a library, run in the top level project directory:
* <p>
* {@code java Jmake.java}
* <p>
* To create an executable, provide the main class as an argument:
* <p>
* {@code java Jmake.java package.MainClass}
*
* @param args Main class
*
* @throws IOException
*/
public static void main(String[] args) throws IOException, InterruptedException {
String separator = "--------------------------------------------------------------";
// get the start time
long start = System.nanoTime();
// check that lib path exists
Path libPath = Paths.get("lib");
if (!Files.exists(libPath)) {
throw new IllegalStateException("Directory not found: lib/. At top level of project?");
}
// check that src path exists
Path srcPath = Paths.get("src/main/java");
if (!Files.exists(srcPath)) {
// try alternate src path (non maven)
srcPath = Paths.get("src");
if (!Files.exists(srcPath)) {
throw new IllegalStateException("Directory not found: src/. At top level of project?");
}
}
// get the project name (same name as current directory where launched)
String cwdString = System.getProperty("user.dir");
String name = Paths.get(cwdString).getFileName().toString();
Pattern pattern = Pattern.compile("[^-_A-Za-z0-9]");
Matcher m = pattern.matcher(name);
if (m.find()) {
throw new IllegalArgumentException(
"The name of the project directory must have no spaces and only _, -, A-Z, a-z, 0-9");
}
System.out.println(separator);
System.out.format("Building %s%n", name);
System.out.println(separator);
// check for main class
String mainClass = "";
if (args.length == 1) {
System.out.format("Creating executable for main class: %s%n", args[0]);
mainClass = args[0];
} else {
System.out.println("Creating library (no main class provided)");
}
// present list of available main classes if not provided?
// get all the java files and write to a temp file
Path listfile = Files.createTempFile(null, null);
try (Stream<Path> files = Files.find(srcPath, 999,
(path, attribute) -> attribute.isRegularFile() && path.getFileName().toString().endsWith(".java"))) {
List<String> filenames = files.map(Path::toString).toList();
Files.write(listfile, filenames);
}
// delete the bin folder
if (Files.isDirectory(Paths.get("bin/"), LinkOption.NOFOLLOW_LINKS)) {
System.out.println("Deleting bin/ directory");
Files.walk(Paths.get("./bin")).sorted(Comparator.reverseOrder()).map(Path::toFile).forEach(File::delete);
}
// get the os
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
System.out.format("Compiling on %s with:%n", System.getProperty("os.name"));
// create the output directory
boolean created = new File("bin").mkdir();
// compile with java 17 by default
String[] buildCommand = { "javac", "-encoding", "utf-8", "--release", "17", "-d", "bin", "-cp", "lib/*",
String.format("@%s", listfile) };
Process process;
if (isWindows) {
buildCommand[8] = "lib\\*";
}
System.out.println(" " + String.join(" ", buildCommand));
process = Runtime.getRuntime().exec(buildCommand);
process.waitFor();
InputStream in = process.getErrorStream();
System.err.println(new BufferedReader(new InputStreamReader(in)).lines().collect(Collectors.joining("\n")));
// copy the resources into the jar
Path resourceDir = Paths.get("src/main/resources");
Path destinationDir = Paths.get("bin/");
if (Files.exists(resourceDir)) {
System.out.println("Copying resources");
Files.walk(resourceDir).forEach(source -> {
Path destination = Paths.get(destinationDir.toString(),
source.toString().substring(resourceDir.toString().length()));
try {
// System.out.format("destination: %s%n", destination.toString());
Files.copy(source, destination);
} catch (java.nio.file.FileAlreadyExistsException e) {
// ignoring this message (finds that bin already exists)
} catch (IOException e) {
e.printStackTrace();
}
});
}
// get the current date (maybe one day replace with semver computed from
// sources)
LocalDate date = LocalDate.now();
String dateText = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
// create the jar file (-C changes the working directory to bin/)
System.out.println("Creating jar file");
String[] jarCommand = { "jar", "cf", String.format("bin/%s-%s.jar", name, dateText), "-C", "bin", "." };
System.out.println(" " + String.join(" ", jarCommand));
Runtime.getRuntime().exec(jarCommand).waitFor();
// create executable scripts
if (!mainClass.isEmpty()) {
System.out.println("Creating run files");
// mac or linux
Files.write(Paths.get(String.format("%s", name)),
String.format("java -cp bin/*:lib/* %s $@", mainClass).getBytes(StandardCharsets.UTF_8));
// windows
Files.write(Paths.get(String.format("%s.bat", name)),
String.format("java -cp \"bin/*;lib/*\" %s %%*", mainClass).getBytes(StandardCharsets.UTF_8));
}
// generate the javadoc
System.out.println("Creating javadoc");
String[] javadocCommand = { "javadoc", "--ignore-source-errors", "-sourcepath", srcPath.toString(), "-d",
"./javadoc", String.format("@%s", listfile) };
System.out.println(" " + String.join(" ", javadocCommand));
ProcessBuilder pb = new ProcessBuilder(javadocCommand);
pb.inheritIO();
process = pb.start();
process.waitFor();
System.out.println("");
// generate source jar
System.out.println("Creating source jar");
String sourceJarCommand = String.format("jar cf bin/%s-%s-sources.jar @%s", name, dateText, listfile);
System.out.println(" " + sourceJarCommand);
Runtime.getRuntime().exec(sourceJarCommand.split(" "));
// run any tests (replacing all of junit with a few lines)
System.out.println("Running tests\n");
try (Stream<Path> files = Files.find(srcPath, 999,
(path, attribute) -> attribute.isRegularFile() && path.getFileName().toString().endsWith(".java"))) {
List<Path> paths = files.toList();
for (Path p : paths) {
// get the package name
String packageLine = Files.lines(p).filter(line -> line.startsWith("package")).findFirst().get();
String packageName = packageLine.split(" ")[1].replace(";", "");
// get class name from filename
String className = p.getFileName().toString().split(".java")[0];
String fqn = packageName + "." + className;
// modified for this build to include orekit-data
String[] testCommand = { "java", "-ea", "-cp", "bin/*:lib/*",
String.format("%s.%s", packageName, className) };
if (!fqn.equals(mainClass)) {
if (isWindows) {
testCommand[4] = "bin\\*;lib\\*";
}
System.out.println(testCommand);
// run command
pb = new ProcessBuilder(testCommand);
pb.redirectErrorStream(true);
process = pb.start();
// print any errors
InputStream in2 = process.getInputStream();
String output = new BufferedReader(new InputStreamReader(in2)).lines()
.collect(Collectors.joining("\n"));
if (output.startsWith("Error: Main method not found")) {
System.err.println("no tests found");
} else {
System.err.println(output);
}
System.out.println("");
}
}
}
// delete the temp file list
Files.delete(listfile);
// finished
long stop = System.nanoTime();
System.out.println(separator);
System.out.format("Total time: %.3f s%n", (stop - start) / 1_000_000_000.0);
System.out.println(separator);
}
}