]> git.argeo.org Git - cc0/argeo-build.git/blob - argeo/build/Make.java
Releasing
[cc0/argeo-build.git] / argeo / build / Make.java
1 package org.argeo.build;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.io.PrintWriter;
8 import java.lang.management.ManagementFactory;
9 import java.nio.file.FileVisitResult;
10 import java.nio.file.Files;
11 import java.nio.file.Path;
12 import java.nio.file.PathMatcher;
13 import java.nio.file.Paths;
14 import java.nio.file.SimpleFileVisitor;
15 import java.nio.file.attribute.BasicFileAttributes;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.HashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Objects;
22 import java.util.Properties;
23 import java.util.StringJoiner;
24 import java.util.StringTokenizer;
25 import java.util.jar.JarEntry;
26 import java.util.jar.JarOutputStream;
27 import java.util.jar.Manifest;
28
29 import org.eclipse.jdt.core.compiler.CompilationProgress;
30
31 import aQute.bnd.osgi.Analyzer;
32 import aQute.bnd.osgi.Jar;
33
34 public class Make {
35 private final static String SDK_MK = "sdk.mk";
36
37 final Path execDirectory;
38 final Path sdkSrcBase;
39 final Path argeoBuildBase;
40 final Path sdkBuildBase;
41 final Path buildBase;
42 final Path a2Output;
43
44 public Make() throws IOException {
45 execDirectory = Paths.get(System.getProperty("user.dir"));
46 Path sdkMkP = findSdkMk(execDirectory);
47 Objects.requireNonNull(sdkMkP, "No " + SDK_MK + " found under " + execDirectory);
48
49 Map<String, String> context = new HashMap<>();
50 List<String> sdkMkLines = Files.readAllLines(sdkMkP);
51 lines: for (String line : sdkMkLines) {
52 StringTokenizer st = new StringTokenizer(line, " :=");
53 if (!st.hasMoreTokens())
54 continue lines;
55 String key = st.nextToken();
56 if (!st.hasMoreTokens())
57 continue lines;
58 String value = st.nextToken();
59 context.put(key, value);
60 }
61
62 sdkSrcBase = Paths.get(context.computeIfAbsent("SDK_SRC_BASE", (key) -> {
63 throw new IllegalStateException(key + " not found");
64 })).toAbsolutePath();
65 argeoBuildBase = sdkSrcBase.resolve("sdk/argeo-build");
66
67 sdkBuildBase = Paths.get(context.computeIfAbsent("SDK_BUILD_BASE", (key) -> {
68 throw new IllegalStateException(key + " not found");
69 })).toAbsolutePath();
70 buildBase = sdkBuildBase.resolve(sdkSrcBase.getFileName());
71 a2Output = sdkBuildBase.resolve("a2");
72 }
73
74 /*
75 * ACTIONS
76 */
77
78 void all(Map<String, List<String>> options) throws IOException {
79 // List<String> a2Bundles = options.get("--a2-bundles");
80 // if (a2Bundles == null)
81 // throw new IllegalArgumentException("--a2-bundles must be specified");
82 // List<String> bundles = new ArrayList<>();
83 // for (String a2Bundle : a2Bundles) {
84 // Path a2BundleP = Paths.get(a2Bundle);
85 // Path bundleP = a2Output.relativize(a2BundleP.getParent().getParent().resolve(a2BundleP.getFileName()));
86 // bundles.add(bundleP.toString());
87 // }
88 // options.put("--bundles", bundles);
89 compile(options);
90 bundle(options);
91 }
92
93 @SuppressWarnings("restriction")
94 void compile(Map<String, List<String>> options) throws IOException {
95 List<String> bundles = options.get("--bundles");
96 Objects.requireNonNull(bundles, "--bundles argument must be set");
97 if (bundles.isEmpty())
98 return;
99
100 List<String> a2Categories = options.getOrDefault("--dep-categories", new ArrayList<>());
101 List<String> a2Bases = options.getOrDefault("--a2-bases", new ArrayList<>());
102 if (a2Bases.isEmpty()) {
103 a2Bases.add(a2Output.toString());
104 }
105
106 List<String> compilerArgs = new ArrayList<>();
107
108 Path ecjArgs = argeoBuildBase.resolve("ecj.args");
109 compilerArgs.add("@" + ecjArgs);
110
111 // classpath
112 if (!a2Categories.isEmpty()) {
113 compilerArgs.add("-cp");
114 StringJoiner classPath = new StringJoiner(File.pathSeparator);
115 for (String a2Base : a2Bases) {
116 for (String a2Category : a2Categories) {
117 Path a2Dir = Paths.get(a2Base).resolve(a2Category);
118 for (Path jarP : Files.newDirectoryStream(a2Dir,
119 (p) -> p.getFileName().toString().endsWith(".jar"))) {
120 classPath.add(jarP.toString());
121 }
122 }
123 }
124 compilerArgs.add(classPath.toString());
125 }
126
127 // sources
128 for (String bundle : bundles) {
129 StringBuilder sb = new StringBuilder();
130 sb.append(execDirectory.resolve(bundle).resolve("src"));
131 sb.append("[-d");
132 compilerArgs.add(sb.toString());
133 sb = new StringBuilder();
134 sb.append(buildBase.resolve(bundle).resolve("bin"));
135 sb.append("]");
136 compilerArgs.add(sb.toString());
137 }
138
139 // System.out.println(compilerArgs);
140
141 CompilationProgress compilationProgress = new CompilationProgress() {
142 int totalWork;
143 long currentChunk = 0;
144
145 long chunksCount = 80;
146
147 @Override
148 public void worked(int workIncrement, int remainingWork) {
149 long chunk = ((totalWork - remainingWork) * chunksCount) / totalWork;
150 if (chunk != currentChunk) {
151 currentChunk = chunk;
152 for (long i = 0; i < currentChunk; i++) {
153 System.out.print("#");
154 }
155 for (long i = currentChunk; i < chunksCount; i++) {
156 System.out.print("-");
157 }
158 System.out.print("\r");
159 }
160 if (remainingWork == 0)
161 System.out.print("\n");
162 }
163
164 @Override
165 public void setTaskName(String name) {
166 }
167
168 @Override
169 public boolean isCanceled() {
170 return false;
171 }
172
173 @Override
174 public void done() {
175 }
176
177 @Override
178 public void begin(int remainingWork) {
179 this.totalWork = remainingWork;
180 }
181 };
182 // Use Main instead of BatchCompiler to workaround the fact that
183 // org.eclipse.jdt.core.compiler.batch is not exported
184 boolean success = org.eclipse.jdt.internal.compiler.batch.Main.compile(
185 compilerArgs.toArray(new String[compilerArgs.size()]), new PrintWriter(System.out),
186 new PrintWriter(System.err), (CompilationProgress) compilationProgress);
187 if (!success) {
188 System.exit(1);
189 }
190 }
191
192 void bundle(Map<String, List<String>> options) throws IOException {
193 List<String> bundles = options.get("--bundles");
194 Objects.requireNonNull(bundles, "--bundles argument must be set");
195 if (bundles.isEmpty())
196 return;
197
198 List<String> categories = options.get("--category");
199 Objects.requireNonNull(bundles, "--bundles argument must be set");
200 if (categories.size() != 1)
201 throw new IllegalArgumentException("One and only one category must be specified");
202 String category = categories.get(0);
203
204 // create jars
205 for (String bundle : bundles) {
206 createBundle(bundle, category);
207 }
208 }
209
210 /*
211 * JAR PACKAGING
212 */
213 void createBundle(String bundle, String category) throws IOException {
214 Path source = execDirectory.resolve(bundle);
215 Path compiled = buildBase.resolve(bundle);
216 String bundleSymbolicName = source.getFileName().toString();
217
218 // Metadata
219 Properties properties = new Properties();
220 Path argeoBnd = argeoBuildBase.resolve("argeo.bnd");
221 try (InputStream in = Files.newInputStream(argeoBnd)) {
222 properties.load(in);
223 }
224 // FIXME make it configurable
225 Path branchBnd = sdkSrcBase.resolve("cnf/unstable.bnd");
226 try (InputStream in = Files.newInputStream(branchBnd)) {
227 properties.load(in);
228 }
229
230 Path bndBnd = source.resolve("bnd.bnd");
231 try (InputStream in = Files.newInputStream(bndBnd)) {
232 properties.load(in);
233 }
234
235 // Normalise
236 properties.put("Bundle-SymbolicName", bundleSymbolicName);
237
238 // Calculate MANIFEST
239 Path binP = compiled.resolve("bin");
240 Manifest manifest;
241 try (Analyzer bndAnalyzer = new Analyzer()) {
242 bndAnalyzer.setProperties(properties);
243 Jar jar = new Jar(bundleSymbolicName, binP.toFile());
244 bndAnalyzer.setJar(jar);
245 manifest = bndAnalyzer.calcManifest();
246
247 // keys: for (Object key : manifest.getMainAttributes().keySet()) {
248 // System.out.println(key + ": " + manifest.getMainAttributes().getValue(key.toString()));
249 // }
250 } catch (Exception e) {
251 throw new RuntimeException("Bnd analysis of " + compiled + " failed", e);
252 }
253
254 String major = properties.getProperty("MAJOR");
255 Objects.requireNonNull(major, "MAJOR must be set");
256 String minor = properties.getProperty("MINOR");
257 Objects.requireNonNull(minor, "MINOR must be set");
258
259 // Write manifest
260 Path manifestP = compiled.resolve("META-INF/MANIFEST.MF");
261 Files.createDirectories(manifestP.getParent());
262 try (OutputStream out = Files.newOutputStream(manifestP)) {
263 manifest.write(out);
264 }
265 //
266 // // Load manifest
267 // Path manifestP = compiled.resolve("META-INF/MANIFEST.MF");
268 // if (!Files.exists(manifestP))
269 // throw new IllegalStateException("Manifest " + manifestP + " not found");
270 // Manifest manifest;
271 // try (InputStream in = Files.newInputStream(manifestP)) {
272 // manifest = new Manifest(in);
273 // } catch (IOException e) {
274 // throw new IllegalStateException("Cannot read manifest " + manifestP, e);
275 // }
276
277 // Load excludes
278 List<PathMatcher> excludes = new ArrayList<>();
279 Path excludesP = argeoBuildBase.resolve("excludes.txt");
280 for (String line : Files.readAllLines(excludesP)) {
281 PathMatcher pathMatcher = excludesP.getFileSystem().getPathMatcher("glob:" + line);
282 excludes.add(pathMatcher);
283 }
284
285 Path bundleParent = Paths.get(bundle).getParent();
286 Path a2JarDirectory = bundleParent != null ? a2Output.resolve(bundleParent).resolve(category)
287 : a2Output.resolve(category);
288 Path jarP = a2JarDirectory.resolve(compiled.getFileName() + "." + major + "." + minor + ".jar");
289 Files.createDirectories(jarP.getParent());
290
291 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarP), manifest)) {
292 // add all classes first
293 // Path binP = compiled.resolve("bin");
294 Files.walkFileTree(binP, new SimpleFileVisitor<Path>() {
295
296 @Override
297 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
298 jarOut.putNextEntry(new JarEntry(binP.relativize(file).toString()));
299 Files.copy(file, jarOut);
300 return FileVisitResult.CONTINUE;
301 }
302 });
303
304 // add resources
305 Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
306
307 @Override
308 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
309 Path relativeP = source.relativize(dir);
310 for (PathMatcher exclude : excludes)
311 if (exclude.matches(relativeP))
312 return FileVisitResult.SKIP_SUBTREE;
313
314 return FileVisitResult.CONTINUE;
315 }
316
317 @Override
318 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
319 Path relativeP = source.relativize(file);
320 for (PathMatcher exclude : excludes)
321 if (exclude.matches(relativeP))
322 return FileVisitResult.CONTINUE;
323 JarEntry entry = new JarEntry(relativeP.toString());
324 jarOut.putNextEntry(entry);
325 Files.copy(file, jarOut);
326 return FileVisitResult.CONTINUE;
327 }
328
329 });
330
331 // add sources
332 // TODO add effective BND, Eclipse project file, etc., in order to be able to
333 // repackage
334 Path srcP = source.resolve("src");
335 Files.walkFileTree(srcP, new SimpleFileVisitor<Path>() {
336
337 @Override
338 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
339 jarOut.putNextEntry(new JarEntry("OSGI-OPT/src/" + srcP.relativize(file).toString()));
340 Files.copy(file, jarOut);
341 return FileVisitResult.CONTINUE;
342 }
343 });
344
345 }
346
347 }
348
349 private Path findSdkMk(Path directory) {
350 Path sdkMkP = directory.resolve(SDK_MK);
351 if (Files.exists(sdkMkP)) {
352 return sdkMkP.toAbsolutePath();
353 }
354 if (directory.getParent() == null)
355 return null;
356 return findSdkMk(directory.getParent());
357
358 }
359
360 public static void main(String... args) {
361 try {
362 if (args.length == 0)
363 throw new IllegalArgumentException("At least an action must be provided");
364 int actionIndex = 0;
365 String action = args[actionIndex];
366 if (args.length > actionIndex + 1 && !args[actionIndex + 1].startsWith("-"))
367 throw new IllegalArgumentException(
368 "Action " + action + " must be followed by an option: " + Arrays.asList(args));
369
370 Map<String, List<String>> options = new HashMap<>();
371 String currentOption = null;
372 for (int i = actionIndex + 1; i < args.length; i++) {
373 if (args[i].startsWith("-")) {
374 currentOption = args[i];
375 if (!options.containsKey(currentOption))
376 options.put(currentOption, new ArrayList<>());
377
378 } else {
379 options.get(currentOption).add(args[i]);
380 }
381 }
382
383 Make argeoMake = new Make();
384 switch (action) {
385 case "compile" -> argeoMake.compile(options);
386 case "bundle" -> argeoMake.bundle(options);
387 case "all" -> argeoMake.all(options);
388
389 default -> throw new IllegalArgumentException("Unkown action: " + action);
390 }
391
392 long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
393 System.out.println("Completed after " + jvmUptime + " ms");
394 } catch (Exception e) {
395 e.printStackTrace();
396 System.exit(1);
397 }
398 }
399 }