1 package org
.argeo
.build
;
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
;
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
;
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
.zip
.Deflater
;
43 import org
.eclipse
.jdt
.core
.compiler
.CompilationProgress
;
45 import aQute
.bnd
.osgi
.Analyzer
;
46 import aQute
.bnd
.osgi
.Jar
;
49 * Minimalistic OSGi compiler and packager, meant to be used as a single file
50 * without being itself compiled first. It depends on the Eclipse batch compiler
51 * (aka. ECJ) and the BND Libs library for OSGi metadata generation (which
52 * itselfs depends on slf4j).<br/>
54 * For example, a typical system call would be:<br/>
55 * <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>
58 private final static Logger logger
= System
.getLogger(Make
.class.getName());
61 * Environment variable on whether sources should be packaged separately or
62 * integrated in the bundles.
64 private final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
67 * Environment variable on whether legal files at the root of the sources should
68 * be included in the generated bundles. Should be set to true when building
69 * third-party software in order no to include the build harness license into
70 * the generated bundles.
72 private final static String ENV_NO_SDK_LEGAL
= "NO_SDK_LEGAL";
75 * Environment variable to override the default location for the Argeo Build
76 * configuration files. Typically used if Argeo Build has been compiled and
77 * packaged separately.
79 private final static String ENV_ARGEO_BUILD_CONFIG
= "ARGEO_BUILD_CONFIG";
81 /** Make file variable (in {@link #SDK_MK}) with a path to the sources base. */
82 private final static String VAR_SDK_SRC_BASE
= "SDK_SRC_BASE";
85 * Make file variable (in {@link #SDK_MK}) with a path to the build output base.
87 private final static String VAR_SDK_BUILD_BASE
= "SDK_BUILD_BASE";
89 * Make file variable (in {@link #BRANCH_MK}) with the branch.
91 private final static String VAR_BRANCH
= "BRANCH";
93 /** Name of the local-specific Makefile (sdk.mk). */
94 final static String SDK_MK
= "sdk.mk";
95 /** Name of the branch definition Makefile (branch.mk). */
96 final static String BRANCH_MK
= "branch.mk";
98 /** The execution directory (${user.dir}). */
99 final Path execDirectory
;
100 /** Base of the source code, typically the cloned git repository. */
101 final Path sdkSrcBase
;
103 * The base of the builder, typically a submodule pointing to the INCLUDEpublic
104 * argeo-build directory.
106 final Path argeoBuildBase
;
107 /** The base of the build for all layers. */
108 final Path sdkBuildBase
;
109 /** The base of the build for this layer. */
110 final Path buildBase
;
111 /** The base of the a2 output for all layers. */
113 /** The base of the a2 sources when packaged separately. */
114 final Path a2srcOutput
;
116 /** Whether sources should be packaged separately. */
117 final boolean sourceBundles
;
118 /** Whether common legal files should be included. */
119 final boolean noSdkLegal
;
121 /** Constructor initialises the base directories. */
122 public Make() throws IOException
{
123 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
125 logger
.log(Level
.INFO
, "Sources will be packaged separately");
126 noSdkLegal
= Boolean
.parseBoolean(System
.getenv(ENV_NO_SDK_LEGAL
));
128 logger
.log(Level
.INFO
, "SDK legal files will NOT be included");
130 execDirectory
= Paths
.get(System
.getProperty("user.dir"));
131 Path sdkMkP
= findSdkMk(execDirectory
);
132 Objects
.requireNonNull(sdkMkP
, "No " + SDK_MK
+ " found under " + execDirectory
);
134 Map
<String
, String
> context
= readMakefileVariables(sdkMkP
);
135 sdkSrcBase
= Paths
.get(context
.computeIfAbsent(VAR_SDK_SRC_BASE
, (key
) -> {
136 throw new IllegalStateException(key
+ " not found");
137 })).toAbsolutePath();
139 Path argeoBuildBaseT
= sdkSrcBase
.resolve("sdk/argeo-build");
140 if (!Files
.exists(argeoBuildBaseT
)) {
141 String fromEnv
= System
.getenv(ENV_ARGEO_BUILD_CONFIG
);
143 argeoBuildBaseT
= Paths
.get(fromEnv
);
144 if (fromEnv
== null || !Files
.exists(argeoBuildBaseT
)) {
145 throw new IllegalStateException(
146 "Argeo Build not found. Did you initialise the git submodules or set the "
147 + ENV_ARGEO_BUILD_CONFIG
+ " environment variable?");
150 argeoBuildBase
= argeoBuildBaseT
;
152 sdkBuildBase
= Paths
.get(context
.computeIfAbsent(VAR_SDK_BUILD_BASE
, (key
) -> {
153 throw new IllegalStateException(key
+ " not found");
154 })).toAbsolutePath();
155 buildBase
= sdkBuildBase
.resolve(sdkSrcBase
.getFileName());
156 a2Output
= sdkBuildBase
.resolve("a2");
157 a2srcOutput
= sdkBuildBase
.resolve("a2.src");
163 /** Compile and create the bundles in one go. */
164 void all(Map
<String
, List
<String
>> options
) throws IOException
{
169 /** Compile all the bundles which have been passed via the --bundle argument. */
170 void compile(Map
<String
, List
<String
>> options
) throws IOException
{
171 List
<String
> bundles
= options
.get("--bundles");
172 Objects
.requireNonNull(bundles
, "--bundles argument must be set");
173 if (bundles
.isEmpty())
176 List
<String
> a2Categories
= options
.getOrDefault("--dep-categories", new ArrayList
<>());
177 List
<String
> a2Bases
= options
.getOrDefault("--a2-bases", new ArrayList
<>());
178 if (a2Bases
.isEmpty() || !a2Bases
.contains(a2Output
.toString())) {
179 a2Bases
.add(a2Output
.toString());
182 List
<String
> compilerArgs
= new ArrayList
<>();
184 Path ecjArgs
= argeoBuildBase
.resolve("ecj.args");
185 compilerArgs
.add("@" + ecjArgs
);
188 if (!a2Categories
.isEmpty()) {
189 // We will keep only the highest major.minor
190 // and order by bundle name, for predictability
191 Map
<String
, A2Jar
> a2Jars
= new TreeMap
<>();
193 // StringJoiner modulePath = new StringJoiner(File.pathSeparator);
194 for (String a2Base
: a2Bases
) {
195 categories
: for (String a2Category
: a2Categories
) {
196 Path a2Dir
= Paths
.get(a2Base
).resolve(a2Category
);
197 if (!Files
.exists(a2Dir
))
199 // modulePath.add(a2Dir.toString());
200 for (Path jarP
: Files
.newDirectoryStream(a2Dir
, (p
) -> p
.getFileName().toString().endsWith(".jar")
201 && !p
.getFileName().toString().endsWith(".src.jar"))) {
202 A2Jar a2Jar
= new A2Jar(jarP
);
203 if (a2Jars
.containsKey(a2Jar
.name
)) {
204 A2Jar current
= a2Jars
.get(a2Jar
.name
);
205 if (a2Jar
.major
> current
.major
)
206 a2Jars
.put(a2Jar
.name
, a2Jar
);
207 else if (a2Jar
.major
== current
.major
//
208 // if minor equals, we take the last one
209 && a2Jar
.minor
>= current
.minor
)
210 a2Jars
.put(a2Jar
.name
, a2Jar
);
212 a2Jars
.put(a2Jar
.name
, a2Jar
);
218 StringJoiner classPath
= new StringJoiner(File
.pathSeparator
);
219 for (Iterator
<A2Jar
> it
= a2Jars
.values().iterator(); it
.hasNext();)
220 classPath
.add(it
.next().path
.toString());
222 compilerArgs
.add("-cp");
223 compilerArgs
.add(classPath
.toString());
224 // compilerArgs.add("--module-path");
225 // compilerArgs.add(modulePath.toString());
229 for (String bundle
: bundles
) {
230 StringBuilder sb
= new StringBuilder();
231 Path bundlePath
= execDirectory
.resolve(bundle
);
232 if (!Files
.exists(bundlePath
)) {
233 if (bundles
.size() == 1) {
234 logger
.log(WARNING
, "Bundle " + bundle
+ " not found in " + execDirectory
235 + ", assuming this is this directory, as only one bundle was requested.");
236 bundlePath
= execDirectory
;
238 throw new IllegalArgumentException("Bundle " + bundle
+ " not found in " + execDirectory
);
240 sb
.append(bundlePath
.resolve("src"));
242 compilerArgs
.add(sb
.toString());
243 sb
= new StringBuilder();
244 sb
.append(buildBase
.resolve(bundle
).resolve("bin"));
246 compilerArgs
.add(sb
.toString());
249 if (logger
.isLoggable(INFO
))
250 compilerArgs
.add("-time");
252 if (logger
.isLoggable(DEBUG
)) {
253 logger
.log(DEBUG
, "Compiler arguments:");
254 for (String arg
: compilerArgs
)
255 logger
.log(DEBUG
, arg
);
258 boolean success
= org
.eclipse
.jdt
.core
.compiler
.batch
.BatchCompiler
.compile(
259 compilerArgs
.toArray(new String
[compilerArgs
.size()]), new PrintWriter(System
.out
),
260 new PrintWriter(System
.err
), new MakeCompilationProgress());
261 if (!success
) // kill the process if compilation failed
262 throw new IllegalStateException("Compilation failed");
265 /** Package the bundles. */
266 void bundle(Map
<String
, List
<String
>> options
) throws IOException
{
268 List
<String
> bundles
= options
.get("--bundles");
269 Objects
.requireNonNull(bundles
, "--bundles argument must be set");
270 if (bundles
.isEmpty())
273 List
<String
> categories
= options
.get("--category");
274 Objects
.requireNonNull(categories
, "--category argument must be set");
275 if (categories
.size() != 1)
276 throw new IllegalArgumentException("One and only one --category must be specified");
277 String category
= categories
.get(0);
280 Path branchMk
= sdkSrcBase
.resolve(BRANCH_MK
);
281 if (Files
.exists(branchMk
)) {
282 Map
<String
, String
> branchVariables
= readMakefileVariables(branchMk
);
283 branch
= branchVariables
.get(VAR_BRANCH
);
288 long begin
= System
.currentTimeMillis();
289 // create jars in parallel
290 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
291 for (String bundle
: bundles
) {
292 toDos
.add(CompletableFuture
.runAsync(() -> {
294 createBundle(branch
, bundle
, category
);
295 } catch (IOException e
) {
296 throw new RuntimeException("Packaging of " + bundle
+ " failed", e
);
300 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
301 long duration
= System
.currentTimeMillis() - begin
;
302 logger
.log(INFO
, "Packaging took " + duration
+ " ms");
305 /** Install the bundles. */
306 void install(Map
<String
, List
<String
>> options
, boolean uninstall
) throws IOException
{
308 List
<String
> bundles
= options
.get("--bundles");
309 Objects
.requireNonNull(bundles
, "--bundles argument must be set");
310 if (bundles
.isEmpty())
313 List
<String
> categories
= options
.get("--category");
314 Objects
.requireNonNull(categories
, "--category argument must be set");
315 if (categories
.size() != 1)
316 throw new IllegalArgumentException("One and only one --category must be specified");
317 String category
= categories
.get(0);
319 List
<String
> targetDirs
= options
.get("--target");
320 Objects
.requireNonNull(targetDirs
, "--target argument must be set");
321 if (targetDirs
.size() != 1)
322 throw new IllegalArgumentException("One and only one --target must be specified");
323 Path targetA2
= Paths
.get(targetDirs
.get(0));
324 logger
.log(INFO
, (uninstall ?
"Uninstalling from " : "Installing to ") + targetA2
);
327 Path branchMk
= sdkSrcBase
.resolve(BRANCH_MK
);
328 if (Files
.exists(branchMk
)) {
329 Map
<String
, String
> branchVariables
= readMakefileVariables(branchMk
);
330 branch
= branchVariables
.get(VAR_BRANCH
);
332 throw new IllegalArgumentException(VAR_BRANCH
+ " variable must be set.");
335 Properties properties
= new Properties();
336 Path branchBnd
= sdkSrcBase
.resolve("sdk/branches/" + branch
+ ".bnd");
337 if (Files
.exists(branchBnd
))
338 try (InputStream in
= Files
.newInputStream(branchBnd
)) {
341 String major
= properties
.getProperty("major");
342 Objects
.requireNonNull(major
, "'major' must be set");
343 String minor
= properties
.getProperty("minor");
344 Objects
.requireNonNull(minor
, "'minor' must be set");
347 for (String bundle
: bundles
) {
348 Path bundlePath
= Paths
.get(bundle
);
349 Path bundleParent
= bundlePath
.getParent();
350 Path a2JarDirectory
= bundleParent
!= null ? a2Output
.resolve(bundleParent
).resolve(category
)
351 : a2Output
.resolve(category
);
352 Path jarP
= a2JarDirectory
.resolve(bundlePath
.getFileName() + "." + major
+ "." + minor
+ ".jar");
354 Path targetJarP
= targetA2
.resolve(a2Output
.relativize(jarP
));
355 if (uninstall
) { // uninstall
356 if (Files
.exists(targetJarP
)) {
357 Files
.delete(targetJarP
);
358 logger
.log(DEBUG
, "Removed " + targetJarP
);
361 Path targetParent
= targetJarP
.getParent();
362 deleteEmptyParents(targetA2
, targetParent
);
364 Files
.createDirectories(targetJarP
.getParent());
365 boolean update
= Files
.exists(targetJarP
);
366 Files
.copy(jarP
, targetJarP
, StandardCopyOption
.REPLACE_EXISTING
);
367 logger
.log(DEBUG
, (update ?
"Updated " : "Installed ") + targetJarP
);
371 logger
.log(INFO
, uninstall ? count
+ " bundles removed" : count
+ " bundles installed or updated");
374 /** Delete empty parent directory up to the A2 target (included). */
375 void deleteEmptyParents(Path targetA2
, Path targetParent
) throws IOException
{
376 if (!Files
.isDirectory(targetParent
))
377 throw new IllegalArgumentException(targetParent
+ " must be a directory");
378 boolean isA2target
= Files
.isSameFile(targetA2
, targetParent
);
379 if (!Files
.list(targetParent
).iterator().hasNext()) {
380 Files
.delete(targetParent
);
382 return;// stop after deleting A2 base
383 deleteEmptyParents(targetA2
, targetParent
.getParent());
387 /** Package a single bundle. */
388 void createBundle(String branch
, String bundle
, String category
) throws IOException
{
390 if (!Files
.exists(execDirectory
.resolve(bundle
))) {
392 "Bundle " + bundle
+ " not found in " + execDirectory
+ ", assuming this is this directory.");
393 source
= execDirectory
;
395 source
= execDirectory
.resolve(bundle
);
397 Path srcP
= source
.resolve("src");
399 Path compiled
= buildBase
.resolve(bundle
);
400 String bundleSymbolicName
= source
.getFileName().toString();
403 Properties properties
= new Properties();
404 Path argeoBnd
= argeoBuildBase
.resolve("argeo.bnd");
405 try (InputStream in
= Files
.newInputStream(argeoBnd
)) {
409 if (branch
!= null) {
410 Path branchBnd
= sdkSrcBase
.resolve("sdk/branches/" + branch
+ ".bnd");
411 if (Files
.exists(branchBnd
))
412 try (InputStream in
= Files
.newInputStream(branchBnd
)) {
417 Path bndBnd
= source
.resolve("bnd.bnd");
418 if (Files
.exists(bndBnd
))
419 try (InputStream in
= Files
.newInputStream(bndBnd
)) {
424 if (!properties
.containsKey("Bundle-SymbolicName"))
425 properties
.put("Bundle-SymbolicName", bundleSymbolicName
);
427 // Calculate MANIFEST
428 Path binP
= compiled
.resolve("bin");
429 if (!Files
.exists(binP
))
430 Files
.createDirectories(binP
);
432 try (Analyzer bndAnalyzer
= new Analyzer()) {
433 bndAnalyzer
.setProperties(properties
);
434 Jar jar
= new Jar(bundleSymbolicName
, binP
.toFile());
435 bndAnalyzer
.setJar(jar
);
436 manifest
= bndAnalyzer
.calcManifest();
437 } catch (Exception e
) {
438 throw new RuntimeException("Bnd analysis of " + compiled
+ " failed", e
);
441 String major
= properties
.getProperty("major");
442 Objects
.requireNonNull(major
, "'major' must be set");
443 String minor
= properties
.getProperty("minor");
444 Objects
.requireNonNull(minor
, "'minor' must be set");
447 Path manifestP
= compiled
.resolve("META-INF/MANIFEST.MF");
448 Files
.createDirectories(manifestP
.getParent());
449 try (OutputStream out
= Files
.newOutputStream(manifestP
)) {
454 List
<PathMatcher
> excludes
= new ArrayList
<>();
455 Path excludesP
= argeoBuildBase
.resolve("excludes.txt");
456 for (String line
: Files
.readAllLines(excludesP
)) {
457 PathMatcher pathMatcher
= excludesP
.getFileSystem().getPathMatcher("glob:" + line
);
458 excludes
.add(pathMatcher
);
461 Path bundleParent
= Paths
.get(bundle
).getParent();
462 Path a2JarDirectory
= bundleParent
!= null ? a2Output
.resolve(bundleParent
).resolve(category
)
463 : a2Output
.resolve(category
);
464 Path jarP
= a2JarDirectory
.resolve(compiled
.getFileName() + "." + major
+ "." + minor
+ ".jar");
465 Files
.createDirectories(jarP
.getParent());
467 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarP
), manifest
)) {
468 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
469 // add all classes first
470 Files
.walkFileTree(binP
, new SimpleFileVisitor
<Path
>() {
472 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
473 jarOut
.putNextEntry(new JarEntry(binP
.relativize(file
).toString()));
474 Files
.copy(file
, jarOut
);
475 return FileVisitResult
.CONTINUE
;
480 Files
.walkFileTree(source
, new SimpleFileVisitor
<Path
>() {
482 public FileVisitResult
preVisitDirectory(Path dir
, BasicFileAttributes attrs
) throws IOException
{
483 // skip output directory if it happens to be within the sources
484 if (Files
.isSameFile(sdkBuildBase
, dir
))
485 return FileVisitResult
.SKIP_SUBTREE
;
487 // skip excluded patterns
488 Path relativeP
= source
.relativize(dir
);
489 for (PathMatcher exclude
: excludes
)
490 if (exclude
.matches(relativeP
))
491 return FileVisitResult
.SKIP_SUBTREE
;
493 return FileVisitResult
.CONTINUE
;
497 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
498 Path relativeP
= source
.relativize(file
);
499 for (PathMatcher exclude
: excludes
)
500 if (exclude
.matches(relativeP
))
501 return FileVisitResult
.CONTINUE
;
502 JarEntry entry
= new JarEntry(relativeP
.toString());
503 jarOut
.putNextEntry(entry
);
504 Files
.copy(file
, jarOut
);
505 return FileVisitResult
.CONTINUE
;
509 // Add all resources from src/
510 Files
.walkFileTree(srcP
, new SimpleFileVisitor
<Path
>() {
512 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
513 if (file
.getFileName().toString().endsWith(".java")
514 || file
.getFileName().toString().endsWith(".class"))
515 return FileVisitResult
.CONTINUE
;
516 jarOut
.putNextEntry(new JarEntry(srcP
.relativize(file
).toString()));
517 if (!Files
.isDirectory(file
))
518 Files
.copy(file
, jarOut
);
519 return FileVisitResult
.CONTINUE
;
523 // add legal notices and licenses
524 for (Path p
: listLegalFilesToInclude(source
).values()) {
525 jarOut
.putNextEntry(new JarEntry(p
.getFileName().toString()));
526 Files
.copy(p
, jarOut
);
530 // TODO add effective BND, Eclipse project file, etc., in order to be able to
532 if (!sourceBundles
) {
533 copySourcesToJar(srcP
, jarOut
, "OSGI-OPT/src/");
537 if (sourceBundles
) {// create separate sources jar
538 Path a2srcJarDirectory
= bundleParent
!= null ? a2srcOutput
.resolve(bundleParent
).resolve(category
)
539 : a2srcOutput
.resolve(category
);
540 Files
.createDirectories(a2srcJarDirectory
);
541 Path srcJarP
= a2srcJarDirectory
.resolve(compiled
.getFileName() + "." + major
+ "." + minor
+ ".src.jar");
542 Manifest srcManifest
= new Manifest();
543 srcManifest
.getMainAttributes().put(Attributes
.Name
.MANIFEST_VERSION
, "1.0");
544 srcManifest
.getMainAttributes().putValue("Bundle-SymbolicName", bundleSymbolicName
+ ".src");
545 srcManifest
.getMainAttributes().putValue("Bundle-Version",
546 manifest
.getMainAttributes().getValue("Bundle-Version").toString());
547 srcManifest
.getMainAttributes().putValue("Eclipse-SourceBundle",
548 bundleSymbolicName
+ ";version=\"" + manifest
.getMainAttributes().getValue("Bundle-Version"));
550 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
551 copySourcesToJar(srcP
, srcJarOut
, "");
552 // add legal notices and licenses
553 for (Path p
: listLegalFilesToInclude(source
).values()) {
554 srcJarOut
.putNextEntry(new JarEntry(p
.getFileName().toString()));
555 Files
.copy(p
, srcJarOut
);
561 /** List the relevant legal files to include, from the SDK source base. */
562 Map
<String
, Path
> listLegalFilesToInclude(Path bundleBase
) throws IOException
{
563 Map
<String
, Path
> toInclude
= new HashMap
<>();
565 DirectoryStream
<Path
> sdkSrcLegal
= Files
.newDirectoryStream(sdkSrcBase
, (p
) -> {
566 String fileName
= p
.getFileName().toString();
567 return switch (fileName
) {
571 case "COPYING.LESSER":
577 for (Path p
: sdkSrcLegal
)
578 toInclude
.put(p
.getFileName().toString(), p
);
580 for (Iterator
<Map
.Entry
<String
, Path
>> entries
= toInclude
.entrySet().iterator(); entries
.hasNext();) {
581 Map
.Entry
<String
, Path
> entry
= entries
.next();
582 Path inBundle
= bundleBase
.resolve(entry
.getValue().getFileName());
583 // remove file if it is also defined at bundle level
584 // since it has already been copied
586 if (Files
.exists(inBundle
))
595 /** Add sources to a jar file */
596 void copySourcesToJar(Path srcP
, JarOutputStream srcJarOut
, String prefix
) throws IOException
{
597 Files
.walkFileTree(srcP
, new SimpleFileVisitor
<Path
>() {
599 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
600 srcJarOut
.putNextEntry(new JarEntry(prefix
+ srcP
.relativize(file
).toString()));
601 if (!Files
.isDirectory(file
))
602 Files
.copy(file
, srcJarOut
);
603 return FileVisitResult
.CONTINUE
;
609 * Recursively find the base source directory (which contains the
610 * <code>{@value #SDK_MK}</code> file).
612 Path
findSdkMk(Path directory
) {
613 Path sdkMkP
= directory
.resolve(SDK_MK
);
614 if (Files
.exists(sdkMkP
)) {
615 return sdkMkP
.toAbsolutePath();
617 if (directory
.getParent() == null)
619 return findSdkMk(directory
.getParent());
623 * Reads Makefile variable assignments of the form =, :=, or ?=, ignoring white
624 * spaces. To be used with very simple included Makefiles only.
626 Map
<String
, String
> readMakefileVariables(Path path
) throws IOException
{
627 Map
<String
, String
> context
= new HashMap
<>();
628 List
<String
> sdkMkLines
= Files
.readAllLines(path
);
629 lines
: for (String line
: sdkMkLines
) {
630 StringTokenizer st
= new StringTokenizer(line
, " :=?");
631 if (!st
.hasMoreTokens())
633 String key
= st
.nextToken();
634 if (!st
.hasMoreTokens())
636 String value
= st
.nextToken();
637 if (st
.hasMoreTokens()) // probably not a simple variable assignment
639 context
.put(key
, value
);
644 /** Main entry point, interpreting actions and arguments. */
645 public static void main(String
... args
) {
646 if (args
.length
== 0)
647 throw new IllegalArgumentException("At least an action must be provided");
649 String action
= args
[actionIndex
];
650 if (args
.length
> actionIndex
+ 1 && !args
[actionIndex
+ 1].startsWith("-"))
651 throw new IllegalArgumentException(
652 "Action " + action
+ " must be followed by an option: " + Arrays
.asList(args
));
654 Map
<String
, List
<String
>> options
= new HashMap
<>();
655 String currentOption
= null;
656 for (int i
= actionIndex
+ 1; i
< args
.length
; i
++) {
657 if (args
[i
].startsWith("-")) {
658 currentOption
= args
[i
];
659 if (!options
.containsKey(currentOption
))
660 options
.put(currentOption
, new ArrayList
<>());
663 options
.get(currentOption
).add(args
[i
]);
668 Make argeoMake
= new Make();
670 case "compile" -> argeoMake
.compile(options
);
671 case "bundle" -> argeoMake
.bundle(options
);
672 case "all" -> argeoMake
.all(options
);
673 case "install" -> argeoMake
.install(options
, false);
674 case "uninstall" -> argeoMake
.install(options
, true);
676 default -> throw new IllegalArgumentException("Unkown action: " + action
);
679 long jvmUptime
= ManagementFactory
.getRuntimeMXBean().getUptime();
680 logger
.log(INFO
, "Make.java action '" + action
+ "' succesfully completed after " + (jvmUptime
/ 1000) + "."
681 + (jvmUptime
% 1000) + " s");
682 } catch (Exception e
) {
683 long jvmUptime
= ManagementFactory
.getRuntimeMXBean().getUptime();
684 logger
.log(ERROR
, "Make.java action '" + action
+ "' failed after " + (jvmUptime
/ 1000) + "."
685 + (jvmUptime
% 1000) + " s", e
);
690 /** A jar file in A2 format */
700 String fileName
= path
.getFileName().toString();
701 fileName
= fileName
.substring(0, fileName
.lastIndexOf('.'));
702 minor
= Integer
.parseInt(fileName
.substring(fileName
.lastIndexOf('.') + 1));
703 fileName
= fileName
.substring(0, fileName
.lastIndexOf('.'));
704 major
= Integer
.parseInt(fileName
.substring(fileName
.lastIndexOf('.') + 1));
705 name
= fileName
.substring(0, fileName
.lastIndexOf('.'));
706 } catch (Exception e
) {
707 throw new IllegalArgumentException("Badly formatted A2 jar " + path
, e
);
713 * An ECJ {@link CompilationProgress} printing a progress bar while compiling.
715 static class MakeCompilationProgress
extends CompilationProgress
{
716 private int totalWork
;
717 private long currentChunk
= 0;
718 private long chunksCount
= 80;
721 public void worked(int workIncrement
, int remainingWork
) {
722 if (!logger
.isLoggable(Level
.INFO
)) // progress bar only at INFO level
724 long chunk
= ((totalWork
- remainingWork
) * chunksCount
) / totalWork
;
725 if (chunk
!= currentChunk
) {
726 currentChunk
= chunk
;
727 for (long i
= 0; i
< currentChunk
; i
++) {
728 System
.out
.print("#");
730 for (long i
= currentChunk
; i
< chunksCount
; i
++) {
731 System
.out
.print("-");
733 System
.out
.print("\r");
735 if (remainingWork
== 0)
736 System
.out
.print("\n");
740 public void setTaskName(String name
) {
744 public boolean isCanceled() {
753 public void begin(int remainingWork
) {
754 this.totalWork
= remainingWork
;