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