Or you can define osName
as a string...
import org.gradle.internal.os.OperatingSystem
switch (OperatingSystem.current()) {
case OperatingSystem.LINUX:
project.ext.osName = "Linux";
break;
case OperatingSystem.MAC_OS:
project.ext.osName = "macOS";
break;
case OperatingSystem.WINDOWS:
project.ext.osName = "Windows";
break;
}
... and use it later - to include a native library for example:
run {
systemProperty "java.library.path", "lib/$osName"
}
But it wouldn't change anything since OperatingSystem works exactly like your code:
public static OperatingSystem forName(String os) {
String osName = os.toLowerCase();
if (osName.contains("Windows")) {
return WINDOWS;
} else if (osName.contains("mac os x") || osName.contains("darwin") || osName.contains("osx")) {
return MAC_OS;
} else if (osName.contains("sunos") || osName.contains("solaris")) {
return SOLARIS;
} else if (osName.contains("linux")) {
return LINUX;
} else if (osName.contains("freebsd")) {
return FREE_BSD;
} else {
// Not strictly true
return UNIX;
}
}
Source: https://github.com/gradle/gradle/blob/master/subprojects/base-services/src/main/java/org/gradle/internal/os/OperatingSystem.java
Edit:
You can do the same for the architecture:
project.ext.osArch = OperatingSystem.current().getArch();
if ("x86".equals(project.ext.osArch)) {
project.ext.osArch = "i386";
}
and:
run {
systemProperty "java.library.path", "lib/$osName/$osArch"
}
Just be aware that getArch()
will return:
- "ppc" on PowerPC
- "amd64" on 64b
- "i386" OR "x86" on 32b.
getArch()
will return "x86" on Solaris or "i386" for any other platform.
Edit 2:
Or if you want to avoid any import, you can simply do it yourself:
def getOsName(project) {
final String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("linux")) {
return ("linux");
} else if (osName.contains("mac os x") || osName.contains("darwin") || osName.contains("osx")) {
return ("macos");
} else if (osName.contains("windows")) {
return ("windows");
} else if (osName.contains("sunos") || osName.contains("solaris")) {
return ("solaris");
} else if (osName.contains("freebsd")) {
return ("freebsd");
}
return ("unix");
}
def getOsArch(project) {
final String osArch = System.getProperty("os.arch");
if ("x86".equals(osArch)) {
return ("i386");
}
else if ("x86_64".equals(osArch)) {
return ("amd64");
}
else if ("powerpc".equals(osArch)) {
return ("ppc");
}
return (osArch);
}
toLowerCase().contains()
part, as I just need the name.System.getProperty('os.arch')
"WINDOWS".toLowerCase()
is locale dependent and will returnwındows
(note the dotless i) on machines where the locale is Turkish. UsetoLowerCase(Locale.ROOT)
instead to be on the safe side.