package hudson.plugins.git;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;

import hudson.EnvVars;
import hudson.model.TaskListener;
import hudson.tools.AbstractCommandInstaller;
import hudson.tools.BatchCommandInstaller;
import hudson.tools.CommandInstaller;
import hudson.tools.InstallSourceProperty;
import java.io.File;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.junit.jupiter.WithJenkins;

@WithJenkins
class GitToolResolverTest {

    private JenkinsRule r;

    private GitTool gitTool;

    @BeforeEach
    void setUp(JenkinsRule rule) {
        r = rule;
        GitTool.onLoaded();
        gitTool = GitTool.getDefaultInstallation();
    }

    @Test
    void shouldResolveToolsOnMaster() throws Exception {
        // Jenkins 2.307+ uses "built-in" for the label on the controller node
        // Before 2.307, used the deprecated term "master"
        final String label = r.jenkins.getSelfLabel().getName();
        final String command = "echo Hello";
        final String toolHome = "TOOL_HOME";
        AbstractCommandInstaller installer = isWindows()
                ? new BatchCommandInstaller(label, command, toolHome)
                : new CommandInstaller(label, command, toolHome);
        GitTool t = new GitTool(
                "myGit",
                null,
                Collections.singletonList(new InstallSourceProperty(Collections.singletonList(installer))));
        t.getDescriptor().setInstallations(t);

        GitTool defaultTool = GitTool.getDefaultInstallation();
        GitTool resolved = (GitTool) defaultTool.translate(r.jenkins, new EnvVars(), TaskListener.NULL);
        assertThat(resolved.getGitExe(), containsString(toolHome));
    }

    private boolean isWindows() {
        return File.pathSeparatorChar == ';';
    }
}
