-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild
More file actions
executable file
·757 lines (620 loc) · 23.6 KB
/
build
File metadata and controls
executable file
·757 lines (620 loc) · 23.6 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
#!/usr/bin/env -S java --source 21
// ft: java
// In case of doubt about the JDK used:
// -showversion
//
// In case of debug procedure:
// -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import java.util.SequencedCollection;
import java.util.SequencedSet;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
import java.util.function.IntSupplier;
import java.util.function.ToIntFunction;
import java.util.stream.Stream;
/**
* Stupid Simple Java Build System.
* <p>
* <code>
* $> java build.java help
* </code>
* <p>
* Still missing:
* <ul>
* <li>Resource file support in src/{main,test}/resources</li>
* <li>Integration test support</li>
* <li>Überjar support</li>
* </ul>
*/
public class build {
public static void main(String... args) {
// System.getenv().forEach((k, v) -> System.out.printf("env: %s = %s%n", k, v));
// System.getProperties().forEach((k, v) -> System.out.printf("jvm: %s = %s%n", k, v));
if (args.length < 1) {
execute(() -> build.usage(0), System::exit);
}
else {
var target = args[0];
switch (target) {
//@formatter:off
case "help" -> execute(() -> build.usage(0), System::exit);
case "compile" -> execute(main.compile::command, System::exit);
case "package" -> execute(main.archive::command, System::exit);
case "run" -> execute(main.runtime::command, System::exit, shift(args));
case "testCompile" -> execute(test.compile::command, System::exit);
case "test" -> execute(test.runtime::command, System::exit, shift(args));
case "clean" -> execute(build::clean, System::exit);
case null, default -> execute(() -> build.usage(1), System::exit);
//@formatter:on
}
}
}
static int usage(int exitCode) {
final String progname = Path.of(sysProp("jdk.launcher.sourcefile")).getFileName().toString();
System.out.printf(
"""
NAME
%1$s — Stupid Simple Java Build System.
SYNOPSIS
%1$s [ TARGET [ ...ARGS ] ]
TARGETS
compile — compile source files
run — run the program, passing ARGS to the program
test — execute test suite, passing ARGS to JUnit
package — create JAR file
clean — cleanup the source worktree
testCompile — compile only test sources
FILES
assume source files in the following locations:
· src/main/java — main source files of the program
· src/test/java — test source files of the program test suite
all outputs are in build directory
DEPENDENCIES
using maven dependencies management mechanism with following classpath definition:
· main.compile — dependencies required to compile the program
· main.runtime — dependencies required to run the program,
includes by default the ``main.compile`` dependencies
· test.compile — dependencies required to compile test suite,
includes by default the ``main.compile`` dependencies
· test.runtime — dependencies required to run test suite,
includes by default the ``test.compile`` dependencies
a dependencies is define by:
· a groupID
· an artifactId
· a version
%n""",
progname);
return exitCode;
}
static int clean() {
try {
rmdir(Path.of("target"));
}
catch (IOException cause) {
throw propagate(cause);
}
return 0;
}
static class main {
static final Path sources = cwd().resolve(Path.of("src", "main", "java"));
static final Path classes = cwd().resolve(Path.of("target", "main", "classes"));
static class compile {
static final maven.dependencies dependencies = new maven.dependencies().scope("main.compile");
static int command() {
return javac.compile(main.sources,
main.classes,
new classpath(main.compile.dependencies));
}
}
static class runtime {
static final String fqClassName = buildProp("build.main.runtime.fqClassName").orElse("");
static final maven.dependencies dependencies = new maven.dependencies(main.compile.dependencies).scope("main.runtime");
static int command(String... args) {
execute(main.archive::command, build::exitOnError);
return java.runJar(main.archive.name,
new classpath(main.classes).append(runtime.dependencies),
args);
}
}
static class archive {
static final String name = cwd().resolve(Path.of("target")
.resolve(buildProp("build.main.jar.name")
.orElseGet(() -> cwd().getFileName().toString() + ".jar")))
.toString();
static int command() {
execute(main.compile::command, build::exitOnError);
if (main.runtime.fqClassName.isBlank()) throw new IllegalStateException("'build.main.runtime.fqClassName' is missing");
return jar.archive(main.archive.name,
main.runtime.fqClassName,
main.classes);
}
}
}
static class test {
static final Path sources = cwd().resolve(Path.of("src", "test", "java"));
static final Path classes = cwd().resolve(Path.of("target", "test", "classes"));
static class compile {
static final maven.dependencies dependencies = new maven.dependencies(main.runtime.dependencies).scope("test.compile");
static int command() {
execute(main.compile::command, build::exitOnError);
return javac.compile(test.sources,
test.classes,
new classpath(main.classes).append(test.compile.dependencies));
}
}
static class runtime {
static final maven.dependencies dependencies = new maven.dependencies(test.compile.dependencies).scope("test.runtime");
static int command(String... args) {
if (args == null || args.length == 0) {
return command(
"execute",
"--disable-banner",
"--fail-if-no-tests",
"--scan-classpath"
);
}
else {
execute(test.compile::command, build::exitOnError);
return java.run("org.junit.platform.console.ConsoleLauncher",
new classpath(main.classes)
.append(test.classes)
.append(test.runtime.dependencies),
args);
}
}
}
}
static class javac {
static final Path JAVAC = java.HOME.resolve(Path.of("bin", "javac"));
static int compile(Path sourcePath, Path outputDir, classpath classpath) {
command.line commandLine = new command.line(
JAVAC.toString(),
"--source", java.VERSION,
"--target", java.VERSION,
"--source-path", sourcePath.toString(),
"-classpath", classpath.toString(),
"-d", outputDir.toString()
).append(sourceFiles(sourcePath));
return command.execute(commandLine, pipe(System.out), pipe(System.err));
}
static String[] sourceFiles(Path sourceDirectory) {
try (var walker = Files.walk(sourceDirectory)) {
return walker.filter(p -> p.getFileName().toString().matches(".*\\.java"))
.map(p -> p.toFile().toString())
.toArray(String[]::new);
}
catch (IOException cause) {
throw propagate(cause);
}
}
static String[] classFiles(Path classesDirectory) {
try (var walker = Files.walk(classesDirectory)) {
return walker.filter(p -> p.getFileName().toString().matches(".*\\.class"))
.map(p -> p.toFile().toString())
.map(p -> p.replaceFirst("^" + classesDirectory.toString(), ""))
.toArray(String[]::new);
}
catch (IOException cause) {
throw propagate(cause);
}
}
}
static class jar {
static final Path JAR = java.HOME.resolve(Path.of("bin", "jar"));
static int archive(String archive, String fqClassName, Path classesDirectory) {
command.line commandLine = new command.line(
JAR.toString(),
"--create",
"--file", archive,
"--main-class", fqClassName,
"-C", classesDirectory.toString()
).append(javac.classFiles(classesDirectory));
return command.execute(commandLine, pipe(System.out), pipe(System.err));
}
}
static class java {
static final Path HOME = Path.of(sysProp("java.home"));
static final Path JAVA = HOME.resolve(Path.of("bin", "java"));
static final String VERSION = sysProp("java.specification.version");
static int run(String fqClassName, classpath classpath, String... args) {
command.line commandLine = new command.line(
JAVA.toString(),
"-classpath", classpath.toString(),
fqClassName
).append(args);
return command.execute(commandLine, pipe(System.out), pipe(System.err));
}
static int runJar(String jarFile, classpath classpath, String... args) {
command.line commandLine = new command.line(
JAVA.toString(),
"-classpath", classpath.toString(),
"-jar", jarFile
).append(args);
return command.execute(commandLine, pipe(System.out), pipe(System.err));
}
}
static class classpath {
private final List<String> paths = new ArrayList<>();
classpath(Path... paths) {
this.append(paths);
}
classpath(maven.dependencies dependencies) {
this.append(dependencies);
}
classpath append(Path... paths) {
return append(Arrays.stream(paths).map(Path::toString).toArray(String[]::new));
}
classpath append(String... paths) {
this.paths.addAll(Arrays.asList(paths));
return this;
}
classpath append(maven.dependencies dependencies) {
dependencies.resolve()
.map(maven.dependency::localJarPath)
.map(Path::toString)
.forEach(this.paths::add);
return this;
}
@Override public String toString() {
return String.join(":", paths);
}
}
static class maven {
static final Path HOME = userHome().resolve(".m2");
static final HttpClient REMOTE_REPOSITORY = HttpClient.newHttpClient();
static Collection<dependency> resolve(Collection<dependency> dependencies) {
SequencedSet<dependency> toResolve = new LinkedHashSet<>(dependencies);
SequencedSet<dependency> resolved = new LinkedHashSet<>();
while (!toResolve.isEmpty()) {
dependency next = toResolve.removeFirst();
downloadIfMissing(next);
resolved.addLast(next);
next.pom().dependencies().stream()
.filter(dependency -> !resolved.contains(dependency))
.forEach(toResolve::add);
}
return resolved;
}
static void downloadIfMissing(maven.dependency d) {
downloadIfMissing(d.remotePomPath(), d.localPomPath());
downloadIfMissing(d.remoteJarPath(), d.localJarPath());
}
static void downloadIfMissing(URI remoteUri, Path localPath) {
if (localPath.toFile().isFile() && localPath.toFile().canRead()) {
return;
}
System.out.printf("downloading %s ... ", remoteUri);
HttpRequest request = HttpRequest.newBuilder()
.GET().uri(remoteUri)
.build();
if (!localPath.getParent().toFile().isDirectory() && !localPath.getParent().toFile().mkdirs()) {
throw new IllegalStateException("Can not create directory " + localPath.getParent());
}
try {
HttpResponse<Path> httpResponse = REMOTE_REPOSITORY.send(request, HttpResponse.BodyHandlers.ofFile(localPath));
if (httpResponse.statusCode() < 200 || 300 <= httpResponse.statusCode()) {
Path downloaded = httpResponse.body();
if (downloaded.toFile().isFile()) downloaded.toFile().delete();
throw new IOException("Unable to get file from server, got status " + httpResponse.statusCode());
}
System.out.printf(" ✔%n");
}
catch (IOException | InterruptedException cause) {
System.out.printf("failed!%n");
throw propagate(cause);
}
}
record dependency(
String g,
String a,
String v
) {
static class Builder {
private String groupId;
private String artifactId;
private String version;
private String scope = "compile"; // Default scope in pom.xml if not specified
void groupId(String groupId) {
this.groupId = groupId;
}
void artifactId(String artifactId) {
this.artifactId = artifactId;
}
void version(String version) {
this.version = version;
}
void scope(String scope) {
this.scope = scope;
}
String scope() {
return scope;
}
dependency build() {
return new dependency(groupId, artifactId, version);
}
}
public pom pom() {
return new pom(localPomPath());
}
static Path localRepository() {
return buildProp("build.maven.local.repository")
.map(Paths::get)
.orElseGet(() -> HOME.resolve("repository"));
}
String relativePath(String pathSeperator, String ext) {
return "%2$s%1$s%3$s%1$s%4$s%1$s%3$s-%4$s.%5$s"
.formatted(pathSeperator, g.replaceAll("\\.", pathSeperator), a, v, ext);
}
public Path localJarPath() {
return localRepository().resolve(relativePath(File.separator, "jar"));
}
public Path localPomPath() {
return localRepository().resolve(relativePath(File.separator, "pom"));
}
static URI remoteRepository() {
return URI.create("https://repo.maven.apache.org/maven2/");
}
public URI remoteJarPath() {
return remoteRepository().resolve(relativePath("/", "jar"));
}
public URI remotePomPath() {
return remoteRepository().resolve(relativePath("/", "pom"));
}
}
static class dependencies {
private final List<dependency> dependencies = new ArrayList<>();
dependencies() { /* 😉 */ }
dependencies(dependencies dependencies) {
addAll(dependencies.dependencies);
}
void addAll(Collection<dependency> dependencies) {
this.dependencies.addAll(dependencies);
}
void add(dependency dependencies) {
this.dependencies.add(dependencies);
}
dependencies scope(String scope) {
buildProp("build.%s.dependencies".formatted(scope))
.ifPresent(dependenciesString ->
Arrays.stream(dependenciesString.split("\\s"))
.filter(dependency -> !dependency.isBlank())
.map(dependency -> {
String[] strings = dependency.split(":");
return new dependency(strings[0], strings[1], strings[2]);
})
.forEach(this::add));
return this;
}
Stream<dependency> resolve() {
return maven.resolve(this.dependencies).stream();
}
}
static class pom {
static final String NAMESPACE_URI = "http://maven.apache.org/POM/4.0.0";
static final String NAMESPACE_PREFIX = "pom";
static final XPath XPATH = XPathFactory.newDefaultInstance().newXPath();
static final String xpath = "//pom:project/pom:dependencies/pom:dependency";
static final XPathExpression xPathExpression;
static {
XPATH.setNamespaceContext(
new NamespaceContext() {
@Override public String getNamespaceURI(String prefix) {
return prefix.equals(NAMESPACE_PREFIX)
? NAMESPACE_URI
: "";
}
@Override public String getPrefix(String namespaceURI) {
return namespaceURI.equals(NAMESPACE_URI)
? NAMESPACE_PREFIX
: "";
}
@Override public Iterator<String> getPrefixes(String namespaceURI) {
return ( namespaceURI.equals(NAMESPACE_URI)
? List.of(NAMESPACE_PREFIX)
: List.<String>of() ).iterator();
}
}
);
try {
xPathExpression = XPATH.compile(xpath);
}
catch (XPathExpressionException cause) {
throw propagate(cause);
}
}
final InputSource source;
pom(Path location) {
try {
source = new InputSource(new FileReader(location.toFile()));
}
catch (FileNotFoundException cause) {
throw propagate(cause);
}
}
SequencedCollection<dependency> dependencies() {
final NodeList dependencyNodeList;
try {
dependencyNodeList = (NodeList) xPathExpression.evaluate(source, XPathConstants.NODESET);
}
catch (XPathExpressionException cause) {
throw propagate(cause);
}
List<dependency> dependencies = new ArrayList<>();
for (int i = 0; i < dependencyNodeList.getLength(); i++) {
Node dependencyNode = dependencyNodeList.item(i);
NodeList children = dependencyNode.getChildNodes();
dependency.Builder builder = new dependency.Builder();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
if (Node.TEXT_NODE == child.getNodeType()) continue;
//@formatter:off
if (child.getLocalName().equals("groupId")) builder.groupId(child.getTextContent());
if (child.getLocalName().equals("artifactId")) builder.artifactId(child.getTextContent());
if (child.getLocalName().equals("version")) builder.version(child.getTextContent());
if (child.getLocalName().equals("scope")) builder.scope(child.getTextContent());
//@formatter:on
}
if (List.of("compile", "runtime").contains(builder.scope())) {
dependencies.add(builder.build());
}
}
return dependencies;
}
}
}
static void execute(IntSupplier command, IntConsumer exitCodeHandler) {
exitCodeHandler.accept(command.getAsInt());
}
static void execute(ToIntFunction<String[]> command, IntConsumer exitCodeHandler, String... args) {
exitCodeHandler.accept(command.applyAsInt(args));
}
static void exitOnError(int exitCode) {
if (exitCode != 0) {
System.exit(exitCode);
}
}
/**
* Current Working Directory.
*
* @return The directory where the build script lies.
*/
static Path cwd() {
Path cwd = Path.of(sysProp("jdk.launcher.sourcefile")).getParent();
return ".".equals(cwd.getFileName().toString())
? cwd.getParent()
: cwd;
}
static Path userHome() {
return Path.of(sysProp("user.home"));
}
static String sysProp(String key) {
return Optional.ofNullable(System.getProperty(key))
.orElseThrow(() -> new IllegalStateException("Can not find value of JVM property '" + key + "'"));
}
static Optional<String> buildProp(String key) {
return Optional.ofNullable(PROPERTIES.getProperty(key))
.filter(s -> !s.isBlank());
}
static Consumer<BufferedReader> pipe(PrintStream out) {
return in -> in.lines().forEachOrdered(out::println);
}
static class command {
static class line {
final List<String> items = new ArrayList<>();
line(String... items) {
append(items);
}
line append(String... moreItems) {
items.addAll(Arrays.asList(moreItems));
return this;
}
String[] toArray() {
return items.toArray(String[]::new);
}
@Override public String toString() {
return String.join(" ", items);
}
}
static int execute(command.line commandline,
Consumer<BufferedReader> stdoutConsumer,
Consumer<BufferedReader> stderrConsumer) {
try {
System.out.printf("+ %s%n", commandline);
Process process = Runtime.getRuntime().exec(commandline.toArray());
int exitCode = process.waitFor();
if (exitCode != 0) {
System.err.printf("Run '%s', got exit code '%d'%n", commandline, exitCode);
}
// System.out.printf("Run '%s', got exit code '%d'%n", String.join(" ", commandline), exitCode);
try (BufferedReader stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
if (stdoutConsumer != null) {
stdoutConsumer.accept(stdout);
}
if (stderrConsumer != null) {
stderrConsumer.accept(stderr);
}
}
return exitCode;
}
catch (Exception cause) {
throw new IllegalStateException("Run %s, got unexpected error".formatted(commandline), cause);
}
}
}
static void rmdir(Path path) throws IOException {
if (path.toFile().isDirectory()) {
try (var files = Files.walk(path)){
files.sorted(Comparator.reverseOrder()) // to look at directories content first
.forEachOrdered(justDo(Files::deleteIfExists));
}
}
}
@FunctionalInterface
interface IOProcedure<T> {
void accept(T input) throws IOException;
}
static <T> Consumer<T> justDo(IOProcedure<T> block) {
return (T input) -> {
try {
block.accept(input);
}
catch (IOException error) {
throw propagate(error);
}
};
}
static RuntimeException propagate(Throwable cause) {
throw new RuntimeException(cause);
}
static String[] shift(String[] array) {
String[] strings = new String[array.length - 1];
System.arraycopy(array, 1, strings, 0, array.length - 1);
return strings;
}
static final Properties PROPERTIES = new Properties();
static {
try {
PROPERTIES.load(new FileReader(cwd().resolve("build.properties").toFile()));
File localBuildPropertiesFile = cwd().resolve("build-local.properties").toFile();
if (localBuildPropertiesFile.isFile() && localBuildPropertiesFile.canRead()) {
PROPERTIES.load(new FileReader(localBuildPropertiesFile));
}
}
catch (IOException cause) {
throw propagate(cause);
}
}
}