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