1 package org
.argeo
.build
;
3 import static java
.lang
.System
.Logger
.Level
.ERROR
;
4 import static java
.lang
.System
.Logger
.Level
.INFO
;
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
;
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
;
36 import org
.eclipse
.jdt
.core
.compiler
.CompilationProgress
;
38 import aQute
.bnd
.osgi
.Analyzer
;
39 import aQute
.bnd
.osgi
.Jar
;
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/>
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>
51 private final static Logger logger
= System
.getLogger(Make
.class.getName());
53 /** Name of the local-specific Makefile (sdk.mk). */
54 final static String SDK_MK
= "sdk.mk";
55 /** Name of the branch definition Makefile (branch.mk). */
56 final static String BRANCH_MK
= "branch.mk";
58 /** The execution directory (${user.dir}). */
59 final Path execDirectory
;
60 /** Base of the source code, typically the cloned git repository. */
61 final Path sdkSrcBase
;
63 * The base of the builder, typically a submodule pointing to the public
64 * argeo-build directory.
66 final Path argeoBuildBase
;
67 /** The base of the build for all layers. */
68 final Path sdkBuildBase
;
69 /** The base of the build for this layer. */
71 /** The base of the a2 output for all layers. */
74 /** Constructor initialises the base directories. */
75 public Make() throws IOException
{
76 execDirectory
= Paths
.get(System
.getProperty("user.dir"));
77 Path sdkMkP
= findSdkMk(execDirectory
);
78 Objects
.requireNonNull(sdkMkP
, "No " + SDK_MK
+ " found under " + execDirectory
);
80 Map
<String
, String
> context
= readeMakefileVariables(sdkMkP
);
81 sdkSrcBase
= Paths
.get(context
.computeIfAbsent("SDK_SRC_BASE", (key
) -> {
82 throw new IllegalStateException(key
+ " not found");
84 argeoBuildBase
= sdkSrcBase
.resolve("sdk/argeo-build");
86 sdkBuildBase
= Paths
.get(context
.computeIfAbsent("SDK_BUILD_BASE", (key
) -> {
87 throw new IllegalStateException(key
+ " not found");
89 buildBase
= sdkBuildBase
.resolve(sdkSrcBase
.getFileName());
90 a2Output
= sdkBuildBase
.resolve("a2");
96 /** Compile and create the bundles in one go. */
97 void all(Map
<String
, List
<String
>> options
) throws IOException
{
102 /** Compile all the bundles which have been passed via the --bundle argument. */
103 @SuppressWarnings("restriction")
104 void compile(Map
<String
, List
<String
>> options
) throws IOException
{
105 List
<String
> bundles
= options
.get("--bundles");
106 Objects
.requireNonNull(bundles
, "--bundles argument must be set");
107 if (bundles
.isEmpty())
110 List
<String
> a2Categories
= options
.getOrDefault("--dep-categories", new ArrayList
<>());
111 List
<String
> a2Bases
= options
.getOrDefault("--a2-bases", new ArrayList
<>());
112 if (a2Bases
.isEmpty()) {
113 a2Bases
.add(a2Output
.toString());
116 List
<String
> compilerArgs
= new ArrayList
<>();
118 Path ecjArgs
= argeoBuildBase
.resolve("ecj.args");
119 compilerArgs
.add("@" + ecjArgs
);
122 if (!a2Categories
.isEmpty()) {
123 StringJoiner classPath
= new StringJoiner(File
.pathSeparator
);
124 StringJoiner modulePath
= new StringJoiner(File
.pathSeparator
);
125 for (String a2Base
: a2Bases
) {
126 for (String a2Category
: a2Categories
) {
127 Path a2Dir
= Paths
.get(a2Base
).resolve(a2Category
);
128 if (!Files
.exists(a2Dir
))
129 Files
.createDirectories(a2Dir
);
130 modulePath
.add(a2Dir
.toString());
131 for (Path jarP
: Files
.newDirectoryStream(a2Dir
,
132 (p
) -> p
.getFileName().toString().endsWith(".jar"))) {
133 classPath
.add(jarP
.toString());
137 compilerArgs
.add("-cp");
138 compilerArgs
.add(classPath
.toString());
139 // compilerArgs.add("--module-path");
140 // compilerArgs.add(modulePath.toString());
144 for (String bundle
: bundles
) {
145 StringBuilder sb
= new StringBuilder();
146 Path bundlePath
= execDirectory
.resolve(bundle
);
147 if (!Files
.exists(bundlePath
))
148 throw new IllegalArgumentException("Bundle " + bundle
+ " not found in " + execDirectory
);
149 sb
.append(bundlePath
.resolve("src"));
151 compilerArgs
.add(sb
.toString());
152 sb
= new StringBuilder();
153 sb
.append(buildBase
.resolve(bundle
).resolve("bin"));
155 compilerArgs
.add(sb
.toString());
158 if (logger
.isLoggable(INFO
))
159 compilerArgs
.add("-time");
161 // for (String arg : compilerArgs)
162 // System.out.println(arg);
164 boolean success
= org
.eclipse
.jdt
.core
.compiler
.batch
.BatchCompiler
.compile(
165 compilerArgs
.toArray(new String
[compilerArgs
.size()]), new PrintWriter(System
.out
),
166 new PrintWriter(System
.err
), new MakeCompilationProgress());
167 if (!success
) // kill the process if compilation failed
168 throw new IllegalStateException("Compilation failed");
171 /** Package the bundles. */
172 void bundle(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())
179 List
<String
> categories
= options
.get("--category");
180 Objects
.requireNonNull(bundles
, "--category argument must be set");
181 if (categories
.size() != 1)
182 throw new IllegalArgumentException("One and only one --category must be specified");
183 String category
= categories
.get(0);
185 Path branchMk
= sdkSrcBase
.resolve(BRANCH_MK
);
186 if (!Files
.exists(branchMk
))
187 throw new IllegalStateException("No " + branchMk
+ " file available");
188 Map
<String
, String
> branchVariables
= readeMakefileVariables(branchMk
);
190 String branch
= branchVariables
.get("BRANCH");
192 long begin
= System
.currentTimeMillis();
193 // create jars in parallel
194 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
195 for (String bundle
: bundles
) {
196 toDos
.add(CompletableFuture
.runAsync(() -> {
198 createBundle(branch
, bundle
, category
);
199 } catch (IOException e
) {
200 throw new RuntimeException("Packaging of " + bundle
+ " failed", e
);
204 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
205 long duration
= System
.currentTimeMillis() - begin
;
206 logger
.log(INFO
, "Packaging took " + duration
+ " ms");
212 /** Package a single bundle. */
213 void createBundle(String branch
, String bundle
, String category
) throws IOException
{
214 Path source
= execDirectory
.resolve(bundle
);
215 Path compiled
= buildBase
.resolve(bundle
);
216 String bundleSymbolicName
= source
.getFileName().toString();
219 Properties properties
= new Properties();
220 Path argeoBnd
= argeoBuildBase
.resolve("argeo.bnd");
221 try (InputStream in
= Files
.newInputStream(argeoBnd
)) {
225 Path branchBnd
= sdkSrcBase
.resolve("sdk/branches/" + branch
+ ".bnd");
226 try (InputStream in
= Files
.newInputStream(branchBnd
)) {
230 Path bndBnd
= source
.resolve("bnd.bnd");
231 try (InputStream in
= Files
.newInputStream(bndBnd
)) {
236 if (!properties
.containsKey("Bundle-SymbolicName"))
237 properties
.put("Bundle-SymbolicName", bundleSymbolicName
);
239 // Calculate MANIFEST
240 Path binP
= compiled
.resolve("bin");
241 if (!Files
.exists(binP
))
242 Files
.createDirectories(binP
);
244 try (Analyzer bndAnalyzer
= new Analyzer()) {
245 bndAnalyzer
.setProperties(properties
);
246 Jar jar
= new Jar(bundleSymbolicName
, binP
.toFile());
247 bndAnalyzer
.setJar(jar
);
248 manifest
= bndAnalyzer
.calcManifest();
249 } catch (Exception e
) {
250 throw new RuntimeException("Bnd analysis of " + compiled
+ " failed", e
);
253 String major
= properties
.getProperty("major");
254 Objects
.requireNonNull(major
, "'major' must be set");
255 String minor
= properties
.getProperty("minor");
256 Objects
.requireNonNull(minor
, "'minor' must be set");
259 Path manifestP
= compiled
.resolve("META-INF/MANIFEST.MF");
260 Files
.createDirectories(manifestP
.getParent());
261 try (OutputStream out
= Files
.newOutputStream(manifestP
)) {
266 List
<PathMatcher
> excludes
= new ArrayList
<>();
267 Path excludesP
= argeoBuildBase
.resolve("excludes.txt");
268 for (String line
: Files
.readAllLines(excludesP
)) {
269 PathMatcher pathMatcher
= excludesP
.getFileSystem().getPathMatcher("glob:" + line
);
270 excludes
.add(pathMatcher
);
273 Path bundleParent
= Paths
.get(bundle
).getParent();
274 Path a2JarDirectory
= bundleParent
!= null ? a2Output
.resolve(bundleParent
).resolve(category
)
275 : a2Output
.resolve(category
);
276 Path jarP
= a2JarDirectory
.resolve(compiled
.getFileName() + "." + major
+ "." + minor
+ ".jar");
277 Files
.createDirectories(jarP
.getParent());
279 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarP
), manifest
)) {
280 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
281 // add all classes first
282 Files
.walkFileTree(binP
, new SimpleFileVisitor
<Path
>() {
284 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
285 jarOut
.putNextEntry(new JarEntry(binP
.relativize(file
).toString()));
286 Files
.copy(file
, jarOut
);
287 return FileVisitResult
.CONTINUE
;
292 Files
.walkFileTree(source
, new SimpleFileVisitor
<Path
>() {
294 public FileVisitResult
preVisitDirectory(Path dir
, BasicFileAttributes attrs
) throws IOException
{
295 Path relativeP
= source
.relativize(dir
);
296 for (PathMatcher exclude
: excludes
)
297 if (exclude
.matches(relativeP
))
298 return FileVisitResult
.SKIP_SUBTREE
;
300 return FileVisitResult
.CONTINUE
;
304 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
305 Path relativeP
= source
.relativize(file
);
306 for (PathMatcher exclude
: excludes
)
307 if (exclude
.matches(relativeP
))
308 return FileVisitResult
.CONTINUE
;
309 JarEntry entry
= new JarEntry(relativeP
.toString());
310 jarOut
.putNextEntry(entry
);
311 Files
.copy(file
, jarOut
);
312 return FileVisitResult
.CONTINUE
;
316 Path srcP
= source
.resolve("src");
317 // Add all resources from src/
318 Files
.walkFileTree(srcP
, new SimpleFileVisitor
<Path
>() {
320 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
321 if (file
.getFileName().toString().endsWith(".java")
322 || file
.getFileName().toString().endsWith(".class"))
323 return FileVisitResult
.CONTINUE
;
324 jarOut
.putNextEntry(new JarEntry(srcP
.relativize(file
).toString()));
325 if (!Files
.isDirectory(file
))
326 Files
.copy(file
, jarOut
);
327 return FileVisitResult
.CONTINUE
;
332 // TODO add effective BND, Eclipse project file, etc., in order to be able to
334 Files
.walkFileTree(srcP
, new SimpleFileVisitor
<Path
>() {
336 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
337 jarOut
.putNextEntry(new JarEntry("OSGI-OPT/src/" + srcP
.relativize(file
).toString()));
338 if (!Files
.isDirectory(file
))
339 Files
.copy(file
, jarOut
);
340 return FileVisitResult
.CONTINUE
;
348 * Recursively find the base source directory (which contains the
349 * <code>{@value #SDK_MK}</code> file).
351 Path
findSdkMk(Path directory
) {
352 Path sdkMkP
= directory
.resolve(SDK_MK
);
353 if (Files
.exists(sdkMkP
)) {
354 return sdkMkP
.toAbsolutePath();
356 if (directory
.getParent() == null)
358 return findSdkMk(directory
.getParent());
362 * Reads Makefile variable assignments of the form =, :=, or ?=, ignoring white
363 * spaces. To be used with very simple included Makefiles only.
365 Map
<String
, String
> readeMakefileVariables(Path path
) throws IOException
{
366 Map
<String
, String
> context
= new HashMap
<>();
367 List
<String
> sdkMkLines
= Files
.readAllLines(path
);
368 lines
: for (String line
: sdkMkLines
) {
369 StringTokenizer st
= new StringTokenizer(line
, " :=?");
370 if (!st
.hasMoreTokens())
372 String key
= st
.nextToken();
373 if (!st
.hasMoreTokens())
375 String value
= st
.nextToken();
376 if (st
.hasMoreTokens()) // probably not a simple variable assignment
378 context
.put(key
, value
);
383 /** Main entry point, interpreting actions and arguments. */
384 public static void main(String
... args
) {
385 if (args
.length
== 0)
386 throw new IllegalArgumentException("At least an action must be provided");
388 String action
= args
[actionIndex
];
389 if (args
.length
> actionIndex
+ 1 && !args
[actionIndex
+ 1].startsWith("-"))
390 throw new IllegalArgumentException(
391 "Action " + action
+ " must be followed by an option: " + Arrays
.asList(args
));
393 Map
<String
, List
<String
>> options
= new HashMap
<>();
394 String currentOption
= null;
395 for (int i
= actionIndex
+ 1; i
< args
.length
; i
++) {
396 if (args
[i
].startsWith("-")) {
397 currentOption
= args
[i
];
398 if (!options
.containsKey(currentOption
))
399 options
.put(currentOption
, new ArrayList
<>());
402 options
.get(currentOption
).add(args
[i
]);
407 Make argeoMake
= new Make();
409 case "compile" -> argeoMake
.compile(options
);
410 case "bundle" -> argeoMake
.bundle(options
);
411 case "all" -> argeoMake
.all(options
);
413 default -> throw new IllegalArgumentException("Unkown action: " + action
);
416 long jvmUptime
= ManagementFactory
.getRuntimeMXBean().getUptime();
417 logger
.log(INFO
, "Make.java action '" + action
+ "' succesfully completed after " + (jvmUptime
/ 1000) + "."
418 + (jvmUptime
% 1000) + " s");
419 } catch (Exception e
) {
420 long jvmUptime
= ManagementFactory
.getRuntimeMXBean().getUptime();
421 logger
.log(ERROR
, "Make.java action '" + action
+ "' failed after " + (jvmUptime
/ 1000) + "."
422 + (jvmUptime
% 1000) + " s", e
);
428 * An ECJ {@link CompilationProgress} printing a progress bar while compiling.
430 static class MakeCompilationProgress
extends CompilationProgress
{
431 private int totalWork
;
432 private long currentChunk
= 0;
433 private long chunksCount
= 80;
436 public void worked(int workIncrement
, int remainingWork
) {
437 if (!logger
.isLoggable(Level
.INFO
)) // progress bar only at INFO level
439 long chunk
= ((totalWork
- remainingWork
) * chunksCount
) / totalWork
;
440 if (chunk
!= currentChunk
) {
441 currentChunk
= chunk
;
442 for (long i
= 0; i
< currentChunk
; i
++) {
443 System
.out
.print("#");
445 for (long i
= currentChunk
; i
< chunksCount
; i
++) {
446 System
.out
.print("-");
448 System
.out
.print("\r");
450 if (remainingWork
== 0)
451 System
.out
.print("\n");
455 public void setTaskName(String name
) {
459 public boolean isCanceled() {
468 public void begin(int remainingWork
) {
469 this.totalWork
= remainingWork
;