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