Search in sources :

Example 1 with MavenRepo

use of dev.jbang.dependencies.MavenRepo in project jbang by jbangdev.

the class Edit method renderTemplate.

private void renderTemplate(TemplateEngine engine, List<String> collectDependencies, String fullclassName, String baseName, List<String> resolvedDependencies, List<MavenRepo> repositories, String templateName, List<String> userParams, Path destination) throws IOException {
    Template template = engine.getTemplate(templateName);
    if (template == null)
        throw new ExitException(EXIT_INVALID_INPUT, "Could not locate template named: '" + templateName + "'");
    String result = template.data("repositories", repositories.stream().map(MavenRepo::getUrl).filter(s -> !"".equals(s))).data("dependencies", collectDependencies).data("gradledependencies", gradleify(collectDependencies)).data("baseName", baseName).data("fullClassName", fullclassName).data("classpath", resolvedDependencies.stream().filter(t -> !t.isEmpty()).collect(Collectors.toList())).data("userParams", String.join(" ", userParams)).data("cwd", System.getProperty("user.dir")).render();
    Util.writeString(destination, result);
}
Also used : java.util(java.util) MavenRepo(dev.jbang.dependencies.MavenRepo) System.out(java.lang.System.out) WatchKey(java.nio.file.WatchKey) dev.jbang.source(dev.jbang.source) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) JitPackUtil(dev.jbang.dependencies.JitPackUtil) CP_SEPARATOR(dev.jbang.Settings.CP_SEPARATOR) Charset(java.nio.charset.Charset) EditorManager(dev.jbang.net.EditorManager) TemplateEngine(dev.jbang.util.TemplateEngine) Path(java.nio.file.Path) CommandLine(picocli.CommandLine) Util(dev.jbang.util.Util) Files(java.nio.file.Files) WatchEvent(java.nio.file.WatchEvent) DependencyUtil(dev.jbang.dependencies.DependencyUtil) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Shell(dev.jbang.util.Util.Shell) File(java.io.File) WatchService(java.nio.file.WatchService) Template(io.quarkus.qute.Template) BaseBuilder.escapeOSArguments(dev.jbang.source.builders.BaseBuilder.escapeOSArguments) Settings(dev.jbang.Settings) Util.verboseMsg(dev.jbang.util.Util.verboseMsg) FileSystems(java.nio.file.FileSystems) Cache(dev.jbang.Cache) MavenRepo(dev.jbang.dependencies.MavenRepo) Template(io.quarkus.qute.Template)

Example 2 with MavenRepo

use of dev.jbang.dependencies.MavenRepo in project jbang by jbangdev.

the class IntegrationManager method runIntegration.

/**
 * Discovers all integration points and runs them.
 * <p>
 * If an integration point created a native image it returns the resulting
 * image.
 *
 * @param repositories
 * @param artifacts
 * @param tmpJarDir
 * @param pomPath
 * @param source
 * @param nativeRequested
 * @return
 */
public static IntegrationResult runIntegration(List<MavenRepo> repositories, List<ArtifactInfo> artifacts, Path tmpJarDir, Path pomPath, Source source, boolean nativeRequested) {
    URL[] urls = artifacts.stream().map(s -> {
        try {
            return s.getFile().toURI().toURL();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }).toArray(URL[]::new);
    List<String> comments = source.getLines().stream().filter(s -> s.startsWith("//")).collect(Collectors.toList());
    URLClassLoader integrationCl = new URLClassLoader(urls);
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Map<String, byte[]> data = new HashMap<>();
    List<Map.Entry<String, String>> repos = null;
    List<Map.Entry<String, Path>> deps = null;
    Path nativeImage = null;
    String mainClass = null;
    List<String> javaArgs = null;
    PrintStream oldout = System.out;
    try {
        // TODO: should we add new properties to the integration method?
        if (source.getResourceRef().getFile() != null) {
            System.setProperty("jbang.source", source.getResourceRef().getFile().getAbsolutePath());
        }
        Thread.currentThread().setContextClassLoader(integrationCl);
        Set<String> classNames = loadIntegrationClassNames(integrationCl);
        for (String className : classNames) {
            if (repos == null) {
                repos = repositories.stream().map(s -> new MapRepoEntry(s.getId(), s.getUrl())).collect(Collectors.toList());
            }
            if (deps == null) {
                deps = artifacts.stream().map(s -> new MapEntry(s.getCoordinate().toCanonicalForm(), s.getFile().toPath())).collect(Collectors.toList());
            }
            Class<?> clazz = Class.forName(className, true, integrationCl);
            Method method = clazz.getDeclaredMethod("postBuild", Path.class, Path.class, List.class, List.class, List.class, boolean.class);
            Util.infoMsg("Post build with " + className);
            if (Util.isVerbose()) {
                System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.err)));
            } else {
                System.setOut(new PrintStream(new OutputStream() {

                    public void write(int b) {
                    // DO NOTHING
                    // TODO: capture it for later print if error
                    }
                }));
            }
            @SuppressWarnings("unchecked") Map<String, Object> integrationResult = (Map<String, Object>) method.invoke(null, tmpJarDir, pomPath, repos, deps, comments, nativeRequested);
            @SuppressWarnings("unchecked") Map<String, byte[]> ret = (Map<String, byte[]>) integrationResult.get(FILES);
            if (ret != null) {
                data.putAll(ret);
            }
            Path image = (Path) integrationResult.get(NATIVE_IMAGE);
            if (image != null) {
                nativeImage = image;
            }
            String mc = (String) integrationResult.get(MAIN_CLASS);
            if (mc != null) {
                mainClass = mc;
            }
            @SuppressWarnings("unchecked") List<String> ja = (List<String>) integrationResult.get(JAVA_ARGS);
            if (ja != null) {
                javaArgs = ja;
            }
        }
        for (Map.Entry<String, byte[]> entry : data.entrySet()) {
            Path target = tmpJarDir.resolve(entry.getKey());
            Files.createDirectories(target.getParent());
            try (OutputStream out = Files.newOutputStream(target)) {
                out.write(entry.getValue());
            }
        }
    } catch (ClassNotFoundException e) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to load integration class", e);
    } catch (NoSuchMethodException e) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Integration class missing method with signature public static Map<String, byte[]> postBuild(Path classesDir, Path pomFile, List<Map.Entry<String, Path>> dependencies)", e);
    } catch (Exception e) {
        throw new ExitException(EXIT_UNEXPECTED_STATE, "Issue running postBuild()", e);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
        System.setOut(oldout);
    }
    return new IntegrationResult(nativeImage, mainClass, javaArgs);
}
Also used : Enumeration(java.util.Enumeration) URL(java.net.URL) HashMap(java.util.HashMap) MavenRepo(dev.jbang.dependencies.MavenRepo) Source(dev.jbang.source.Source) ExitException(dev.jbang.cli.ExitException) ArtifactInfo(dev.jbang.dependencies.ArtifactInfo) HashSet(java.util.HashSet) URLClassLoader(java.net.URLClassLoader) Map(java.util.Map) Method(java.lang.reflect.Method) Path(java.nio.file.Path) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) Util(dev.jbang.util.Util) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) Set(java.util.Set) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) EXIT_UNEXPECTED_STATE(dev.jbang.cli.BaseCommand.EXIT_UNEXPECTED_STATE) FileDescriptor(java.io.FileDescriptor) BufferedReader(java.io.BufferedReader) InputStream(java.io.InputStream) MalformedURLException(java.net.MalformedURLException) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) List(java.util.List) ExitException(dev.jbang.cli.ExitException) Path(java.nio.file.Path) PrintStream(java.io.PrintStream) Method(java.lang.reflect.Method) ExitException(dev.jbang.cli.ExitException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) URLClassLoader(java.net.URLClassLoader) FileOutputStream(java.io.FileOutputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with MavenRepo

use of dev.jbang.dependencies.MavenRepo in project jbang by jbangdev.

the class Edit method createProjectForEdit.

/**
 * Create Project to use for editing *
 */
File createProjectForEdit(SourceSet ss, RunContext ctx, boolean reload) throws IOException {
    File originalFile = ss.getResourceRef().getFile();
    List<String> dependencies = ss.getDependencies();
    String cp = ss.getClassPath().getClassPath();
    List<String> resolvedDependencies = Arrays.asList(cp.split(CP_SEPARATOR));
    File baseDir = Settings.getCacheDir(Cache.CacheClass.projects).toFile();
    String name = originalFile.getName();
    name = Util.unkebabify(name);
    File tmpProjectDir = new File(baseDir, name + "_jbang_" + Util.getStableID(originalFile.getAbsolutePath()));
    tmpProjectDir.mkdirs();
    tmpProjectDir = new File(tmpProjectDir, stripPrefix(name));
    tmpProjectDir.mkdirs();
    File srcDir = new File(tmpProjectDir, "src");
    srcDir.mkdir();
    Path srcFile = srcDir.toPath().resolve(name);
    Util.createLink(srcFile, originalFile.toPath());
    for (Source source : ss.getSources()) {
        File sfile = null;
        if (source.getJavaPackage().isPresent()) {
            File packageDir = new File(srcDir, source.getJavaPackage().get().replace(".", File.separator));
            packageDir.mkdirs();
            sfile = new File(packageDir, source.getResourceRef().getFile().getName());
        } else {
            sfile = new File(srcDir, source.getResourceRef().getFile().getName());
        }
        Path destFile = source.getResourceRef().getFile().toPath().toAbsolutePath();
        Util.createLink(sfile.toPath(), destFile);
    }
    for (RefTarget ref : ss.getResources()) {
        File target = ref.to(srcDir.toPath()).toFile();
        target.getParentFile().mkdirs();
        Util.createLink(target.toPath(), ref.getSource().getFile().toPath().toAbsolutePath());
    }
    // create build gradle
    Optional<String> packageName = Util.getSourcePackage(new String(Files.readAllBytes(srcFile), Charset.defaultCharset()));
    String baseName = Util.getBaseName(name);
    String fullClassName;
    fullClassName = packageName.map(s -> s + "." + baseName).orElse(baseName);
    String templateName = "build.qute.gradle";
    Path destination = new File(tmpProjectDir, "build.gradle").toPath();
    TemplateEngine engine = TemplateEngine.instance();
    // both collectDependencies and repositories are manipulated by
    // resolveDependencies
    List<MavenRepo> repositories = ss.getRepositories();
    if (repositories.isEmpty()) {
        ss.addRepository(DependencyUtil.toMavenRepo("mavencentral"));
    }
    // Turn any URL dependencies into regular GAV coordinates
    List<String> depIds = dependencies.stream().map(JitPackUtil::ensureGAV).collect(Collectors.toList());
    // And if we encountered URLs let's make sure the JitPack repo is available
    if (!depIds.equals(dependencies) && repositories.stream().noneMatch(r -> DependencyUtil.REPO_JITPACK.equals(r.getUrl()))) {
        ss.addRepository(DependencyUtil.toMavenRepo(DependencyUtil.ALIAS_JITPACK));
    }
    renderTemplate(engine, depIds, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    // setup eclipse
    templateName = ".qute.classpath";
    destination = new File(tmpProjectDir, ".classpath").toPath();
    renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    templateName = ".qute.project";
    destination = new File(tmpProjectDir, ".project").toPath();
    renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    templateName = "main.qute.launch";
    destination = new File(tmpProjectDir, ".eclipse/" + baseName + ".launch").toPath();
    destination.toFile().getParentFile().mkdirs();
    renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    templateName = "main-port-4004.qute.launch";
    destination = new File(tmpProjectDir, ".eclipse/" + baseName + "-port-4004.launch").toPath();
    renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    // setup vscode
    templateName = "launch.qute.json";
    destination = new File(tmpProjectDir, ".vscode/launch.json").toPath();
    if (isNeeded(reload, destination)) {
        destination.toFile().getParentFile().mkdirs();
        renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    }
    // setup vscode
    templateName = "README.qute.md";
    destination = new File(tmpProjectDir, "README.md").toPath();
    if (isNeeded(reload, destination)) {
        destination.toFile().getParentFile().mkdirs();
        renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    }
    templateName = "settings.qute.json";
    destination = new File(tmpProjectDir, ".vscode/settings.json").toPath();
    if (isNeeded(reload, destination)) {
        destination.toFile().getParentFile().mkdirs();
        renderTemplate(engine, dependencies, fullClassName, baseName, resolvedDependencies, repositories, templateName, ctx.getArguments(), destination);
    }
    return tmpProjectDir;
}
Also used : Path(java.nio.file.Path) java.util(java.util) MavenRepo(dev.jbang.dependencies.MavenRepo) System.out(java.lang.System.out) WatchKey(java.nio.file.WatchKey) dev.jbang.source(dev.jbang.source) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) JitPackUtil(dev.jbang.dependencies.JitPackUtil) CP_SEPARATOR(dev.jbang.Settings.CP_SEPARATOR) Charset(java.nio.charset.Charset) EditorManager(dev.jbang.net.EditorManager) TemplateEngine(dev.jbang.util.TemplateEngine) Path(java.nio.file.Path) CommandLine(picocli.CommandLine) Util(dev.jbang.util.Util) Files(java.nio.file.Files) WatchEvent(java.nio.file.WatchEvent) DependencyUtil(dev.jbang.dependencies.DependencyUtil) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Shell(dev.jbang.util.Util.Shell) File(java.io.File) WatchService(java.nio.file.WatchService) Template(io.quarkus.qute.Template) BaseBuilder.escapeOSArguments(dev.jbang.source.builders.BaseBuilder.escapeOSArguments) Settings(dev.jbang.Settings) Util.verboseMsg(dev.jbang.util.Util.verboseMsg) FileSystems(java.nio.file.FileSystems) Cache(dev.jbang.Cache) TemplateEngine(dev.jbang.util.TemplateEngine) MavenRepo(dev.jbang.dependencies.MavenRepo) File(java.io.File)

Aggregations

MavenRepo (dev.jbang.dependencies.MavenRepo)3 Util (dev.jbang.util.Util)3 IOException (java.io.IOException)3 Files (java.nio.file.Files)3 Path (java.nio.file.Path)3 Collectors (java.util.stream.Collectors)3 Cache (dev.jbang.Cache)2 Settings (dev.jbang.Settings)2 CP_SEPARATOR (dev.jbang.Settings.CP_SEPARATOR)2 DependencyUtil (dev.jbang.dependencies.DependencyUtil)2 JitPackUtil (dev.jbang.dependencies.JitPackUtil)2 EditorManager (dev.jbang.net.EditorManager)2 dev.jbang.source (dev.jbang.source)2 BaseBuilder.escapeOSArguments (dev.jbang.source.builders.BaseBuilder.escapeOSArguments)2 TemplateEngine (dev.jbang.util.TemplateEngine)2 Shell (dev.jbang.util.Util.Shell)2 Util.verboseMsg (dev.jbang.util.Util.verboseMsg)2 Template (io.quarkus.qute.Template)2 File (java.io.File)2 System.out (java.lang.System.out)2