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

import com.atlassian.bitbucket.mesh.git.builder.GitProcessBuilder;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;

public class DefaultGitDiffBuilder extends AbstractGitDiffCoreBuilder<GitDiffBuilder> implements GitDiffBuilder {

    public DefaultGitDiffBuilder(GitProcessBuilder builder) {
        super(builder.command("diff"));
    }

    @Override
    protected void applyArguments() {
        super.applyArguments();

        //Context is handled here rather than in the base class because the null case is treated differently for diff
        //than for diff-tree.
        if (context == null) {
            builder.argument("-U"); //Unified diff with default context
        } else {
            builder.argument("-U" + context); //Unified diff with explicit context
        }

        if (StringUtils.isBlank(ancestor)) {
            //If no ancestor is provided, switch to the git log command. --pretty=format: here eliminates all of the
            //other git log output, leaving just the diff output, and -1 limits output to just the requested rev.
            //
            //Note: This style of under-the-covers command switching is _not_ a behaviour to be emulated! It is an
            //      unfortunate but necessary evil of how git diff works with root commits. In general, the caller
            //      should _know_ which git command to use and use the correct one.
            builder.command("log").argument("--pretty=format:").argument("-1");
        } else {
            builder.commitish(ancestor);
        }
        builder.commitish(rev);

        applyPaths();
    }

    @Nonnull
    @Override
    protected DefaultGitDiffBuilder self() {
        return this;
    }
}
