use of dev.jbang.cli.ExitException in project jbang by jbangdev.
the class RunContext method forResource.
public Code forResource(String resource) {
Catalog catalog = getCatalog() != null ? Catalog.get(getCatalog().toPath()) : null;
ResourceResolver resolver = ResourceResolver.forScripts(this::resolveDependency, catalog);
ResourceRef resourceRef = resolver.resolve(resource);
// just proceed if the script file is a regular file at this point
if (resourceRef == null || !resourceRef.getFile().canRead()) {
throw new ExitException(BaseCommand.EXIT_INVALID_INPUT, "Script or alias could not be found or read: '" + resource + "'");
}
if (resourceRef instanceof AliasResourceResolver.AliasedResourceRef) {
// The resource we found was obtained from an alias which might
// contain extra options that need to be taken into account
// when running the code
Alias alias = ((AliasResourceResolver.AliasedResourceRef) resourceRef).getAlias();
if (getArguments() == null || getArguments().isEmpty()) {
setArguments(alias.arguments);
}
if (getJavaOptions() == null || getJavaOptions().isEmpty()) {
setJavaOptions(alias.javaOptions);
}
if (getAdditionalSources() == null || getAdditionalSources().isEmpty()) {
setAdditionalSources(alias.sources);
}
if (getAdditionalDependencies() == null || getAdditionalDependencies().isEmpty()) {
setAdditionalDependencies(alias.dependencies);
}
if (getAdditionalRepositories() == null || getAdditionalRepositories().isEmpty()) {
setAdditionalRepositories(alias.repositories);
}
if (getAdditionalClasspaths() == null || getAdditionalClasspaths().isEmpty()) {
setAdditionalClasspaths(alias.classpaths);
}
if (getProperties() == null || getProperties().isEmpty()) {
setProperties(alias.properties);
}
if (getJavaVersion() == null) {
setJavaVersion(alias.javaVersion);
}
if (getMainClass() == null) {
setMainClass(alias.mainClass);
}
setAlias(alias);
}
// note script file must be not null at this point
setOriginalRef(resource);
return forResourceRef(resourceRef);
}
use of dev.jbang.cli.ExitException in project jbang by jbangdev.
the class JarCmdGenerator method generateCommandLineList.
@Override
protected List<String> generateCommandLineList() throws IOException {
List<String> fullArgs = new ArrayList<>();
if (ctx.isNativeImage()) {
String imagename = getImageName(code.getJarFile()).toString();
if (new File(imagename).exists()) {
fullArgs.add(imagename);
} else {
Util.warnMsg("native built image not found - running in java mode.");
}
}
if (fullArgs.isEmpty()) {
String classpath = ctx.resolveClassPath(code);
List<String> optionalArgs = new ArrayList<>();
String requestedJavaVersion = ctx.getJavaVersion() != null ? ctx.getJavaVersion() : code.getJavaVersion().orElse(null);
String javacmd = JavaUtil.resolveInJavaHome("java", requestedJavaVersion);
addPropertyFlags(ctx.getProperties(), "-D", optionalArgs);
// optionalArgs.add("--source 11");
if (ctx.isDebugEnabled()) {
optionalArgs.add("-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=" + ctx.getDebugString());
}
if (ctx.isEnableAssertions()) {
optionalArgs.add("-ea");
}
if (ctx.isEnableSystemAssertions()) {
optionalArgs.add("-esa");
}
if (ctx.isFlightRecordingEnabled()) {
// TODO: find way to generate ~/.jbang/script.jfc to configure flightrecorder to
// have 0 ms thresholds
String jfropt = "-XX:StartFlightRecording=" + ctx.getFlightRecorderString().replace("{baseName}", Util.getBaseName(code.getResourceRef().getFile().toString()));
optionalArgs.add(jfropt);
Util.verboseMsg("Flight recording enabled with:" + jfropt);
}
if (code.getJarFile() != null) {
if (Util.isBlankString(classpath)) {
classpath = code.getJarFile().getAbsolutePath();
} else {
classpath = code.getJarFile().getAbsolutePath() + Settings.CP_SEPARATOR + classpath.trim();
}
}
if (!Util.isBlankString(classpath)) {
optionalArgs.add("-classpath");
optionalArgs.add(classpath);
}
if (Optional.ofNullable(ctx.getClassDataSharing()).orElse(code.enableCDS())) {
Path cdsJsa = code.getJarFile().toPath().toAbsolutePath();
if (Files.exists(cdsJsa)) {
Util.verboseMsg("CDS: Using shared archive classes from " + cdsJsa);
optionalArgs.add("-XX:SharedArchiveFile=" + cdsJsa);
} else {
Util.verboseMsg("CDS: Archiving Classes At Exit at " + cdsJsa);
optionalArgs.add("-XX:ArchiveClassesAtExit=" + cdsJsa);
}
}
fullArgs.add(javacmd);
addAgentsArgs(fullArgs);
fullArgs.addAll(ctx.getRuntimeOptionsMerged(code));
fullArgs.addAll(ctx.getAutoDetectedModuleArguments(code, requestedJavaVersion));
fullArgs.addAll(optionalArgs);
String mainClass = ctx.getMainClassOr(code);
if (mainClass != null) {
fullArgs.add(mainClass);
} else {
throw new ExitException(BaseCommand.EXIT_INVALID_INPUT, "no main class deduced, specified nor found in a manifest");
}
}
fullArgs.addAll(ctx.getArguments());
return fullArgs;
}
use of dev.jbang.cli.ExitException in project jbang by jbangdev.
the class DependencyUtil method resolveDependenciesViaAether.
public static List<ArtifactInfo> resolveDependenciesViaAether(List<String> depIds, List<MavenRepo> customRepos, boolean offline, boolean loggingEnabled, boolean transitively) {
ConfigurableMavenResolverSystem resolver = Maven.configureResolver().withMavenCentralRepo(false).workOffline(offline);
customRepos.forEach(mavenRepo -> mavenRepo.apply(resolver));
System.setProperty("maven.repo.local", Settings.getLocalMavenRepo().toPath().toAbsolutePath().toString());
Map<Boolean, List<MavenCoordinate>> coordList = depIds.stream().map(DependencyUtil::depIdToArtifact).collect(Collectors.partitioningBy(c -> c.getType().equals(PackagingType.POM)));
List<MavenCoordinate> coords = coordList.get(false);
List<MavenCoordinate> pomcoords = coordList.get(true);
PomEquippedResolveStage pomResolve = null;
if (!pomcoords.isEmpty()) {
String beforeDepMgmt = "<project xmlns=\"http://maven.apache.org/POM/4.0.0\"\n" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" + " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n" + " <modelVersion>4.0.0</modelVersion>\n" + "\n" + " <groupId>dev.jbang.internal</groupId>\n" + " <artifactId>dependency-pom</artifactId>\n" + " <version>1.0-SNAPSHOT</version>\n" + " <packaging>pom</packaging>\n" + "<dependencyManagement>\n" + " <dependencies>\n";
String afterDepMgmt = "</dependencies>\n" + "</dependencyManagement>\n" + "</project>";
StringBuffer buf = new StringBuffer(beforeDepMgmt);
for (MavenCoordinate pomcoord : pomcoords) {
buf.append("<dependency>\n" + " <groupId>" + pomcoord.getGroupId() + "</groupId>\n" + " <artifactId>" + pomcoord.getArtifactId() + "</artifactId>\n" + " <version>" + pomcoord.getVersion() + "</version>\n" + " <type>pom</type>\n" + " <scope>import</scope>\n" + " </dependency>\n");
}
buf.append(afterDepMgmt);
Path pompath = null;
try {
pompath = File.createTempFile("jbang", ".xml").toPath();
Util.writeString(pompath, buf.toString());
} catch (IOException e) {
throw new ExitException(CommandLine.ExitCode.SOFTWARE, "Error trying to generate pom.xml for dependency management");
}
if (loggingEnabled) {
infoMsg("Artifacts used for dependency management:");
infoMsgFmt(" %s\n", String.join("\n ", pomcoords.stream().map(Coordinate::toCanonicalForm).collect(Collectors.toList())));
}
pomResolve = resolver.loadPomFromFile(pompath.toFile());
}
Optional<MavenCoordinate> pom = coords.stream().filter(c -> c.getType().equals(PackagingType.POM)).findFirst();
if (pom.isPresent()) {
// when we support more than one BOM POM
throw new ExitException(1, "POM imports as found in " + pom.get().toCanonicalForm() + " is only supported as the first import.");
}
List<String> canonicals = coords.stream().map(Coordinate::toCanonicalForm).collect(Collectors.toList());
if (loggingEnabled) {
infoHeader();
infoMsgFmt("%s\n", String.join("\n ", canonicals));
}
try {
MavenStrategyStage resolve;
if (pomResolve != null) {
resolve = pomResolve.resolve(canonicals);
} else {
resolve = resolver.resolve(canonicals);
}
MavenFormatStage stage = transitively ? resolve.withTransitivity() : resolve.withoutTransitivity();
// , RUNTIME);
List<MavenResolvedArtifact> artifacts = stage.asList(MavenResolvedArtifact.class);
if (loggingEnabled)
infoMsgFmt("Done\n");
return artifacts.stream().map(mra -> new ArtifactInfo(mra.getCoordinate(), mra.asFile())).collect(Collectors.toList());
} catch (ResolutionException nrr) {
Throwable cause = nrr.getCause();
Set<Throwable> causes = new LinkedHashSet<Throwable>();
StringBuffer buf = new StringBuffer();
buf.append(nrr.getMessage());
while (cause != null && !causes.contains(cause)) {
causes.add(cause);
buf.append("\n " + cause.getMessage());
}
String repos = customRepos.stream().map(repo -> repo.toString()).collect(Collectors.joining(", "));
throw new ExitException(1, String.format("Could not resolve dependencies from %s\n", repos) + buf.toString(), nrr);
} catch (RuntimeException e) {
throw new ExitException(1, "Unknown error occurred while trying to resolve dependencies", e);
}
}
use of dev.jbang.cli.ExitException in project jbang by jbangdev.
the class TrustedSources method createTrustedSources.
public static void createTrustedSources() {
Path trustedSourcesFile = Settings.getTrustedSourcesFile();
if (Files.notExists(trustedSourcesFile)) {
String templateName = "trusted-sources.qute";
Template template = TemplateEngine.instance().getTemplate(templateName);
if (template == null)
throw new ExitException(1, "Could not locate template named: '" + templateName + "'");
String result = template.render();
try {
Util.writeString(trustedSourcesFile, result);
} catch (IOException e) {
Util.errorMsg("Could not create initial trusted-sources file at " + trustedSourcesFile, e);
}
}
}
use of dev.jbang.cli.ExitException in project jbang by jbangdev.
the class Catalog method getByRef.
/**
* Load a Catalog's aliases given a file path or URL
*
* @param catalogRef File path or URL to a Catalog JSON file. If this does not
* end in .json then jbang-catalog.json will be appended to
* the end.
* @return A Catalog object
*/
public static Catalog getByRef(String catalogRef) {
if (!catalogRef.endsWith(".json")) {
if (!catalogRef.endsWith("/")) {
catalogRef += "/";
}
catalogRef += JBANG_CATALOG_JSON;
}
Path catalogPath = null;
try {
Catalog catalog = get(ResourceRef.forResource(catalogRef));
if (catalog == null) {
throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to download catalog: " + catalogRef);
}
Util.verboseMsg(String.format("Obtained catalog from %s", catalogRef));
int p = catalogRef.lastIndexOf('/');
if (p > 0) {
String baseRef = catalog.baseRef;
String catalogBaseRef = catalogRef.substring(0, p);
if (baseRef != null) {
if (!baseRef.startsWith("/") && !baseRef.contains(":")) {
baseRef = catalogBaseRef + "/" + baseRef;
}
} else {
baseRef = catalogBaseRef;
}
catalog = new Catalog(baseRef, catalog.description, catalog.catalogRef, catalog.catalogs, catalog.aliases, catalog.templates);
}
return catalog;
} catch (JsonParseException ex) {
throw new ExitException(EXIT_UNEXPECTED_STATE, "Unable to download catalog: " + catalogRef + " via " + catalogPath, ex);
}
}
Aggregations