package com.atlassian.stash.internal.scm.git.version;

import com.atlassian.bitbucket.io.EolDetectingLineOutputHandler;
import com.atlassian.bitbucket.util.Version;
import com.atlassian.bitbucket.scm.CommandOutputHandler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A {@link CommandOutputHandler} which parses {@code git version} output to produce a {@link Version}.
 */
public class VersionOutputHandler extends EolDetectingLineOutputHandler implements CommandOutputHandler<Version> {

    private final Pattern versionPattern = Pattern.compile("^git version (.*)");

    private Version version;

    public VersionOutputHandler() {
        super("UTF-8");
    }

    @Override
    public Version getOutput() {
        return version;
    }

    @Override
    protected void processLine(int lineNum, String line) {
        if (version == null) {
            // we only need the first line
            Matcher matcher = versionPattern.matcher(line);
            if (matcher.matches()) {
                version = new Version(matcher.group(1));
            }
        }
    }
}
