Skip to content

Commit

Permalink
refactor: drop classifierWithLikes in plugin param (#15)
Browse files Browse the repository at this point in the history
Signed-off-by: tison <wander4096@gmail.com>
  • Loading branch information
tisonkun authored Oct 23, 2024
1 parent c03d1d7 commit c9283e0
Show file tree
Hide file tree
Showing 8 changed files with 27 additions and 143 deletions.
40 changes: 10 additions & 30 deletions lib/src/main/java/com/tisonkun/os/core/Detector.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Detector {
public static final String DETECTED_NAME = "os.detected.name";
Expand Down Expand Up @@ -71,47 +72,25 @@ public Detector(
}

public Detected detect() {
return detect(Collections.emptyList());
}

public Detected detect(List<String> classifierWithLikes) {
final String osName = systemPropertyOperationProvider.getSystemProperty("os.name");
final String osArch = systemPropertyOperationProvider.getSystemProperty("os.arch");
final String osVersion = systemPropertyOperationProvider.getSystemProperty("os.version");

final OS detectedName = normalizeOs(osName);
final Arch detectedArch = normalizeArch(osArch);
final int detectedBitness = determineBitness(detectedArch.name());

// Assume the default classifier, without any os "like" extension.
final StringBuilder detectedClassifierBuilder = new StringBuilder();
detectedClassifierBuilder.append(detectedName);
detectedClassifierBuilder.append('-');
detectedClassifierBuilder.append(detectedArch);

// For Linux systems, add additional properties regarding details of the OS.
final String detectedClassifier = String.valueOf(detectedName) + '-' + detectedArch;
final LinuxRelease linuxRelease = OS.linux != detectedName ? null : getLinuxRelease();
if (linuxRelease != null) {
for (String classifierLike : classifierWithLikes) {
if (linuxRelease.like.contains(classifierLike)) {
detectedClassifierBuilder.append('-');
detectedClassifierBuilder.append(classifierLike);
// First one wins.
break;
}
}
}

final String detectedClassifier = detectedClassifierBuilder.toString();
return new Detected(detectedBitness, osVersion, detectedClassifier, detectedName, detectedArch, linuxRelease);
}

public void detect(Properties props, List<String> classifierWithLikes) {
public void detect(Properties props) {
loggingProvider.info("------------------------------------------------------------------------");
loggingProvider.info("Detecting the operating system and CPU architecture");
loggingProvider.info("------------------------------------------------------------------------");

final Detected detected = detect(classifierWithLikes);
final Detected detected = detect();

setProperty(props, DETECTED_NAME, detected.os.name());
setProperty(props, DETECTED_ARCH, detected.arch.name());
Expand Down Expand Up @@ -145,7 +124,7 @@ public void detect(Properties props, List<String> classifierWithLikes) {
}

// Add properties for all systems that this OS is "like".
for (String like : linuxRelease.like) {
for (String like : linuxRelease.likes) {
final String propKey = DETECTED_RELEASE_LIKE_PREFIX + like;
setProperty(props, propKey, "true");
}
Expand Down Expand Up @@ -360,7 +339,8 @@ private LinuxRelease parseLinuxOsReleaseFile(String fileName) {
}

if (id != null) {
return new LinuxRelease(id, version, likeSet);
final List<String> likes = likeSet.stream().sorted().collect(Collectors.toList());
return new LinuxRelease(id, version, likes);
}
} catch (IOException ignored) {
// Just absorb. Don't treat failure to read /etc/os-release as an error.
Expand Down Expand Up @@ -404,10 +384,10 @@ private LinuxRelease parseLinuxRedhatReleaseFile() {
version = versionMatcher.group(1);
}

final Set<String> likeSet = new LinkedHashSet<String>(Arrays.asList(DEFAULT_REDHAT_VARIANTS));
final Set<String> likeSet = new LinkedHashSet<>(Arrays.asList(DEFAULT_REDHAT_VARIANTS));
likeSet.add(id);

return new LinuxRelease(id, version, likeSet);
final List<String> likes = likeSet.stream().sorted().collect(Collectors.toList());
return new LinuxRelease(id, version, likes);
}
} catch (IOException ignored) {
// Just absorb. Don't treat failure to read /etc/os-release as an error.
Expand Down
4 changes: 2 additions & 2 deletions lib/src/main/java/com/tisonkun/os/core/LinuxRelease.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.tisonkun.os.core;

import java.util.Collection;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.ToString;
Expand All @@ -27,5 +27,5 @@
public class LinuxRelease {
public final String id;
public final String version;
public final Collection<String> like;
public final List<String> likes;
}
3 changes: 1 addition & 2 deletions lib/src/test/java/com/tisonkun/os/core/DetectorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package com.tisonkun.os.core;

import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.Properties;
import org.junit.jupiter.api.Test;

Expand All @@ -26,7 +25,7 @@ class DetectorTest {
void testDetectProperties() {
final Properties properties = new Properties();
final Detector detector = new Detector(System.out::println);
detector.detect(properties, Collections.emptyList());
detector.detect(properties);
assertThat(properties)
.containsKeys(
"os.detected.name",
Expand Down
34 changes: 10 additions & 24 deletions plugin-gradle/src/main/java/com/tisonkun/os/gradle/OSDetector.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -46,8 +44,6 @@ public abstract class OSDetector {
@Inject
public abstract ProjectLayout getProjectLayout();

private final List<String> classifierWithLikes = new ArrayList<>();

@SuppressWarnings("FieldCanBeLocal")
private final Project project;

Expand Down Expand Up @@ -78,24 +74,13 @@ public Release getRelease() {
return new Release(impl);
}

public synchronized void setClassifierWithLikes(List<String> classifierWithLikes) {
if (impl != null) {
throw new IllegalStateException("classifierWithLikes must be set before osdetector is read.");
}
this.classifierWithLikes.clear();
this.classifierWithLikes.addAll(classifierWithLikes);
}

private synchronized Impl getImpl() {
if (impl == null) {
if (GradleVersion.current().compareTo(GradleVersion.version("6.5")) >= 0) {
impl = new Impl(
classifierWithLikes,
new ConfigurationTimeSafeSystemPropertyOperations(),
new ConfigurationTimeSafeFileOperations());
new ConfigurationTimeSafeSystemPropertyOperations(), new ConfigurationTimeSafeFileOperations());
} else {
impl = new Impl(
classifierWithLikes, new DefaultSystemPropertyOperations(), new DefaultFileOperations());
impl = new Impl(new DefaultSystemPropertyOperations(), new DefaultFileOperations());
}
}
return impl;
Expand Down Expand Up @@ -137,12 +122,9 @@ public boolean isLike(String baseRelease) {
private static class Impl {
private final Properties detectedProperties = new Properties();

private Impl(
List<String> classifierWithLikes,
SystemPropertyOperationProvider sysPropOps,
FileOperationProvider fsOps) {
private Impl(SystemPropertyOperationProvider sysPropOps, FileOperationProvider fsOps) {
final Detector detector = new Detector(sysPropOps, fsOps, log::info);
detector.detect(detectedProperties, classifierWithLikes);
detector.detect(detectedProperties);
}
}

Expand All @@ -156,7 +138,9 @@ private static <T> Provider<T> forUseAtConfigurationTime(Provider<T> provider) {
}
}

/** Provides system property operations compatible with Gradle configuration cache. */
/**
* Provides system property operations compatible with Gradle configuration cache.
*/
private final class ConfigurationTimeSafeSystemPropertyOperations implements SystemPropertyOperationProvider {
@Override
public String getSystemProperty(String name) {
Expand All @@ -177,7 +161,9 @@ public String setSystemProperty(String name, String value) {
}
}

/** Provides filesystem operations compatible with Gradle configuration cache. */
/**
* Provides filesystem operations compatible with Gradle configuration cache.
*/
private final class ConfigurationTimeSafeFileOperations implements FileOperationProvider {
@Override
public InputStream readFile(String fileName) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,6 @@
package com.tisonkun.os.gradle;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.Collections;
import org.gradle.api.Project;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -48,24 +45,4 @@ void pluginAddsExtensionToProject() {
assertThat(detector.getRelease()).isNull();
}
}

@Test
void setClassifierWithLikes() {
final Project project = ProjectBuilder.builder().build();
project.apply(action -> action.plugin("com.tisonkun.osdetector"));

final OSDetector detector = (OSDetector) project.getExtensions().getByName("osdetector");
detector.setClassifierWithLikes(new ArrayList<String>() {
{
add("debian");
add("fedora");
}
});
assertThat(detector.getOs()).isNotNull();
assertThat(detector.getArch()).isNotNull();
System.err.println("classifier=" + detector.getClassifier());

assertThatThrownBy(() -> detector.setClassifierWithLikes(Collections.singletonList("debian")))
.isExactlyInstanceOf(IllegalStateException.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.io.StringReader;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
Expand Down Expand Up @@ -131,7 +130,7 @@ private Map<String, String> getProperties(MavenSession session) throws MavenExec
sessionProps.putAll(session.getSystemProperties());
sessionProps.putAll(session.getUserProperties());
try {
detector.detect(sessionProps, getClassifierWithLikes(session));
detector.detect(sessionProps);
} catch (DetectionException e) {
throw new MavenExecutionException(
e.getMessage(), session.getCurrentProject().getFile());
Expand All @@ -152,22 +151,6 @@ private Map<String, String> getProperties(MavenSession session) throws MavenExec
return dict;
}

/**
* Inspects the session's user and project properties for the {@link
* DetectMojo#CLASSIFIER_WITH_LIKES_PROPERTY} and separates the property into a list.
*/
private static List<String> getClassifierWithLikes(MavenSession session) {
// Check to see if the project defined the
final Properties props = new Properties();
props.putAll(session.getUserProperties());

if (session.getCurrentProject() != null) {
props.putAll(session.getCurrentProject().getProperties());
}

return DetectMojo.getClassifierWithLikes(props.getProperty(DetectMojo.CLASSIFIER_WITH_LIKES_PROPERTY));
}

private void injectSession(MavenSession session, Map<String, String> dict) {
final Properties sessionExecProps = session.getSystemProperties();
sessionExecProps.setProperty(Detector.DETECTED_NAME, String.valueOf(dict.get(Detector.DETECTED_NAME)));
Expand All @@ -182,7 +165,7 @@ private void injectSession(MavenSession session, Map<String, String> dict) {

// Work around the 'NoClassDefFoundError' or 'ClassNotFoundException' related with Aether in IntelliJ IDEA.
for (StackTraceElement e : new Exception().getStackTrace()) {
if (String.valueOf(e.getClassName()).startsWith("org.jetbrains.idea.maven")) {
if (e.getClassName().startsWith("org.jetbrains.idea.maven")) {
return;
}
}
Expand Down
33 changes: 1 addition & 32 deletions plugin-maven/src/main/java/com/tisonkun/os/maven/DetectMojo.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,6 @@
import com.tisonkun.os.core.DefaultSystemPropertyOperations;
import com.tisonkun.os.core.DetectionException;
import com.tisonkun.os.core.Detector;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
Expand Down Expand Up @@ -54,14 +51,9 @@
*/
@Mojo(name = "detect", defaultPhase = LifecyclePhase.VALIDATE, threadSafe = true)
public class DetectMojo extends AbstractMojo {
static final String CLASSIFIER_WITH_LIKES_PROPERTY = "os.detection.classifierWithLikes";

@Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;

@Parameter(property = CLASSIFIER_WITH_LIKES_PROPERTY, defaultValue = "${" + CLASSIFIER_WITH_LIKES_PROPERTY + '}')
private String classifierWithLikes;

private final Detector detector = new Detector(
new DefaultSystemPropertyOperations(), new DefaultFileOperations(), message -> getLog().info(message));

Expand All @@ -73,32 +65,9 @@ public DetectMojo() {}
@Override
public void execute() throws MojoExecutionException {
try {
detector.detect(project.getProperties(), getClassifierWithLikes(classifierWithLikes));
detector.detect(project.getProperties());
} catch (DetectionException e) {
throw new MojoExecutionException(e.getMessage());
}
}

/**
* Takes a comma-separated value of os "likes" to be included in the generated classifier and
* returns them as a list.
*
* @param propertyValue the value of the {@link #CLASSIFIER_WITH_LIKES_PROPERTY} property.
* @return the value as a list of entries.
*/
public static List<String> getClassifierWithLikes(String propertyValue) {
if (propertyValue == null) {
return Collections.emptyList();
}

final String[] parts = propertyValue.split(",");
final List<String> likes = new ArrayList<>(parts.length);
for (String part : parts) {
part = part.trim();
if (!part.isEmpty()) {
likes.add(part);
}
}
return likes;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.inject.Inject;
Expand Down Expand Up @@ -56,16 +55,7 @@ public void contribute(Map<String, String> map) {

final Detector detector =
new Detector(new SimpleSystemPropertyOperations(map), new SimpleFileOperations(), logger::debug);
detector.detect(props, getClassifierWithLikes(map));
}

/**
* Inspects the session's user and project properties for the {@link
* DetectMojo#CLASSIFIER_WITH_LIKES_PROPERTY} and separates the property into a list.
*/
private static List<String> getClassifierWithLikes(Map<String, String> map) {
// Check to see if the project defined the
return DetectMojo.getClassifierWithLikes(map.get(DetectMojo.CLASSIFIER_WITH_LIKES_PROPERTY));
detector.detect(props);
}

private static class SimpleSystemPropertyOperations implements SystemPropertyOperationProvider {
Expand Down

0 comments on commit c9283e0

Please sign in to comment.