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
;
35 import org
.eclipse
.jdt
.core
.compiler
.CompilationProgress
;
37 import aQute
.bnd
.osgi
.Analyzer
;
38 import aQute
.bnd
.osgi
.Jar
;
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/>
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>
50 private final static Logger logger
= System
.getLogger(Make
.class.getName());
52 /** Name of the local-specific Makefile (sdk.mk). */
53 final static String SDK_MK
= "sdk.mk";
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
;
60 * The base of the builder, typically a submodule pointing to the public
61 * argeo-build directory.
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. */
68 /** The base of the a2 output for all layers. */
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
);
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())
83 String key
= st
.nextToken();
84 if (!st
.hasMoreTokens())
86 String value
= st
.nextToken();
87 context
.put(key
, value
);
90 sdkSrcBase
= Paths
.get(context
.computeIfAbsent("SDK_SRC_BASE", (key
) -> {
91 throw new IllegalStateException(key
+ " not found");
93 argeoBuildBase
= sdkSrcBase
.resolve("sdk/argeo-build");
95 sdkBuildBase
= Paths
.get(context
.computeIfAbsent("SDK_BUILD_BASE", (key
) -> {
96 throw new IllegalStateException(key
+ " not found");
98 buildBase
= sdkBuildBase
.resolve(sdkSrcBase
.getFileName());
99 a2Output
= sdkBuildBase
.resolve("a2");
105 /** Compile and create the bundles in one go. */
106 void all(Map
<String
, List
<String
>> options
) throws IOException
{
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())
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());
125 List
<String
> compilerArgs
= new ArrayList
<>();
127 Path ecjArgs
= argeoBuildBase
.resolve("ecj.args");
128 compilerArgs
.add("@" + ecjArgs
);
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());
145 compilerArgs
.add(classPath
.toString());
149 for (String bundle
: bundles
) {
150 StringBuilder sb
= new StringBuilder();
151 sb
.append(execDirectory
.resolve(bundle
).resolve("src"));
153 compilerArgs
.add(sb
.toString());
154 sb
= new StringBuilder();
155 sb
.append(buildBase
.resolve(bundle
).resolve("bin"));
157 compilerArgs
.add(sb
.toString());
160 if (logger
.isLoggable(INFO
))
161 compilerArgs
.add("-time");
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");
170 /** Package the bundles. */
171 void bundle(Map
<String
, List
<String
>> options
) {
173 List
<String
> bundles
= options
.get("--bundles");
174 Objects
.requireNonNull(bundles
, "--bundles argument must be set");
175 if (bundles
.isEmpty())
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);
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);
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(() -> {
195 createBundle(branch
, bundle
, category
);
196 } catch (IOException e
) {
197 throw new RuntimeException("Packaging of " + bundle
+ " failed", e
);
201 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
202 long duration
= System
.currentTimeMillis() - begin
;
203 logger
.log(INFO
, "Packaging took " + duration
+ " ms");
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();
216 Properties properties
= new Properties();
217 Path argeoBnd
= argeoBuildBase
.resolve("argeo.bnd");
218 try (InputStream in
= Files
.newInputStream(argeoBnd
)) {
222 Path branchBnd
= sdkSrcBase
.resolve("sdk/branches/" + branch
+ ".bnd");
223 try (InputStream in
= Files
.newInputStream(branchBnd
)) {
227 Path bndBnd
= source
.resolve("bnd.bnd");
228 try (InputStream in
= Files
.newInputStream(bndBnd
)) {
233 properties
.put("Bundle-SymbolicName", bundleSymbolicName
);
235 // Calculate MANIFEST
236 Path binP
= compiled
.resolve("bin");
237 if (!Files
.exists(binP
))
238 Files
.createDirectories(binP
);
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
);
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");
255 Path manifestP
= compiled
.resolve("META-INF/MANIFEST.MF");
256 Files
.createDirectories(manifestP
.getParent());
257 try (OutputStream out
= Files
.newOutputStream(manifestP
)) {
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
);
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());
275 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarP
), manifest
)) {
276 // add all classes first
277 Files
.walkFileTree(binP
, new SimpleFileVisitor
<Path
>() {
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
;
287 Files
.walkFileTree(source
, new SimpleFileVisitor
<Path
>() {
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
;
295 return FileVisitResult
.CONTINUE
;
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
;
312 // TODO add effective BND, Eclipse project file, etc., in order to be able to
314 Path srcP
= source
.resolve("src");
315 Files
.walkFileTree(srcP
, new SimpleFileVisitor
<Path
>() {
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
;
327 * Recursively find the base source directory (which contains the
328 * <code>{@value #SDK_MK}</code> file).
330 private Path
findSdkMk(Path directory
) {
331 Path sdkMkP
= directory
.resolve(SDK_MK
);
332 if (Files
.exists(sdkMkP
)) {
333 return sdkMkP
.toAbsolutePath();
335 if (directory
.getParent() == null)
337 return findSdkMk(directory
.getParent());
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");
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
));
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
<>());
359 options
.get(currentOption
).add(args
[i
]);
364 Make argeoMake
= new Make();
366 case "compile" -> argeoMake
.compile(options
);
367 case "bundle" -> argeoMake
.bundle(options
);
368 case "all" -> argeoMake
.all(options
);
370 default -> throw new IllegalArgumentException("Unkown action: " + action
);
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
);
385 * An ECJ {@link CompilationProgress} printing a progress bar while compiling.
387 static class MakeCompilationProgress
extends CompilationProgress
{
388 private int totalWork
;
389 private long currentChunk
= 0;
390 private long chunksCount
= 80;
393 public void worked(int workIncrement
, int remainingWork
) {
394 if (!logger
.isLoggable(Level
.INFO
)) // progress bar only at INFO level
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("#");
402 for (long i
= currentChunk
; i
< chunksCount
; i
++) {
403 System
.out
.print("-");
405 System
.out
.print("\r");
407 if (remainingWork
== 0)
408 System
.out
.print("\n");
412 public void setTaskName(String name
) {
416 public boolean isCanceled() {
425 public void begin(int remainingWork
) {
426 this.totalWork
= remainingWork
;