]> git.argeo.org Git - cc0/argeo-build.git/blob - src/org/argeo/build/Make.java
beacf017ed4a68bd13e68fc78f5146020d6342cb
[cc0/argeo-build.git] / src / org / argeo / build / Make.java
1 package org.argeo.build;
2
3 import static java.lang.System.Logger.Level.ERROR;
4 import static java.lang.System.Logger.Level.INFO;
5
6 import java.io.File;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.OutputStream;
10 import java.io.PrintWriter;
11 import java.lang.System.Logger;
12 import java.lang.System.Logger.Level;
13 import java.lang.management.ManagementFactory;
14 import java.nio.file.FileVisitResult;
15 import java.nio.file.Files;
16 import java.nio.file.Path;
17 import java.nio.file.PathMatcher;
18 import java.nio.file.Paths;
19 import java.nio.file.SimpleFileVisitor;
20 import java.nio.file.attribute.BasicFileAttributes;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.HashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Objects;
27 import java.util.Properties;
28 import java.util.StringJoiner;
29 import java.util.StringTokenizer;
30 import java.util.concurrent.CompletableFuture;
31 import java.util.jar.JarEntry;
32 import java.util.jar.JarOutputStream;
33 import java.util.jar.Manifest;
34 import java.util.zip.Deflater;
35
36 import org.eclipse.jdt.core.compiler.CompilationProgress;
37
38 import aQute.bnd.osgi.Analyzer;
39 import aQute.bnd.osgi.Jar;
40
41 /**
42 * Minimalistic OSGi compiler and packager, meant to be used as a single file
43 * without being itself compiled first. It depends on the Eclipse batch compiler
44 * (aka. ECJ) and the BND Libs library for OSGi metadata generation (which
45 * itselfs depends on slf4j).<br/>
46 * <br/>
47 * For example, a typical system call would be:<br/>
48 * <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>
49 */
50 public class Make {
51 private final static Logger logger = System.getLogger(Make.class.getName());
52
53 /**
54 * Environment properties on whether sources should be packaged separately or
55 * integrated in the bundles.
56 */
57 private final static String ENV_BUILD_SOURCE_BUNDLES = "BUILD_SOURCE_BUNDLES";
58
59 /** Name of the local-specific Makefile (sdk.mk). */
60 final static String SDK_MK = "sdk.mk";
61 /** Name of the branch definition Makefile (branch.mk). */
62 final static String BRANCH_MK = "branch.mk";
63
64 /** The execution directory (${user.dir}). */
65 final Path execDirectory;
66 /** Base of the source code, typically the cloned git repository. */
67 final Path sdkSrcBase;
68 /**
69 * The base of the builder, typically a submodule pointing to the public
70 * argeo-build directory.
71 */
72 final Path argeoBuildBase;
73 /** The base of the build for all layers. */
74 final Path sdkBuildBase;
75 /** The base of the build for this layer. */
76 final Path buildBase;
77 /** The base of the a2 output for all layers. */
78 final Path a2Output;
79
80 /** Whether sources should be packaged separately */
81 final boolean sourceBundles;
82
83 /** Constructor initialises the base directories. */
84 public Make() throws IOException {
85 sourceBundles = Boolean.parseBoolean(System.getenv(ENV_BUILD_SOURCE_BUNDLES));
86 if (sourceBundles)
87 logger.log(Level.INFO, "Sources will be packaged separately");
88
89 execDirectory = Paths.get(System.getProperty("user.dir"));
90 Path sdkMkP = findSdkMk(execDirectory);
91 Objects.requireNonNull(sdkMkP, "No " + SDK_MK + " found under " + execDirectory);
92
93 Map<String, String> context = readeMakefileVariables(sdkMkP);
94 sdkSrcBase = Paths.get(context.computeIfAbsent("SDK_SRC_BASE", (key) -> {
95 throw new IllegalStateException(key + " not found");
96 })).toAbsolutePath();
97 argeoBuildBase = sdkSrcBase.resolve("sdk/argeo-build");
98
99 sdkBuildBase = Paths.get(context.computeIfAbsent("SDK_BUILD_BASE", (key) -> {
100 throw new IllegalStateException(key + " not found");
101 })).toAbsolutePath();
102 buildBase = sdkBuildBase.resolve(sdkSrcBase.getFileName());
103 a2Output = sdkBuildBase.resolve("a2");
104 }
105
106 /*
107 * ACTIONS
108 */
109 /** Compile and create the bundles in one go. */
110 void all(Map<String, List<String>> options) throws IOException {
111 compile(options);
112 bundle(options);
113 }
114
115 /** Compile all the bundles which have been passed via the --bundle argument. */
116 @SuppressWarnings("restriction")
117 void compile(Map<String, List<String>> options) throws IOException {
118 List<String> bundles = options.get("--bundles");
119 Objects.requireNonNull(bundles, "--bundles argument must be set");
120 if (bundles.isEmpty())
121 return;
122
123 List<String> a2Categories = options.getOrDefault("--dep-categories", new ArrayList<>());
124 List<String> a2Bases = options.getOrDefault("--a2-bases", new ArrayList<>());
125 if (a2Bases.isEmpty()) {
126 a2Bases.add(a2Output.toString());
127 }
128
129 List<String> compilerArgs = new ArrayList<>();
130
131 Path ecjArgs = argeoBuildBase.resolve("ecj.args");
132 compilerArgs.add("@" + ecjArgs);
133
134 // classpath
135 if (!a2Categories.isEmpty()) {
136 StringJoiner classPath = new StringJoiner(File.pathSeparator);
137 StringJoiner modulePath = new StringJoiner(File.pathSeparator);
138 for (String a2Base : a2Bases) {
139 for (String a2Category : a2Categories) {
140 Path a2Dir = Paths.get(a2Base).resolve(a2Category);
141 if (!Files.exists(a2Dir))
142 Files.createDirectories(a2Dir);
143 modulePath.add(a2Dir.toString());
144 for (Path jarP : Files.newDirectoryStream(a2Dir,
145 (p) -> p.getFileName().toString().endsWith(".jar"))) {
146 classPath.add(jarP.toString());
147 }
148 }
149 }
150 compilerArgs.add("-cp");
151 compilerArgs.add(classPath.toString());
152 // compilerArgs.add("--module-path");
153 // compilerArgs.add(modulePath.toString());
154 }
155
156 // sources
157 for (String bundle : bundles) {
158 StringBuilder sb = new StringBuilder();
159 Path bundlePath = execDirectory.resolve(bundle);
160 if (!Files.exists(bundlePath))
161 throw new IllegalArgumentException("Bundle " + bundle + " not found in " + execDirectory);
162 sb.append(bundlePath.resolve("src"));
163 sb.append("[-d");
164 compilerArgs.add(sb.toString());
165 sb = new StringBuilder();
166 sb.append(buildBase.resolve(bundle).resolve("bin"));
167 sb.append("]");
168 compilerArgs.add(sb.toString());
169 }
170
171 if (logger.isLoggable(INFO))
172 compilerArgs.add("-time");
173
174 // for (String arg : compilerArgs)
175 // System.out.println(arg);
176
177 boolean success = org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
178 compilerArgs.toArray(new String[compilerArgs.size()]), new PrintWriter(System.out),
179 new PrintWriter(System.err), new MakeCompilationProgress());
180 if (!success) // kill the process if compilation failed
181 throw new IllegalStateException("Compilation failed");
182 }
183
184 /** Package the bundles. */
185 void bundle(Map<String, List<String>> options) throws IOException {
186 // check arguments
187 List<String> bundles = options.get("--bundles");
188 Objects.requireNonNull(bundles, "--bundles argument must be set");
189 if (bundles.isEmpty())
190 return;
191
192 List<String> categories = options.get("--category");
193 Objects.requireNonNull(bundles, "--category argument must be set");
194 if (categories.size() != 1)
195 throw new IllegalArgumentException("One and only one --category must be specified");
196 String category = categories.get(0);
197
198 final String branch;
199 Path branchMk = sdkSrcBase.resolve(BRANCH_MK);
200 if (Files.exists(branchMk)) {
201 Map<String, String> branchVariables = readeMakefileVariables(branchMk);
202 branch = branchVariables.get("BRANCH");
203 } else {
204 branch = null;
205 }
206
207 long begin = System.currentTimeMillis();
208 // create jars in parallel
209 List<CompletableFuture<Void>> toDos = new ArrayList<>();
210 for (String bundle : bundles) {
211 toDos.add(CompletableFuture.runAsync(() -> {
212 try {
213 createBundle(branch, bundle, category);
214 } catch (IOException e) {
215 throw new RuntimeException("Packaging of " + bundle + " failed", e);
216 }
217 }));
218 }
219 CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
220 long duration = System.currentTimeMillis() - begin;
221 logger.log(INFO, "Packaging took " + duration + " ms");
222 }
223
224 /*
225 * UTILITIES
226 */
227 /** Package a single bundle. */
228 void createBundle(String branch, String bundle, String category) throws IOException {
229 Path source = execDirectory.resolve(bundle);
230 Path compiled = buildBase.resolve(bundle);
231 String bundleSymbolicName = source.getFileName().toString();
232
233 // Metadata
234 Properties properties = new Properties();
235 Path argeoBnd = argeoBuildBase.resolve("argeo.bnd");
236 try (InputStream in = Files.newInputStream(argeoBnd)) {
237 properties.load(in);
238 }
239
240 if (branch != null) {
241 Path branchBnd = sdkSrcBase.resolve("sdk/branches/" + branch + ".bnd");
242 if (Files.exists(branchBnd))
243 try (InputStream in = Files.newInputStream(branchBnd)) {
244 properties.load(in);
245 }
246 }
247
248 Path bndBnd = source.resolve("bnd.bnd");
249 if (Files.exists(bndBnd))
250 try (InputStream in = Files.newInputStream(bndBnd)) {
251 properties.load(in);
252 }
253
254 // Normalise
255 if (!properties.containsKey("Bundle-SymbolicName"))
256 properties.put("Bundle-SymbolicName", bundleSymbolicName);
257
258 // Calculate MANIFEST
259 Path binP = compiled.resolve("bin");
260 if (!Files.exists(binP))
261 Files.createDirectories(binP);
262 Manifest manifest;
263 try (Analyzer bndAnalyzer = new Analyzer()) {
264 bndAnalyzer.setProperties(properties);
265 Jar jar = new Jar(bundleSymbolicName, binP.toFile());
266 bndAnalyzer.setJar(jar);
267 manifest = bndAnalyzer.calcManifest();
268 } catch (Exception e) {
269 throw new RuntimeException("Bnd analysis of " + compiled + " failed", e);
270 }
271
272 String major = properties.getProperty("major");
273 Objects.requireNonNull(major, "'major' must be set");
274 String minor = properties.getProperty("minor");
275 Objects.requireNonNull(minor, "'minor' must be set");
276
277 // Write manifest
278 Path manifestP = compiled.resolve("META-INF/MANIFEST.MF");
279 Files.createDirectories(manifestP.getParent());
280 try (OutputStream out = Files.newOutputStream(manifestP)) {
281 manifest.write(out);
282 }
283
284 // Load excludes
285 List<PathMatcher> excludes = new ArrayList<>();
286 Path excludesP = argeoBuildBase.resolve("excludes.txt");
287 for (String line : Files.readAllLines(excludesP)) {
288 PathMatcher pathMatcher = excludesP.getFileSystem().getPathMatcher("glob:" + line);
289 excludes.add(pathMatcher);
290 }
291
292 Path bundleParent = Paths.get(bundle).getParent();
293 Path a2JarDirectory = bundleParent != null ? a2Output.resolve(bundleParent).resolve(category)
294 : a2Output.resolve(category);
295 Path jarP = a2JarDirectory.resolve(compiled.getFileName() + "." + major + "." + minor + ".jar");
296 Files.createDirectories(jarP.getParent());
297
298 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarP), manifest)) {
299 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
300 // add all classes first
301 Files.walkFileTree(binP, new SimpleFileVisitor<Path>() {
302 @Override
303 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
304 jarOut.putNextEntry(new JarEntry(binP.relativize(file).toString()));
305 Files.copy(file, jarOut);
306 return FileVisitResult.CONTINUE;
307 }
308 });
309
310 // add resources
311 Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
312 @Override
313 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
314 Path relativeP = source.relativize(dir);
315 for (PathMatcher exclude : excludes)
316 if (exclude.matches(relativeP))
317 return FileVisitResult.SKIP_SUBTREE;
318
319 return FileVisitResult.CONTINUE;
320 }
321
322 @Override
323 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
324 Path relativeP = source.relativize(file);
325 for (PathMatcher exclude : excludes)
326 if (exclude.matches(relativeP))
327 return FileVisitResult.CONTINUE;
328 JarEntry entry = new JarEntry(relativeP.toString());
329 jarOut.putNextEntry(entry);
330 Files.copy(file, jarOut);
331 return FileVisitResult.CONTINUE;
332 }
333 });
334
335 Path srcP = source.resolve("src");
336 // Add all resources from src/
337 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
338 @Override
339 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
340 if (file.getFileName().toString().endsWith(".java")
341 || file.getFileName().toString().endsWith(".class"))
342 return FileVisitResult.CONTINUE;
343 jarOut.putNextEntry(new JarEntry(srcP.relativize(file).toString()));
344 if (!Files.isDirectory(file))
345 Files.copy(file, jarOut);
346 return FileVisitResult.CONTINUE;
347 }
348 });
349
350 // add sources
351 // TODO add effective BND, Eclipse project file, etc., in order to be able to
352 // repackage
353 if (sourceBundles) {
354 // TODO package sources separately
355 } else {
356 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
357 @Override
358 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
359 jarOut.putNextEntry(new JarEntry("OSGI-OPT/src/" + srcP.relativize(file).toString()));
360 if (!Files.isDirectory(file))
361 Files.copy(file, jarOut);
362 return FileVisitResult.CONTINUE;
363 }
364 });
365 }
366 }
367 }
368
369 /**
370 * Recursively find the base source directory (which contains the
371 * <code>{@value #SDK_MK}</code> file).
372 */
373 Path findSdkMk(Path directory) {
374 Path sdkMkP = directory.resolve(SDK_MK);
375 if (Files.exists(sdkMkP)) {
376 return sdkMkP.toAbsolutePath();
377 }
378 if (directory.getParent() == null)
379 return null;
380 return findSdkMk(directory.getParent());
381 }
382
383 /**
384 * Reads Makefile variable assignments of the form =, :=, or ?=, ignoring white
385 * spaces. To be used with very simple included Makefiles only.
386 */
387 Map<String, String> readeMakefileVariables(Path path) throws IOException {
388 Map<String, String> context = new HashMap<>();
389 List<String> sdkMkLines = Files.readAllLines(path);
390 lines: for (String line : sdkMkLines) {
391 StringTokenizer st = new StringTokenizer(line, " :=?");
392 if (!st.hasMoreTokens())
393 continue lines;
394 String key = st.nextToken();
395 if (!st.hasMoreTokens())
396 continue lines;
397 String value = st.nextToken();
398 if (st.hasMoreTokens()) // probably not a simple variable assignment
399 continue lines;
400 context.put(key, value);
401 }
402 return context;
403 }
404
405 /** Main entry point, interpreting actions and arguments. */
406 public static void main(String... args) {
407 if (args.length == 0)
408 throw new IllegalArgumentException("At least an action must be provided");
409 int actionIndex = 0;
410 String action = args[actionIndex];
411 if (args.length > actionIndex + 1 && !args[actionIndex + 1].startsWith("-"))
412 throw new IllegalArgumentException(
413 "Action " + action + " must be followed by an option: " + Arrays.asList(args));
414
415 Map<String, List<String>> options = new HashMap<>();
416 String currentOption = null;
417 for (int i = actionIndex + 1; i < args.length; i++) {
418 if (args[i].startsWith("-")) {
419 currentOption = args[i];
420 if (!options.containsKey(currentOption))
421 options.put(currentOption, new ArrayList<>());
422
423 } else {
424 options.get(currentOption).add(args[i]);
425 }
426 }
427
428 try {
429 Make argeoMake = new Make();
430 switch (action) {
431 case "compile" -> argeoMake.compile(options);
432 case "bundle" -> argeoMake.bundle(options);
433 case "all" -> argeoMake.all(options);
434
435 default -> throw new IllegalArgumentException("Unkown action: " + action);
436 }
437
438 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
439 logger.log(INFO, "Make.java action '" + action + "' succesfully completed after " + (jvmUptime / 1000) + "."
440 + (jvmUptime % 1000) + " s");
441 } catch (Exception e) {
442 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
443 logger.log(ERROR, "Make.java action '" + action + "' failed after " + (jvmUptime / 1000) + "."
444 + (jvmUptime % 1000) + " s", e);
445 System.exit(1);
446 }
447 }
448
449 /**
450 * An ECJ {@link CompilationProgress} printing a progress bar while compiling.
451 */
452 static class MakeCompilationProgress extends CompilationProgress {
453 private int totalWork;
454 private long currentChunk = 0;
455 private long chunksCount = 80;
456
457 @Override
458 public void worked(int workIncrement, int remainingWork) {
459 if (!logger.isLoggable(Level.INFO)) // progress bar only at INFO level
460 return;
461 long chunk = ((totalWork - remainingWork) * chunksCount) / totalWork;
462 if (chunk != currentChunk) {
463 currentChunk = chunk;
464 for (long i = 0; i < currentChunk; i++) {
465 System.out.print("#");
466 }
467 for (long i = currentChunk; i < chunksCount; i++) {
468 System.out.print("-");
469 }
470 System.out.print("\r");
471 }
472 if (remainingWork == 0)
473 System.out.print("\n");
474 }
475
476 @Override
477 public void setTaskName(String name) {
478 }
479
480 @Override
481 public boolean isCanceled() {
482 return false;
483 }
484
485 @Override
486 public void done() {
487 }
488
489 @Override
490 public void begin(int remainingWork) {
491 this.totalWork = remainingWork;
492 }
493 }
494 }