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