]> git.argeo.org Git - cc0/argeo-build.git/blobdiff - src/org/argeo/build/Repackage.java
Do not package sources separately by default
[cc0/argeo-build.git] / src / org / argeo / build / Repackage.java
index de99e5f8c453af44d532d69f67db3952ddafc204..35413fe336df06dee5008f9fba2b827eba98e8a0 100644 (file)
@@ -1,12 +1,14 @@
 package org.argeo.build;
 
 import static java.lang.System.Logger.Level.DEBUG;
+import static java.lang.System.Logger.Level.WARNING;
 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_SYMBOLICNAME;
 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_VERSION;
 import static org.argeo.build.Repackage.ManifestConstants.EXPORT_PACKAGE;
 import static org.argeo.build.Repackage.ManifestConstants.SLC_ORIGIN_M2;
 import static org.argeo.build.Repackage.ManifestConstants.SLC_ORIGIN_M2_REPO;
 
+import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
@@ -35,6 +37,7 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.Properties;
 import java.util.TreeMap;
+import java.util.concurrent.CompletableFuture;
 import java.util.jar.Attributes;
 import java.util.jar.JarEntry;
 import java.util.jar.JarInputStream;
@@ -49,6 +52,10 @@ import aQute.bnd.osgi.Jar;
 public class Repackage {
        private final static Logger logger = System.getLogger(Repackage.class.getName());
 
+       private final static String ENV_BUILD_SOURCE_BUNDLES = "BUILD_SOURCE_BUNDLES";
+
+       private final static boolean parallel = true;
+
        /** Main entry point. */
        public static void main(String[] args) {
                if (args.length < 2) {
@@ -57,12 +64,17 @@ public class Repackage {
                }
                Path a2Base = Paths.get(args[0]).toAbsolutePath().normalize();
                Path descriptorsBase = Paths.get(".").toAbsolutePath().normalize();
-               Repackage factory = new Repackage(a2Base, descriptorsBase, true);
+               Repackage factory = new Repackage(a2Base, descriptorsBase);
 
+               List<CompletableFuture<Void>> toDos = new ArrayList<>();
                for (int i = 1; i < args.length; i++) {
                        Path p = Paths.get(args[i]);
-                       factory.processCategory(p);
+                       if (parallel)
+                               toDos.add(CompletableFuture.runAsync(() -> factory.processCategory(p)));
+                       else
+                               factory.processCategory(p);
                }
+               CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
        }
 
        private final static String COMMON_BND = "common.bnd";
@@ -75,12 +87,16 @@ public class Repackage {
 
        private Properties uris = new Properties();
 
-       private boolean includeSources = true;
-
        /** key is URI prefix, value list of base URLs */
        private Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
 
-       public Repackage(Path a2Base, Path descriptorsBase, boolean includeSources) {
+       private final boolean sourceBundles;
+
+       public Repackage(Path a2Base, Path descriptorsBase) {
+               sourceBundles = Boolean.parseBoolean(System.getenv(ENV_BUILD_SOURCE_BUNDLES));
+               if (sourceBundles)
+                       logger.log(Level.INFO, "Sources will be packaged separately");
+
                Objects.requireNonNull(a2Base);
                Objects.requireNonNull(descriptorsBase);
                this.originBase = Paths.get(System.getProperty("user.home"), ".cache", "argeo/build/origin");
@@ -90,7 +106,6 @@ public class Repackage {
                this.descriptorsBase = descriptorsBase;
                if (!Files.exists(this.descriptorsBase))
                        throw new IllegalArgumentException(this.descriptorsBase + " does not exist");
-               this.includeSources = includeSources;
 
                // URIs mapping
                Path urisPath = this.descriptorsBase.resolve("uris.properties");
@@ -176,7 +191,7 @@ public class Repackage {
                                throw new IllegalArgumentException("No M2 coordinates available for " + bndFile);
                        M2Artifact artifact = new M2Artifact(m2Coordinates);
                        URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
-                       Path downloaded = download(url, originBase, artifact);
+                       Path downloaded = downloadMaven(url, originBase, artifact);
 
                        Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, fileProps, artifact);
 
@@ -262,7 +277,7 @@ public class Repackage {
 
                                // download
                                URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
-                               Path downloaded = download(url, originBase, artifact);
+                               Path downloaded = downloadMaven(url, originBase, artifact);
 
                                Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, mergeProps, artifact);
 //                             logger.log(Level.DEBUG, () -> "Processed " + downloaded);
@@ -302,6 +317,10 @@ public class Repackage {
                mergeProps.put(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
 
                String artifactsStr = mergeProps.getProperty(ManifestConstants.SLC_ORIGIN_M2_MERGE.toString());
+               if (artifactsStr == null)
+                       throw new IllegalArgumentException(
+                                       mergeBnd + ": " + ManifestConstants.SLC_ORIGIN_M2_MERGE + " must be set");
+
                String repoStr = mergeProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
                                ? mergeProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
                                : null;
@@ -321,7 +340,7 @@ public class Repackage {
                        if (artifact.getVersion() == null)
                                artifact.setVersion(m2Version);
                        URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
-                       Path downloaded = download(url, originBase, artifact);
+                       Path downloaded = downloadMaven(url, originBase, artifact);
                        JarEntry entry;
                        try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(downloaded), false)) {
                                entries: while ((entry = jarIn.getNextJarEntry()) != null) {
@@ -358,8 +377,7 @@ public class Repackage {
                                                        try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
                                                                out.write("\n".getBytes());
                                                                jarIn.transferTo(out);
-                                                               if (logger.isLoggable(DEBUG))
-                                                                       logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
+                                                               logger.log(Level.WARNING, artifact.getArtifactId() + " - Appended " + entry.getName());
                                                        }
                                                } else if (entry.getName().startsWith("org/apache/batik/")) {
                                                        logger.log(Level.WARNING, "Skip " + entry.getName());
@@ -384,8 +402,7 @@ public class Repackage {
                                                OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
                                        out.write("\n".getBytes());
                                        in.transferTo(out);
-                                       if (logger.isLoggable(DEBUG))
-                                               logger.log(DEBUG, "Appended " + p);
+                                       logger.log(Level.WARNING, "Appended " + p);
                                }
                        }
                }
@@ -499,20 +516,26 @@ public class Repackage {
        /** Download and integrates sources for a single Maven artifact. */
        protected void downloadAndProcessM2Sources(String repoStr, M2Artifact artifact, Path targetBundleDir)
                        throws IOException {
-               if (!includeSources)
-                       return;
-               M2Artifact sourcesArtifact = new M2Artifact(artifact.toM2Coordinates(), "sources");
-               URL sourcesUrl = M2ConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
-               Path sourcesDownloaded = download(sourcesUrl, originBase, artifact, true);
-               processM2SourceJar(sourcesDownloaded, targetBundleDir);
-               logger.log(Level.TRACE, () -> "Processed source " + sourcesDownloaded);
+//             if (sourceBundles)
+//                     return;
+               try {
+                       M2Artifact sourcesArtifact = new M2Artifact(artifact.toM2Coordinates(), "sources");
+                       URL sourcesUrl = M2ConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
+                       Path sourcesDownloaded = downloadMaven(sourcesUrl, originBase, artifact, true);
+                       processM2SourceJar(sourcesDownloaded, targetBundleDir);
+                       logger.log(Level.TRACE, () -> "Processed source " + sourcesDownloaded);
+               } catch (Exception e) {
+                       logger.log(Level.ERROR, () -> "Cannot download source for  " + artifact);
+               }
 
        }
 
        /** Integrate sources from a downloaded jar file. */
        protected void processM2SourceJar(Path file, Path targetBundleDir) throws IOException {
                try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
-                       Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
+                       Path targetSourceDir = sourceBundles
+                                       ? targetBundleDir.getParent().resolve(targetBundleDir.toString() + ".src")
+                                       : targetBundleDir.resolve("OSGI-OPT/src");
 
                        // TODO make it less dangerous?
                        if (Files.exists(targetSourceDir)) {
@@ -546,12 +569,12 @@ public class Repackage {
        }
 
        /** Download a Maven artifact. */
-       protected Path download(URL url, Path dir, M2Artifact artifact) throws IOException {
-               return download(url, dir, artifact, false);
+       protected Path downloadMaven(URL url, Path dir, M2Artifact artifact) throws IOException {
+               return downloadMaven(url, dir, artifact, false);
        }
 
        /** Download a Maven artifact. */
-       protected Path download(URL url, Path dir, M2Artifact artifact, boolean sources) throws IOException {
+       protected Path downloadMaven(URL url, Path dir, M2Artifact artifact, boolean sources) throws IOException {
                return download(url, dir, artifact.getGroupId() + '/' + artifact.getArtifactId() + "-" + artifact.getVersion()
                                + (sources ? "-sources" : "") + ".jar");
        }
@@ -564,7 +587,6 @@ public class Repackage {
        public void processEclipseArchive(Path duDir) {
                try {
                        Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
-                       // String category = categoryRelativePath.getFileName().toString();
                        Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
                        Files.createDirectories(targetCategoryBase);
                        // first delete all directories from previous builds
@@ -586,7 +608,7 @@ public class Repackage {
                                        throw new IllegalStateException("No url available for " + duDir);
                                commonProps.put(ManifestConstants.SLC_ORIGIN_URI.toString(), url);
                        }
-                       Path downloaded = tryDownload(url, originBase);
+                       Path downloaded = tryDownloadArchive(url, originBase);
 
                        FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
 
@@ -626,9 +648,11 @@ public class Repackage {
                                                                        return FileVisitResult.CONTINUE;
                                                                }
                                                        }
-                                                       if (includeSources && file.getFileName().toString().contains(".source_")) {
+                                                       if (file.getFileName().toString().contains(".source_")) {
+//                                                             if (!sourceBundles) {
                                                                processEclipseSourceJar(file, targetCategoryBase);
                                                                logger.log(Level.DEBUG, () -> "Processed source " + file);
+//                                                             }
 
                                                        } else {
                                                                Map<String, String> map = new HashMap<>();
@@ -644,8 +668,8 @@ public class Repackage {
                                }
                        });
 
-                       DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase,
-                                       (p) -> Files.isDirectory(p) && p.getFileName().toString().indexOf('.') >= 0);
+                       DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)
+                                       && p.getFileName().toString().indexOf('.') >= 0 && !p.getFileName().toString().endsWith(".src"));
                        for (Path dir : dirs) {
                                createJar(dir);
                        }
@@ -668,7 +692,9 @@ public class Repackage {
                                NameVersion nameVersion = new NameVersion(relatedBundle[0], version);
                                targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
 
-                               Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
+                               Path targetSourceDir = sourceBundles
+                                               ? targetBundleDir.getParent().resolve(targetBundleDir.toString() + ".src")
+                                               : targetBundleDir.resolve("OSGI-OPT/src");
 
                                // TODO make it less dangerous?
                                if (Files.exists(targetSourceDir)) {
@@ -825,7 +851,8 @@ public class Repackage {
                                Object previousValue = manifest.getMainAttributes().putValue(key, value);
                                if (previousValue != null && !previousValue.equals(value)) {
                                        if (ManifestConstants.IMPORT_PACKAGE.toString().equals(key)
-                                                       || ManifestConstants.EXPORT_PACKAGE.toString().equals(key))
+                                                       || ManifestConstants.EXPORT_PACKAGE.toString().equals(key)
+                                                       || ManifestConstants.BUNDLE_LICENSE.toString().equals(key))
                                                logger.log(Level.TRACE, file.getFileName() + ": " + key + " was modified");
                                        else
                                                logger.log(Level.WARNING, file.getFileName() + ": " + key + " was " + previousValue
@@ -885,7 +912,7 @@ public class Repackage {
        }
 
        /** Try to download from an URI. */
-       protected Path tryDownload(String uri, Path dir) throws IOException {
+       protected Path tryDownloadArchive(String uri, Path dir) throws IOException {
                // find mirror
                List<String> urlBases = null;
                String uriPrefix = null;
@@ -900,7 +927,7 @@ public class Repackage {
                }
                if (urlBases == null)
                        try {
-                               return download(new URL(uri), dir);
+                               return downloadArchive(new URL(uri), dir);
                        } catch (FileNotFoundException e) {
                                throw new FileNotFoundException("Cannot find " + uri);
                        }
@@ -910,7 +937,7 @@ public class Repackage {
                        String relativePath = uri.substring(uriPrefix.length());
                        URL url = new URL(urlBase + relativePath);
                        try {
-                               return download(url, dir);
+                               return downloadArchive(url, dir);
                        } catch (FileNotFoundException e) {
                                logger.log(Level.WARNING, "Cannot download " + url + ", trying another mirror");
                        }
@@ -918,8 +945,11 @@ public class Repackage {
                throw new FileNotFoundException("Cannot find " + uri);
        }
 
-       /** Effectively download. */
-       protected Path download(URL url, Path dir) throws IOException {
+       /**
+        * Effectively download. Synchronised in order to avoid downloading twice in
+        * parallel.
+        */
+       protected synchronized Path downloadArchive(URL url, Path dir) throws IOException {
                return download(url, dir, (String) null);
        }
 
@@ -928,7 +958,10 @@ public class Repackage {
 
                Path dest;
                if (name == null) {
-                       name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1);
+                       // We use also use parent directory in case the archive itself has a fixed name
+                       String[] segments = url.getPath().split("/");
+                       name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
+                                       : segments[segments.length - 1];
                }
 
                dest = dir.resolve(name);
@@ -963,7 +996,8 @@ public class Repackage {
                                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                                        if (file.getFileName().toString().equals("MANIFEST.MF"))
                                                return super.visitFile(file, attrs);
-                                       JarEntry entry = new JarEntry(bundleDir.relativize(file).toString());
+                                       JarEntry entry = new JarEntry(
+                                                       bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
                                        jarOut.putNextEntry(entry);
                                        Files.copy(file, jarOut);
                                        return super.visitFile(file, attrs);
@@ -972,6 +1006,45 @@ public class Repackage {
                        });
                }
                deleteDirectory(bundleDir);
+
+               if (sourceBundles) {
+                       Path sourceDir = bundleDir.getParent().resolve(bundleDir.toString() + ".src");
+                       if (!Files.exists(sourceDir)) {
+                               logger.log(WARNING, sourceDir + " does not exist, skipping...");
+                               return jarPath;
+                       }
+                       Path srcJarP = sourceDir.getParent().resolve(sourceDir.getFileName() + ".jar");
+                       String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
+                       // in case there are additional directives
+                       bundleSymbolicName = bundleSymbolicName.split(";")[0];
+                       Manifest srcManifest = new Manifest();
+                       srcManifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
+                       srcManifest.getMainAttributes().putValue("Bundle-SymbolicName", bundleSymbolicName + ".src");
+                       srcManifest.getMainAttributes().putValue("Bundle-Version",
+                                       manifest.getMainAttributes().getValue("Bundle-Version").toString());
+                       srcManifest.getMainAttributes().putValue("Eclipse-SourceBundle",
+                                       bundleSymbolicName + ";version=\"" + manifest.getMainAttributes().getValue("Bundle-Version"));
+
+                       try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
+                               srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
+                               Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
+
+                                       @Override
+                                       public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+                                               if (file.getFileName().toString().equals("MANIFEST.MF"))
+                                                       return super.visitFile(file, attrs);
+                                               JarEntry entry = new JarEntry(
+                                                               sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
+                                               srcJarOut.putNextEntry(entry);
+                                               Files.copy(file, srcJarOut);
+                                               return super.visitFile(file, attrs);
+                                       }
+
+                               });
+                       }
+                       deleteDirectory(sourceDir);
+               }
+
                return jarPath;
        }