]> git.argeo.org Git - cc0/argeo-build.git/blob - src/org/argeo/build/Make.java
Exclude output directory, so that single bundles (esp. argeo-build
[cc0/argeo-build.git] / src / org / argeo / build / Make.java
1 package org.argeo.build;
2
3 import static java.lang.System.Logger.Level.DEBUG;
4 import static java.lang.System.Logger.Level.ERROR;
5 import static java.lang.System.Logger.Level.INFO;
6 import static java.lang.System.Logger.Level.WARNING;
7
8 import java.io.File;
9 import java.io.IOException;
10 import java.io.InputStream;
11 import java.io.OutputStream;
12 import java.io.PrintWriter;
13 import java.lang.System.Logger;
14 import java.lang.System.Logger.Level;
15 import java.lang.management.ManagementFactory;
16 import java.nio.file.DirectoryStream;
17 import java.nio.file.FileVisitResult;
18 import java.nio.file.Files;
19 import java.nio.file.Path;
20 import java.nio.file.PathMatcher;
21 import java.nio.file.Paths;
22 import java.nio.file.SimpleFileVisitor;
23 import java.nio.file.attribute.BasicFileAttributes;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.Properties;
32 import java.util.StringJoiner;
33 import java.util.StringTokenizer;
34 import java.util.TreeMap;
35 import java.util.concurrent.CompletableFuture;
36 import java.util.jar.Attributes;
37 import java.util.jar.JarEntry;
38 import java.util.jar.JarOutputStream;
39 import java.util.jar.Manifest;
40 import java.util.zip.Deflater;
41
42 import org.eclipse.jdt.core.compiler.CompilationProgress;
43
44 import aQute.bnd.osgi.Analyzer;
45 import aQute.bnd.osgi.Jar;
46
47 /**
48 * Minimalistic OSGi compiler and packager, meant to be used as a single file
49 * without being itself compiled first. It depends on the Eclipse batch compiler
50 * (aka. ECJ) and the BND Libs library for OSGi metadata generation (which
51 * itselfs depends on slf4j).<br/>
52 * <br/>
53 * For example, a typical system call would be:<br/>
54 * <code>java -cp "/path/to/ECJ jar:/path/to/bndlib jar:/path/to/SLF4J jar" /path/to/cloned/argeo-build/src/org/argeo/build/Make.java action --option1 argument1 argument2 --option2 argument3 </code>
55 */
56 public class Make {
57 private final static Logger logger = System.getLogger(Make.class.getName());
58
59 /**
60 * Environment variable on whether sources should be packaged separately or
61 * integrated in the bundles.
62 */
63 private final static String ENV_SOURCE_BUNDLES = "SOURCE_BUNDLES";
64
65 /**
66 * Environment variable on whether legal files at the root of the sources should
67 * be included in the generated bundles. Should be set to true when building
68 * third-party software in order no to include the build harness license into
69 * the generated bundles.
70 */
71 private final static String ENV_NO_SDK_LEGAL = "NO_SDK_LEGAL";
72
73 /**
74 * Environment variable to override the default location for the Argeo Build
75 * configuration files. Typically used if Argeo Build has been compiled and
76 * packaged separately.
77 */
78 private final static String ENV_ARGEO_BUILD_CONFIG = "ARGEO_BUILD_CONFIG";
79
80 /** Make file variable (in {@link #SDK_MK}) with a path to the sources base. */
81 private final static String VAR_SDK_SRC_BASE = "SDK_SRC_BASE";
82
83 /**
84 * Make file variable (in {@link #SDK_MK}) with a path to the build output base.
85 */
86 private final static String VAR_SDK_BUILD_BASE = "SDK_BUILD_BASE";
87
88 /** Name of the local-specific Makefile (sdk.mk). */
89 final static String SDK_MK = "sdk.mk";
90 /** Name of the branch definition Makefile (branch.mk). */
91 final static String BRANCH_MK = "branch.mk";
92
93 /** The execution directory (${user.dir}). */
94 final Path execDirectory;
95 /** Base of the source code, typically the cloned git repository. */
96 final Path sdkSrcBase;
97 /**
98 * The base of the builder, typically a submodule pointing to the INCLUDEpublic
99 * argeo-build directory.
100 */
101 final Path argeoBuildBase;
102 /** The base of the build for all layers. */
103 final Path sdkBuildBase;
104 /** The base of the build for this layer. */
105 final Path buildBase;
106 /** The base of the a2 output for all layers. */
107 final Path a2Output;
108 /** The base of the a2 sources when packages separately. */
109 final Path a2srcOutput;
110
111 /** Whether sources should be packaged separately. */
112 final boolean sourceBundles;
113 /** Whether common legal files should be included. */
114 final boolean noSdkLegal;
115
116 /** Constructor initialises the base directories. */
117 public Make() throws IOException {
118 sourceBundles = Boolean.parseBoolean(System.getenv(ENV_SOURCE_BUNDLES));
119 if (sourceBundles)
120 logger.log(Level.INFO, "Sources will be packaged separately");
121 noSdkLegal = Boolean.parseBoolean(System.getenv(ENV_NO_SDK_LEGAL));
122 if (noSdkLegal)
123 logger.log(Level.INFO, "SDK legal files will NOT be included");
124
125 execDirectory = Paths.get(System.getProperty("user.dir"));
126 Path sdkMkP = findSdkMk(execDirectory);
127 Objects.requireNonNull(sdkMkP, "No " + SDK_MK + " found under " + execDirectory);
128
129 Map<String, String> context = readMakefileVariables(sdkMkP);
130 sdkSrcBase = Paths.get(context.computeIfAbsent(VAR_SDK_SRC_BASE, (key) -> {
131 throw new IllegalStateException(key + " not found");
132 })).toAbsolutePath();
133
134 Path argeoBuildBaseT = sdkSrcBase.resolve("sdk/argeo-build");
135 if (!Files.exists(argeoBuildBaseT)) {
136 String fromEnv = System.getenv(ENV_ARGEO_BUILD_CONFIG);
137 if (fromEnv != null)
138 argeoBuildBaseT = Paths.get(fromEnv);
139 if (fromEnv == null || !Files.exists(argeoBuildBaseT)) {
140 throw new IllegalStateException(
141 "Argeo Build not found. Did you initialise the git submodules or set the "
142 + ENV_ARGEO_BUILD_CONFIG + " environment variable?");
143 }
144 }
145 argeoBuildBase = argeoBuildBaseT;
146
147 sdkBuildBase = Paths.get(context.computeIfAbsent(VAR_SDK_BUILD_BASE, (key) -> {
148 throw new IllegalStateException(key + " not found");
149 })).toAbsolutePath();
150 buildBase = sdkBuildBase.resolve(sdkSrcBase.getFileName());
151 a2Output = sdkBuildBase.resolve("a2");
152 a2srcOutput = sdkBuildBase.resolve("a2.src");
153 }
154
155 /*
156 * ACTIONS
157 */
158 /** Compile and create the bundles in one go. */
159 void all(Map<String, List<String>> options) throws IOException {
160 compile(options);
161 bundle(options);
162 }
163
164 /** Compile all the bundles which have been passed via the --bundle argument. */
165 void compile(Map<String, List<String>> options) throws IOException {
166 List<String> bundles = options.get("--bundles");
167 Objects.requireNonNull(bundles, "--bundles argument must be set");
168 if (bundles.isEmpty())
169 return;
170
171 List<String> a2Categories = options.getOrDefault("--dep-categories", new ArrayList<>());
172 List<String> a2Bases = options.getOrDefault("--a2-bases", new ArrayList<>());
173 if (a2Bases.isEmpty() || !a2Bases.contains(a2Output.toString())) {
174 a2Bases.add(a2Output.toString());
175 }
176
177 List<String> compilerArgs = new ArrayList<>();
178
179 Path ecjArgs = argeoBuildBase.resolve("ecj.args");
180 compilerArgs.add("@" + ecjArgs);
181
182 // classpath
183 if (!a2Categories.isEmpty()) {
184 // We will keep only the highest major.minor
185 // and order by bundle name, for predictability
186 Map<String, A2Jar> a2Jars = new TreeMap<>();
187
188 // StringJoiner modulePath = new StringJoiner(File.pathSeparator);
189 for (String a2Base : a2Bases) {
190 categories: for (String a2Category : a2Categories) {
191 Path a2Dir = Paths.get(a2Base).resolve(a2Category);
192 if (!Files.exists(a2Dir))
193 continue categories;
194 // modulePath.add(a2Dir.toString());
195 for (Path jarP : Files.newDirectoryStream(a2Dir, (p) -> p.getFileName().toString().endsWith(".jar")
196 && !p.getFileName().toString().endsWith(".src.jar"))) {
197 A2Jar a2Jar = new A2Jar(jarP);
198 if (a2Jars.containsKey(a2Jar.name)) {
199 A2Jar current = a2Jars.get(a2Jar.name);
200 if (a2Jar.major > current.major)
201 a2Jars.put(a2Jar.name, a2Jar);
202 else if (a2Jar.major == current.major //
203 // if minor equals, we take the last one
204 && a2Jar.minor >= current.minor)
205 a2Jars.put(a2Jar.name, a2Jar);
206 } else {
207 a2Jars.put(a2Jar.name, a2Jar);
208 }
209 }
210 }
211 }
212
213 StringJoiner classPath = new StringJoiner(File.pathSeparator);
214 for (Iterator<A2Jar> it = a2Jars.values().iterator(); it.hasNext();)
215 classPath.add(it.next().path.toString());
216
217 compilerArgs.add("-cp");
218 compilerArgs.add(classPath.toString());
219 // compilerArgs.add("--module-path");
220 // compilerArgs.add(modulePath.toString());
221 }
222
223 // sources
224 for (String bundle : bundles) {
225 StringBuilder sb = new StringBuilder();
226 Path bundlePath = execDirectory.resolve(bundle);
227 if (!Files.exists(bundlePath)) {
228 if (bundles.size() == 1) {
229 logger.log(WARNING, "Bundle " + bundle + " not found in " + execDirectory
230 + ", assuming this is this directory, as only one bundle was requested.");
231 bundlePath = execDirectory;
232 } else
233 throw new IllegalArgumentException("Bundle " + bundle + " not found in " + execDirectory);
234 }
235 sb.append(bundlePath.resolve("src"));
236 sb.append("[-d");
237 compilerArgs.add(sb.toString());
238 sb = new StringBuilder();
239 sb.append(buildBase.resolve(bundle).resolve("bin"));
240 sb.append("]");
241 compilerArgs.add(sb.toString());
242 }
243
244 if (logger.isLoggable(INFO))
245 compilerArgs.add("-time");
246
247 if (logger.isLoggable(DEBUG)) {
248 logger.log(DEBUG, "Compiler arguments:");
249 for (String arg : compilerArgs)
250 logger.log(DEBUG, arg);
251 }
252
253 boolean success = org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
254 compilerArgs.toArray(new String[compilerArgs.size()]), new PrintWriter(System.out),
255 new PrintWriter(System.err), new MakeCompilationProgress());
256 if (!success) // kill the process if compilation failed
257 throw new IllegalStateException("Compilation failed");
258 }
259
260 /** Package the bundles. */
261 void bundle(Map<String, List<String>> options) throws IOException {
262 // check arguments
263 List<String> bundles = options.get("--bundles");
264 Objects.requireNonNull(bundles, "--bundles argument must be set");
265 if (bundles.isEmpty())
266 return;
267
268 List<String> categories = options.get("--category");
269 Objects.requireNonNull(bundles, "--category argument must be set");
270 if (categories.size() != 1)
271 throw new IllegalArgumentException("One and only one --category must be specified");
272 String category = categories.get(0);
273
274 final String branch;
275 Path branchMk = sdkSrcBase.resolve(BRANCH_MK);
276 if (Files.exists(branchMk)) {
277 Map<String, String> branchVariables = readMakefileVariables(branchMk);
278 branch = branchVariables.get("BRANCH");
279 } else {
280 branch = null;
281 }
282
283 long begin = System.currentTimeMillis();
284 // create jars in parallel
285 List<CompletableFuture<Void>> toDos = new ArrayList<>();
286 for (String bundle : bundles) {
287 toDos.add(CompletableFuture.runAsync(() -> {
288 try {
289 createBundle(branch, bundle, category);
290 } catch (IOException e) {
291 throw new RuntimeException("Packaging of " + bundle + " failed", e);
292 }
293 }));
294 }
295 CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
296 long duration = System.currentTimeMillis() - begin;
297 logger.log(INFO, "Packaging took " + duration + " ms");
298 }
299
300 /** Package a single bundle. */
301 void createBundle(String branch, String bundle, String category) throws IOException {
302 final Path source;
303 if (!Files.exists(execDirectory.resolve(bundle))) {
304 logger.log(WARNING,
305 "Bundle " + bundle + " not found in " + execDirectory + ", assuming this is this directory.");
306 source = execDirectory;
307 } else {
308 source = execDirectory.resolve(bundle);
309 }
310 Path srcP = source.resolve("src");
311
312 Path compiled = buildBase.resolve(bundle);
313 String bundleSymbolicName = source.getFileName().toString();
314
315 // Metadata
316 Properties properties = new Properties();
317 Path argeoBnd = argeoBuildBase.resolve("argeo.bnd");
318 try (InputStream in = Files.newInputStream(argeoBnd)) {
319 properties.load(in);
320 }
321
322 if (branch != null) {
323 Path branchBnd = sdkSrcBase.resolve("sdk/branches/" + branch + ".bnd");
324 if (Files.exists(branchBnd))
325 try (InputStream in = Files.newInputStream(branchBnd)) {
326 properties.load(in);
327 }
328 }
329
330 Path bndBnd = source.resolve("bnd.bnd");
331 if (Files.exists(bndBnd))
332 try (InputStream in = Files.newInputStream(bndBnd)) {
333 properties.load(in);
334 }
335
336 // Normalise
337 if (!properties.containsKey("Bundle-SymbolicName"))
338 properties.put("Bundle-SymbolicName", bundleSymbolicName);
339
340 // Calculate MANIFEST
341 Path binP = compiled.resolve("bin");
342 if (!Files.exists(binP))
343 Files.createDirectories(binP);
344 Manifest manifest;
345 try (Analyzer bndAnalyzer = new Analyzer()) {
346 bndAnalyzer.setProperties(properties);
347 Jar jar = new Jar(bundleSymbolicName, binP.toFile());
348 bndAnalyzer.setJar(jar);
349 manifest = bndAnalyzer.calcManifest();
350 } catch (Exception e) {
351 throw new RuntimeException("Bnd analysis of " + compiled + " failed", e);
352 }
353
354 String major = properties.getProperty("major");
355 Objects.requireNonNull(major, "'major' must be set");
356 String minor = properties.getProperty("minor");
357 Objects.requireNonNull(minor, "'minor' must be set");
358
359 // Write manifest
360 Path manifestP = compiled.resolve("META-INF/MANIFEST.MF");
361 Files.createDirectories(manifestP.getParent());
362 try (OutputStream out = Files.newOutputStream(manifestP)) {
363 manifest.write(out);
364 }
365
366 // Load excludes
367 List<PathMatcher> excludes = new ArrayList<>();
368 Path excludesP = argeoBuildBase.resolve("excludes.txt");
369 for (String line : Files.readAllLines(excludesP)) {
370 PathMatcher pathMatcher = excludesP.getFileSystem().getPathMatcher("glob:" + line);
371 excludes.add(pathMatcher);
372 }
373
374 Path bundleParent = Paths.get(bundle).getParent();
375 Path a2JarDirectory = bundleParent != null ? a2Output.resolve(bundleParent).resolve(category)
376 : a2Output.resolve(category);
377 Path jarP = a2JarDirectory.resolve(compiled.getFileName() + "." + major + "." + minor + ".jar");
378 Files.createDirectories(jarP.getParent());
379
380 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarP), manifest)) {
381 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
382 // add all classes first
383 Files.walkFileTree(binP, new SimpleFileVisitor<Path>() {
384 @Override
385 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
386 jarOut.putNextEntry(new JarEntry(binP.relativize(file).toString()));
387 Files.copy(file, jarOut);
388 return FileVisitResult.CONTINUE;
389 }
390 });
391
392 // add resources
393 Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
394 @Override
395 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
396 // skip output directory if it happens to be within the sources
397 if (Files.isSameFile(sdkBuildBase, dir))
398 return FileVisitResult.SKIP_SUBTREE;
399
400 // skip excluded patterns
401 Path relativeP = source.relativize(dir);
402 for (PathMatcher exclude : excludes)
403 if (exclude.matches(relativeP))
404 return FileVisitResult.SKIP_SUBTREE;
405
406 return FileVisitResult.CONTINUE;
407 }
408
409 @Override
410 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
411 Path relativeP = source.relativize(file);
412 for (PathMatcher exclude : excludes)
413 if (exclude.matches(relativeP))
414 return FileVisitResult.CONTINUE;
415 JarEntry entry = new JarEntry(relativeP.toString());
416 jarOut.putNextEntry(entry);
417 Files.copy(file, jarOut);
418 return FileVisitResult.CONTINUE;
419 }
420 });
421
422 // Add all resources from src/
423 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
424 @Override
425 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
426 if (file.getFileName().toString().endsWith(".java")
427 || file.getFileName().toString().endsWith(".class"))
428 return FileVisitResult.CONTINUE;
429 jarOut.putNextEntry(new JarEntry(srcP.relativize(file).toString()));
430 if (!Files.isDirectory(file))
431 Files.copy(file, jarOut);
432 return FileVisitResult.CONTINUE;
433 }
434 });
435
436 // add legal notices and licenses
437 for (Path p : listLegalFilesToInclude(source).values()) {
438 jarOut.putNextEntry(new JarEntry(p.getFileName().toString()));
439 Files.copy(p, jarOut);
440 }
441
442 // add sources
443 // TODO add effective BND, Eclipse project file, etc., in order to be able to
444 // repackage
445 if (!sourceBundles) {
446 copySourcesToJar(srcP, jarOut, "OSGI-OPT/src/");
447 }
448 }
449
450 if (sourceBundles) {// create separate sources jar
451 Path a2srcJarDirectory = bundleParent != null ? a2srcOutput.resolve(bundleParent).resolve(category)
452 : a2srcOutput.resolve(category);
453 Files.createDirectories(a2srcJarDirectory);
454 Path srcJarP = a2srcJarDirectory.resolve(compiled.getFileName() + "." + major + "." + minor + ".src.jar");
455 Manifest srcManifest = new Manifest();
456 srcManifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
457 srcManifest.getMainAttributes().putValue("Bundle-SymbolicName", bundleSymbolicName + ".src");
458 srcManifest.getMainAttributes().putValue("Bundle-Version",
459 manifest.getMainAttributes().getValue("Bundle-Version").toString());
460 srcManifest.getMainAttributes().putValue("Eclipse-SourceBundle",
461 bundleSymbolicName + ";version=\"" + manifest.getMainAttributes().getValue("Bundle-Version"));
462
463 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
464 copySourcesToJar(srcP, srcJarOut, "");
465 // add legal notices and licenses
466 for (Path p : listLegalFilesToInclude(source).values()) {
467 srcJarOut.putNextEntry(new JarEntry(p.getFileName().toString()));
468 Files.copy(p, srcJarOut);
469 }
470 }
471 }
472 }
473
474 /** List the relevant legal files to include, from the SDK source base. */
475 Map<String, Path> listLegalFilesToInclude(Path bundleBase) throws IOException {
476 Map<String, Path> toInclude = new HashMap<>();
477 if (!noSdkLegal) {
478 DirectoryStream<Path> sdkSrcLegal = Files.newDirectoryStream(sdkSrcBase, (p) -> {
479 String fileName = p.getFileName().toString();
480 return switch (fileName) {
481 case "NOTICE":
482 case "LICENSE":
483 case "COPYING":
484 case "COPYING.LESSER":
485 yield true;
486 default:
487 yield false;
488 };
489 });
490 for (Path p : sdkSrcLegal)
491 toInclude.put(p.getFileName().toString(), p);
492 }
493 for (Iterator<Map.Entry<String, Path>> entries = toInclude.entrySet().iterator(); entries.hasNext();) {
494 Map.Entry<String, Path> entry = entries.next();
495 Path inBundle = bundleBase.resolve(entry.getValue().getFileName());
496 // remove file if it is also defined at bundle level
497 // since it has already been copied
498 // and has priority
499 if (Files.exists(inBundle))
500 entries.remove();
501 }
502 return toInclude;
503 }
504
505 /*
506 * UTILITIES
507 */
508 /** Add sources to a jar file */
509 void copySourcesToJar(Path srcP, JarOutputStream srcJarOut, String prefix) throws IOException {
510 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
511 @Override
512 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
513 srcJarOut.putNextEntry(new JarEntry(prefix + srcP.relativize(file).toString()));
514 if (!Files.isDirectory(file))
515 Files.copy(file, srcJarOut);
516 return FileVisitResult.CONTINUE;
517 }
518 });
519 }
520
521 /**
522 * Recursively find the base source directory (which contains the
523 * <code>{@value #SDK_MK}</code> file).
524 */
525 Path findSdkMk(Path directory) {
526 Path sdkMkP = directory.resolve(SDK_MK);
527 if (Files.exists(sdkMkP)) {
528 return sdkMkP.toAbsolutePath();
529 }
530 if (directory.getParent() == null)
531 return null;
532 return findSdkMk(directory.getParent());
533 }
534
535 /**
536 * Reads Makefile variable assignments of the form =, :=, or ?=, ignoring white
537 * spaces. To be used with very simple included Makefiles only.
538 */
539 Map<String, String> readMakefileVariables(Path path) throws IOException {
540 Map<String, String> context = new HashMap<>();
541 List<String> sdkMkLines = Files.readAllLines(path);
542 lines: for (String line : sdkMkLines) {
543 StringTokenizer st = new StringTokenizer(line, " :=?");
544 if (!st.hasMoreTokens())
545 continue lines;
546 String key = st.nextToken();
547 if (!st.hasMoreTokens())
548 continue lines;
549 String value = st.nextToken();
550 if (st.hasMoreTokens()) // probably not a simple variable assignment
551 continue lines;
552 context.put(key, value);
553 }
554 return context;
555 }
556
557 /** Main entry point, interpreting actions and arguments. */
558 public static void main(String... args) {
559 if (args.length == 0)
560 throw new IllegalArgumentException("At least an action must be provided");
561 int actionIndex = 0;
562 String action = args[actionIndex];
563 if (args.length > actionIndex + 1 && !args[actionIndex + 1].startsWith("-"))
564 throw new IllegalArgumentException(
565 "Action " + action + " must be followed by an option: " + Arrays.asList(args));
566
567 Map<String, List<String>> options = new HashMap<>();
568 String currentOption = null;
569 for (int i = actionIndex + 1; i < args.length; i++) {
570 if (args[i].startsWith("-")) {
571 currentOption = args[i];
572 if (!options.containsKey(currentOption))
573 options.put(currentOption, new ArrayList<>());
574
575 } else {
576 options.get(currentOption).add(args[i]);
577 }
578 }
579
580 try {
581 Make argeoMake = new Make();
582 switch (action) {
583 case "compile" -> argeoMake.compile(options);
584 case "bundle" -> argeoMake.bundle(options);
585 case "all" -> argeoMake.all(options);
586
587 default -> throw new IllegalArgumentException("Unkown action: " + action);
588 }
589
590 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
591 logger.log(INFO, "Make.java action '" + action + "' succesfully completed after " + (jvmUptime / 1000) + "."
592 + (jvmUptime % 1000) + " s");
593 } catch (Exception e) {
594 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
595 logger.log(ERROR, "Make.java action '" + action + "' failed after " + (jvmUptime / 1000) + "."
596 + (jvmUptime % 1000) + " s", e);
597 System.exit(1);
598 }
599 }
600
601 /** A jar file in A2 format */
602 static class A2Jar {
603 final Path path;
604 final String name;
605 final int major;
606 final int minor;
607
608 A2Jar(Path path) {
609 try {
610 this.path = path;
611 String fileName = path.getFileName().toString();
612 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
613 minor = Integer.parseInt(fileName.substring(fileName.lastIndexOf('.') + 1));
614 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
615 major = Integer.parseInt(fileName.substring(fileName.lastIndexOf('.') + 1));
616 name = fileName.substring(0, fileName.lastIndexOf('.'));
617 } catch (Exception e) {
618 throw new IllegalArgumentException("Badly formatted A2 jar " + path, e);
619 }
620 }
621 }
622
623 /**
624 * An ECJ {@link CompilationProgress} printing a progress bar while compiling.
625 */
626 static class MakeCompilationProgress extends CompilationProgress {
627 private int totalWork;
628 private long currentChunk = 0;
629 private long chunksCount = 80;
630
631 @Override
632 public void worked(int workIncrement, int remainingWork) {
633 if (!logger.isLoggable(Level.INFO)) // progress bar only at INFO level
634 return;
635 long chunk = ((totalWork - remainingWork) * chunksCount) / totalWork;
636 if (chunk != currentChunk) {
637 currentChunk = chunk;
638 for (long i = 0; i < currentChunk; i++) {
639 System.out.print("#");
640 }
641 for (long i = currentChunk; i < chunksCount; i++) {
642 System.out.print("-");
643 }
644 System.out.print("\r");
645 }
646 if (remainingWork == 0)
647 System.out.print("\n");
648 }
649
650 @Override
651 public void setTaskName(String name) {
652 }
653
654 @Override
655 public boolean isCanceled() {
656 return false;
657 }
658
659 @Override
660 public void done() {
661 }
662
663 @Override
664 public void begin(int remainingWork) {
665 this.totalWork = remainingWork;
666 }
667 }
668 }