package jdk.incubator.jpackage.internal;
import java.io.*;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static jdk.incubator.jpackage.internal.StandardBundlerParam.*;
import static jdk.incubator.jpackage.internal.OverridableResource.createResource;
public class LinuxRpmBundler extends LinuxPackageBundler {
private static final Pattern RPM_PACKAGE_NAME_PATTERN =
Pattern.compile("[a-z\\d\\+\\-\\.\\_]+", Pattern.CASE_INSENSITIVE);
public static final BundlerParamInfo<String> PACKAGE_NAME =
new StandardBundlerParam<> (
Arguments.CLIOptions.LINUX_BUNDLE_NAME.getId(),
String.class,
params -> {
String nm = APP_NAME.fetchFrom(params);
if (nm == null) return null;
nm = nm.toLowerCase().replaceAll("[ ]", "-");
return nm;
},
(s, p) -> {
if (!RPM_PACKAGE_NAME_PATTERN.matcher(s).matches()) {
String msgKey = "error.invalid-value-for-package-name";
throw new IllegalArgumentException(
new ConfigException(MessageFormat.format(
I18N.getString(msgKey), s),
I18N.getString(msgKey + ".advice")));
}
return s;
}
);
public static final BundlerParamInfo<String> LICENSE_TYPE =
new StandardBundlerParam<>(
Arguments.CLIOptions.LINUX_RPM_LICENSE_TYPE.getId(),
String.class,
params -> I18N.getString("param.license-type.default"),
(s, p) -> s
);
public static final BundlerParamInfo<String> GROUP =
new StandardBundlerParam<>(
Arguments.CLIOptions.LINUX_CATEGORY.getId(),
String.class,
params -> null,
(s, p) -> s);
private final static String DEFAULT_SPEC_TEMPLATE = "template.spec";
public final static String TOOL_RPM = "rpm";
public final static String TOOL_RPMBUILD = "rpmbuild";
public final static DottedVersion TOOL_RPMBUILD_MIN_VERSION = DottedVersion.lazy(
"4.10");
public LinuxRpmBundler() {
super(PACKAGE_NAME);
}
@Override
public void doValidate(Map<String, ? super Object> params)
throws ConfigException {
}
private static ToolValidator createRpmbuildToolValidator() {
Pattern pattern = Pattern.compile(" (\\d+\\.\\d+)");
return new ToolValidator(TOOL_RPMBUILD).setMinimalVersion(
TOOL_RPMBUILD_MIN_VERSION).setVersionParser(lines -> {
String versionString = lines.limit(1).collect(
Collectors.toList()).get(0);
Matcher matcher = pattern.matcher(versionString);
if (matcher.find()) {
return matcher.group(1);
}
return null;
});
}
@Override
protected List<ToolValidator> getToolValidators(
Map<String, ? super Object> params) {
return List.of(createRpmbuildToolValidator());
}
@Override
protected File buildPackageBundle(
Map<String, String> replacementData,
Map<String, ? super Object> params, File outputParentDir) throws
PackagerException, IOException {
Path specFile = specFile(params);
createResource(DEFAULT_SPEC_TEMPLATE, params)
.setCategory(I18N.getString("resource.rpm-spec-file"))
.setSubstitutionData(replacementData)
.saveToFile(specFile);
return buildRPM(params, outputParentDir.toPath()).toFile();
}
@Override
protected Map<String, String> createReplacementData(
Map<String, ? super Object> params) throws IOException {
Map<String, String> data = new HashMap<>();
final Path prefix = Path.of(LINUX_INSTALL_DIR.fetchFrom(params));
Path appDirectory = prefix;
if (!isInstallDirInUsrTree(prefix.toString())) {
appDirectory = appDirectory.resolve(PACKAGE_NAME.fetchFrom(params));
}
data.put("APPLICATION_PREFIX", prefix.toString());
data.put("APPLICATION_DIRECTORY", appDirectory.toString());
data.put("APPLICATION_SUMMARY", APP_NAME.fetchFrom(params));
data.put("APPLICATION_LICENSE_TYPE", LICENSE_TYPE.fetchFrom(params));
String licenseFile = LICENSE_FILE.fetchFrom(params);
if (licenseFile != null) {
licenseFile = Path.of(licenseFile).toAbsolutePath().normalize().toString();
}
data.put("APPLICATION_LICENSE_FILE", licenseFile);
data.put("APPLICATION_GROUP", GROUP.fetchFrom(params));
return data;
}
@Override
protected void initLibProvidersLookup(
Map<String, ? super Object> params,
LibProvidersLookup libProvidersLookup) {
libProvidersLookup.setPackageLookup(file -> {
return Executor.of(TOOL_RPM,
"-q", "--queryformat", "%{name}\\n",
"-q", "--whatprovides", file.toString())
.saveOutput(true).executeExpectSuccess().getOutput().stream();
});
}
@Override
protected List<ConfigException> verifyOutputBundle(
Map<String, ? super Object> params, Path packageBundle) {
List<ConfigException> errors = new ArrayList<>();
String specFileName = specFile(params).getFileName().toString();
try {
List<PackageProperty> properties = List.of(
new PackageProperty("Name", PACKAGE_NAME.fetchFrom(params),
"APPLICATION_PACKAGE", specFileName),
new PackageProperty("Version", VERSION.fetchFrom(params),
"APPLICATION_VERSION", specFileName),
new PackageProperty("Release", RELEASE.fetchFrom(params),
"APPLICATION_RELEASE", specFileName),
new PackageProperty("Arch", rpmArch(), null, specFileName));
List<String> actualValues = Executor.of(TOOL_RPM, "-qp", "--queryformat",
properties.stream().map(entry -> String.format("%%{%s}",
entry.name)).collect(Collectors.joining("\\n")),
packageBundle.toString()).saveOutput(true).executeExpectSuccess().getOutput();
Iterator<String> actualValuesIt = actualValues.iterator();
properties.forEach(property -> errors.add(property.verifyValue(
actualValuesIt.next())));
} catch (IOException ex) {
Log.verbose(ex);
}
return errors;
}
private enum RpmArchReader {
Rpmbuild(TOOL_RPMBUILD, "--eval=%{_target_cpu}"),
Rpm(TOOL_RPM, "--eval=%{_target_cpu}");
RpmArchReader(String... cmdline) {
this.cmdline = cmdline;
}
String getRpmArch() throws IOException {
Executor exec = Executor.of(cmdline).saveOutput(true);
if (this == values()[values().length - 1]) {
exec.executeExpectSuccess();
} else if (exec.execute() != 0) {
return null;
}
return exec.getOutput().get(0);
}
private final String[] cmdline;
}
private String rpmArch() throws IOException {
if (rpmArch == null) {
for (var rpmArchReader : RpmArchReader.values()) {
rpmArch = rpmArchReader.getRpmArch();
if (rpmArch != null) {
break;
}
}
}
return rpmArch;
}
private Path specFile(Map<String, ? super Object> params) {
return TEMP_ROOT.fetchFrom(params).toPath().resolve(Path.of("SPECS",
PACKAGE_NAME.fetchFrom(params) + ".spec"));
}
private Path buildRPM(Map<String, ? super Object> params,
Path outdir) throws IOException {
Path rpmFile = outdir.toAbsolutePath().resolve(String.format(
"%s-%s-%s.%s.rpm", PACKAGE_NAME.fetchFrom(params),
VERSION.fetchFrom(params), RELEASE.fetchFrom(params), rpmArch()));
Log.verbose(MessageFormat.format(I18N.getString(
"message.outputting-bundle-location"),
rpmFile.getParent()));
PlatformPackage thePackage = createMetaPackage(params);
Executor.of(
TOOL_RPMBUILD,
"-bb", specFile(params).toAbsolutePath().toString(),
"--define", String.format("%%_sourcedir %s",
thePackage.sourceRoot()),
"--define", String.format("%%_rpmdir %s", rpmFile.getParent()),
"--define", String.format("%%_topdir %s",
TEMP_ROOT.fetchFrom(params).toPath().toAbsolutePath()),
"--define", String.format("%%_rpmfilename %s", rpmFile.getFileName())
).executeExpectSuccess();
Log.verbose(MessageFormat.format(
I18N.getString("message.output-bundle-location"),
rpmFile.getParent()));
return rpmFile;
}
@Override
public String getName() {
return I18N.getString("rpm.bundler.name");
}
@Override
public String getID() {
return "rpm";
}
@Override
public boolean supported(boolean runtimeInstaller) {
return Platform.isLinux() && (createRpmbuildToolValidator().validate() == null);
}
@Override
public boolean isDefault() {
return !LinuxDebBundler.isDebian();
}
private String rpmArch;
}