package com.atlassian.bitbucket.mesh.git.builder.config;

import com.atlassian.bitbucket.mesh.git.GitProcessCompletionHandler;
import com.atlassian.bitbucket.mesh.process.ProcessSummary;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;

/**
 * Handles exit statuses for {@code git config}.
 * <p>
 * The handling here is based on the {@code man} page for {@code git config}:
 * <pre><code>
 *     This command will fail with non-zero status upon error. Some exit codes are:
 *     * the section or key is invalid (ret=1),
 *     * no section or name was provided (ret=2),
 *     * the config file is invalid (ret=3),
 *     * the config file cannot be written (ret=4),
 *     * you try to unset an option which does not exist (ret=5),
 *     * you try to unset/set an option for which multiple lines match (ret=5), or
 *     * you try to use an invalid regexp (ret=6).
 * </code></pre>
 */
public class GetConfigCompletionHandler extends GitProcessCompletionHandler {

    @Override
    protected boolean isError(@Nonnull ProcessSummary summary) {
        if (summary.getExitCode() == 1 && summary.getThrown() == null && StringUtils.isEmpty(summary.getStderr())) {
            //If the requested key doesn't exist, git config exits with status code 1 without writing anything
            //to stderr. Rather than throw a CommandFailedException, let the ProcessStdioHandler deal with it
            return false;
        }
        return super.isError(summary);
    }
}
