package com.atlassian.stash.internal.scm.git.command.merge;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.scm.git.command.GitCommandExitHandler;
import com.atlassian.bitbucket.scm.git.command.push.GitNonFastForwardUpdateRejectedException;

import javax.annotation.Nonnull;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @since 2.9
 */
public class UpdateRefCommandExitHandler extends GitCommandExitHandler {

    private static final Pattern PATTERN_OUT_OF_DATE = Pattern.compile("error: Ref ([^\\s]+) is at [a-f0-9]+ but expected [a-f0-9]+");

    public UpdateRefCommandExitHandler(@Nonnull I18nService i18nService, Repository repository) {
        super(i18nService, repository);
    }

    @Override
    protected void evaluateStdErr(String stdErr, String command) {
        Matcher matcher = PATTERN_OUT_OF_DATE.matcher(stdErr);
        if (matcher.find()) { //Don't use matches(); there's a fatal: segment about locking after the error
            throw new GitNonFastForwardUpdateRejectedException(i18nService.createKeyedMessage("bitbucket.git.merge.concurrent"),
                    matcher.group(1));
        }

        //Otherwise, for any other output, fall back on the default handling
        super.evaluateStdErr(stdErr, command);
    }
}
