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