Skip to content

Commit

Permalink
fix: use //GAV for export mavenrepo (#1468)
Browse files Browse the repository at this point in the history
Fixes #1465
  • Loading branch information
quintesse authored Sep 29, 2022
1 parent 7c99280 commit 4d6ab0e
Show file tree
Hide file tree
Showing 9 changed files with 93 additions and 25 deletions.
9 changes: 4 additions & 5 deletions src/main/java/dev/jbang/cli/Export.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import dev.jbang.Settings;
import dev.jbang.dependencies.ArtifactInfo;
import dev.jbang.dependencies.DependencyUtil;
import dev.jbang.dependencies.MavenCoordinate;
import dev.jbang.source.Code;
import dev.jbang.source.RunContext;
Expand Down Expand Up @@ -200,7 +199,7 @@ int apply(Code code, RunContext ctx) throws IOException {

if (!outputPath.toFile().isDirectory()) {
if (outputPath.toFile().exists()) {
Util.warnMsg("Cannot export to maven publish as " + outputPath + " is not a directory.");
Util.warnMsg("Cannot export as maven repository as " + outputPath + " is not a directory.");
return EXIT_INVALID_INPUT;
}
if (exportMixin.force) {
Expand All @@ -212,7 +211,7 @@ int apply(Code code, RunContext ctx) throws IOException {
}

if (code.getGav().isPresent()) {
MavenCoordinate coord = MavenCoordinate.fromString(DependencyUtil.gavWithVersion(code.getGav().get()));
MavenCoordinate coord = MavenCoordinate.fromString(code.getGav().get()).withVersion();
if (group == null) {
group = coord.getGroupId();
}
Expand All @@ -226,7 +225,7 @@ int apply(Code code, RunContext ctx) throws IOException {

if (group == null) {
Util.warnMsg(
"Cannot export to maven publish as no group specified. Add --group=<group id> and run again.");
"Cannot export as maven repository as no group specified. Add --group=<group id> and run again.");
return EXIT_INVALID_INPUT;
}
Path groupdir = outputPath.resolve(Paths.get(group.replace(".", "/")));
Expand All @@ -235,7 +234,7 @@ int apply(Code code, RunContext ctx) throws IOException {
: Util.getBaseName(code.getResourceRef().getFile().getFileName().toString());
Path artifactDir = groupdir.resolve(artifact);

version = version != null ? version : "999-SNAPSHOT";
version = version != null ? version : MavenCoordinate.DEFAULT_VERSION;
Path versionDir = artifactDir.resolve(version);

String suffix = source .getFileName()
Expand Down
7 changes: 0 additions & 7 deletions src/main/java/dev/jbang/dependencies/DependencyUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,6 @@ public static String removeLastCharOptional(String s) {
.orElse(s);
}

public static String gavWithVersion(String gav) {
if (gav.replaceAll("[^:]", "").length() == 1) {
gav += ":999-SNAPSHOT";
}
return gav;
}

public static MavenRepo toMavenRepo(String repoReference) {
String[] split = repoReference.split("=");
String reporef = null;
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/dev/jbang/dependencies/MavenCoordinate.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public class MavenCoordinate {
private final String classifier;
private final String packaging;

public static final String DUMMY_GROUP = "group";
public static final String DEFAULT_VERSION = "999-SNAPSHOT";

private static final Pattern gavPattern = Pattern.compile(
"^(?<groupid>[^:]*):(?<artifactid>[^:]*)(:(?<version>[^:@]*))?(:(?<classifier>[^@]*))?(@(?<type>.*))?$");

Expand Down Expand Up @@ -80,6 +83,11 @@ public MavenCoordinate(@Nonnull String groupId, @Nonnull String artifactId, @Non
this.packaging = packaging;
}

public MavenCoordinate withVersion() {
return version != null ? this
: new MavenCoordinate(groupId, artifactId, DEFAULT_VERSION, classifier, packaging);
}

/**
* Turns a Maven artifact coordinate into a string. This returns the same format
* that can be parsed by the <code>MavenCoordinate.fromString()</code> method.
Expand Down
1 change: 1 addition & 0 deletions src/main/java/dev/jbang/source/Code.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ default Optional<String> getDescription() {
* Returns the resource's Maven GAV. Returns `Optional.empty()` if no GAV is
* available.
*/
@Nonnull
default Optional<String> getGav() {
return Optional.empty();
}
Expand Down
46 changes: 46 additions & 0 deletions src/main/java/dev/jbang/source/Jar.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
package dev.jbang.source;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javax.annotation.Nonnull;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import dev.jbang.dependencies.DependencyResolver;
import dev.jbang.dependencies.DependencyUtil;
import dev.jbang.dependencies.MavenCoordinate;
import dev.jbang.source.builders.BaseBuilder;
import dev.jbang.source.generators.JarCmdGenerator;
import dev.jbang.util.JavaUtil;
Expand All @@ -35,6 +45,7 @@ public class Jar implements Code {
private String classPath;
private String mainClass;
private List<String> javaRuntimeOptions;
private String gav;
private int buildJdk;

// Cached values
Expand All @@ -49,6 +60,25 @@ private Jar(ResourceRef resourceRef, Path jar) {
Attributes attrs = jf.getManifest().getMainAttributes();
mainClass = attrs.getValue(Attributes.Name.MAIN_CLASS);

Optional<JarEntry> pom = jf.stream().filter(e -> e.getName().endsWith("/pom.xml")).findFirst();
if (pom.isPresent()) {
try (InputStream is = jf.getInputStream(pom.get())) {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model model = reader.read(is);
// GAVS of the form "group:xxxx:999-SNAPSHOT" are skipped
if (!MavenCoordinate.DUMMY_GROUP.equals(model.getGroupId())
|| !MavenCoordinate.DEFAULT_VERSION.equals(model.getVersion())) {
gav = model.getGroupId() + ":" + model.getArtifactId();
// The version "999-SNAPSHOT" is ignored
if (!MavenCoordinate.DEFAULT_VERSION.equals(model.getVersion())) {
gav += ":" + model.getVersion();
}
}
} catch (XmlPullParserException e) {
Util.verboseMsg("Unable to read the JAR's pom.xml file", e);
}
}

String val = attrs.getValue(BaseBuilder.ATTR_JBANG_JAVA_OPTIONS);
if (val != null) {
javaRuntimeOptions = Code.quotedStringToList(val);
Expand Down Expand Up @@ -126,6 +156,12 @@ public String getJavaVersion() {
return buildJdk > 0 ? buildJdk + "+" : null;
}

@Nonnull
@Override
public Optional<String> getGav() {
return Optional.ofNullable(gav);
}

/**
* Returns the actual Java version that was used to build this Jar. Will return
* 0 if the information is not available (for example because the Jar hasn't
Expand All @@ -142,16 +178,19 @@ public String getMainClass() {
return mainClass;
}

@Nonnull
@Override
public List<String> getRuntimeOptions() {
return javaRuntimeOptions;
}

@Nonnull
@Override
public Builder builder() {
return () -> this;
}

@Nonnull
@Override
public CmdGenerator cmdGenerator(RunContext ctx) {
return new JarCmdGenerator(this, ctx);
Expand All @@ -168,6 +207,13 @@ public static Jar prepareJar(ResourceRef resourceRef, Path jarFile) {
public static Jar prepareJar(Project prj) {
Jar jsrc = new Jar(prj.getResourceRef(), prj.getJarFile());
jsrc.project = prj;
if (!Files.exists(prj.getJarFile())) {
jsrc.classPath = prj.resolveClassPath().getManifestPath();
jsrc.mainClass = prj.getMainClass();
jsrc.javaRuntimeOptions = prj.getRuntimeOptions();
jsrc.gav = prj.getGav().orElse(null);
jsrc.buildJdk = JavaUtil.javaVersion(prj.getJavaVersion());
}
return jsrc;
}
}
1 change: 1 addition & 0 deletions src/main/java/dev/jbang/source/Project.java
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ public Project setDescription(String description) {
}

@Nonnull
@Override
public Optional<String> getGav() {
return Optional.ofNullable(gav);
}
Expand Down
10 changes: 9 additions & 1 deletion src/main/java/dev/jbang/source/Source.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import dev.jbang.cli.ExitException;
import dev.jbang.cli.ResourceNotFoundException;
import dev.jbang.dependencies.DependencyUtil;
import dev.jbang.dependencies.MavenCoordinate;
import dev.jbang.dependencies.MavenRepo;
import dev.jbang.source.resolvers.SiblingResourceResolver;
import dev.jbang.source.sources.*;
Expand Down Expand Up @@ -296,7 +297,7 @@ public Optional<String> getGav() {
Util.warnMsg(
"Multiple //GAV lines found, only one should be defined in a source file. Using the first");
}
String maybeGav = DependencyUtil.gavWithVersion(gavs.get(0));
String maybeGav = gavWithVersion(gavs.get(0));
if (!DependencyUtil.looksLikeAGav(maybeGav)) {
throw new IllegalArgumentException(
"//GAV line has wrong format, should be '//GAV groupid:artifactid[:version]'");
Expand All @@ -305,6 +306,13 @@ public Optional<String> getGav() {
}
}

private static String gavWithVersion(String gav) {
if (gav.replaceAll("[^:]", "").length() == 1) {
gav += ":" + MavenCoordinate.DEFAULT_VERSION;
}
return gav;
}

static boolean isGavDeclare(String line) {
return line.startsWith(GAV_COMMENT_PREFIX);
}
Expand Down
8 changes: 3 additions & 5 deletions src/main/java/dev/jbang/source/builders/BaseBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import org.jboss.jandex.*;

import dev.jbang.cli.ExitException;
import dev.jbang.dependencies.DependencyUtil;
import dev.jbang.dependencies.MavenCoordinate;
import dev.jbang.source.*;
import dev.jbang.spi.IntegrationManager;
Expand Down Expand Up @@ -418,12 +417,11 @@ protected Path generatePom(Path tmpJarDir) throws IOException {
Util.warnMsg("Could not locate pom.xml template");
} else {
String baseName = Util.getBaseName(prj.getResourceRef().getFile().getFileName().toString());
String group = "group";
String group = MavenCoordinate.DUMMY_GROUP;
String artifact = baseName;
String version = "999-SNAPSHOT";
String version = MavenCoordinate.DEFAULT_VERSION;
if (prj.getGav().isPresent()) {
MavenCoordinate coord = MavenCoordinate.fromString(
DependencyUtil.gavWithVersion(prj.getGav().get()));
MavenCoordinate coord = MavenCoordinate.fromString(prj.getGav().get()).withVersion();
group = coord.getGroupId();
artifact = coord.getArtifactId();
version = coord.getVersion();
Expand Down
28 changes: 21 additions & 7 deletions src/test/java/dev/jbang/cli/TestExport.java
Original file line number Diff line number Diff line change
Expand Up @@ -136,23 +136,21 @@ void testExportMavenPublishNoOutputdir() throws IOException {

}

// @Test
@Test
void testExportMavenPublishNoGroup() throws IOException {
File outFile = jbangTempDir.resolve("target").toFile();
outFile.mkdirs();
ExecutionResult result = checkedRun(null, "export", "mavenrepo", "--force", "-O", outFile.toString(),
"itests/helloworld.java");
ExecutionResult result = checkedRun(null, "export", "mavenrepo", "--force", "-O",
outFile.toString(), examplesTestFolder.resolve("helloworld.java").toString());
assertThat(result.exitCode, equalTo(BaseCommand.EXIT_INVALID_INPUT));
assertThat(result.err, matchesPattern("(?s).*-Dgroup=.*"));

assertThat(result.err, containsString("Add --group=<group id> and run again"));
}

@Test
void testExportMavenPublishWithClasspath() throws IOException {
Path outFile = Settings.getLocalMavenRepo();
ExecutionResult result = checkedRun(null, "export", "mavenrepo", "--force",
"--group=g.a.v",
examplesTestFolder.resolve("classpath_log.java").toString());
"--group=g.a.v", examplesTestFolder.resolve("classpath_log.java").toString());
assertThat(result.exitCode, equalTo(BaseCommand.EXIT_OK));
assertThat(outFile.resolve("g/a/v/classpath_log/999-SNAPSHOT/classpath_log-999-SNAPSHOT.jar").toFile(),
anExistingFile());
Expand All @@ -166,6 +164,22 @@ void testExportMavenPublishWithClasspath() throws IOException {

}

@Test
void testExportMavenPublishWithGAV() throws IOException {
File outFile = jbangTempDir.resolve("target").toFile();
outFile.mkdirs();
ExecutionResult result = checkedRun(null, "export", "mavenrepo", "-O", outFile.toString(),
examplesTestFolder.resolve("quote.java").toString());
assertThat(result.err, matchesPattern("(?s).*Exported to.*target.*"));
assertThat(
outFile.toPath().resolve("dev/jbang/itests/quote/999-SNAPSHOT/quote-999-SNAPSHOT.jar").toFile(),
anExistingFile());
assertThat(
outFile.toPath().resolve("dev/jbang/itests/quote/999-SNAPSHOT/quote-999-SNAPSHOT.pom").toFile(),
anExistingFile());

}

@Test
void testExportMissingScript() {
assertThrows(IllegalArgumentException.class, () -> {
Expand Down

0 comments on commit 4d6ab0e

Please sign in to comment.