001package org.clafer.frontend;
002
003import java.net.URISyntaxException;
004import java.nio.file.Files;
005import java.nio.file.Path;
006import java.security.CodeSource;
007import java.util.Optional;
008
009/**
010 * The Clafer compiler, the Haskell {@code clafer}, that the Java tools run for what they do not do
011 * themselves ({@code clafersg} for a model with a {@code [choco| |]} escape or with
012 * {@code --haskell-frontend}, {@code claferc} for the modes it forwards):
013 * <ul>
014 * <li>{@code -Dclafer.executable}, if it is set;</li>
015 * <li>otherwise {@code clafer} next to the jar of this class, as in Clafer Tools, where both
016 * bundles unpack into one folder with {@code clafersg.jar}, {@code claferc.jar} and
017 * {@code clafer}, so that the folder need not be on the {@code PATH};</li>
018 * <li>otherwise {@code clafer} on the {@code PATH}.</li>
019 * </ul>
020 */
021public final class ClaferExecutable {
022
023    private ClaferExecutable() {
024    }
025
026    /**
027     * The command that runs the Clafer compiler.
028     */
029    public static String find() {
030        String property = System.getProperty("clafer.executable");
031        if (property != null && !property.isEmpty()) {
032            return property;
033        }
034        return jar().flatMap(ClaferExecutable::nextTo).map(Path::toString).orElse("clafer");
035    }
036
037    /**
038     * The executable {@code clafer} ({@code clafer.exe} on Windows) in the folder of a jar, if
039     * there is one.
040     */
041    static Optional<Path> nextTo(Path jar) {
042        if (!Files.isRegularFile(jar) || jar.getParent() == null) {
043            return Optional.empty();
044        }
045        String name = System.getProperty("os.name", "").startsWith("Windows") ? "clafer.exe" : "clafer";
046        Path clafer = jar.getParent().resolve(name);
047        return Files.isRegularFile(clafer) && Files.isExecutable(clafer) ? Optional.of(clafer) : Optional.empty();
048    }
049
050    /**
051     * The jar that this class was loaded from; none when it was loaded from a folder of classes,
052     * as in the tests.
053     */
054    private static Optional<Path> jar() {
055        try {
056            CodeSource source = ClaferExecutable.class.getProtectionDomain().getCodeSource();
057            return source == null || source.getLocation() == null
058                    ? Optional.empty() : Optional.of(Path.of(source.getLocation().toURI()));
059        } catch (URISyntaxException | RuntimeException e) {
060            return Optional.empty();
061        }
062    }
063}