package com.atlassian.jgitflow.core;
import java.io.IOException;
import com.atlassian.jgitflow.core.exception.JGitFlowException;
import com.atlassian.jgitflow.core.util.GitHelper;
import com.google.common.base.Strings;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.RefSpec;
import static com.google.common.base.Preconditions.checkState;
/**
* @since version
*/
public class FeatureStartCommand extends AbstractGitFlowCommand<Ref>
{
private final String branchName;
private boolean fetchDevelop;
FeatureStartCommand(String branchName, Git git, GitFlowConfiguration gfConfig)
{
super(git,gfConfig);
checkState(!Strings.isNullOrEmpty(branchName));
this.branchName = branchName;
this.fetchDevelop = false;
}
@Override
public Ref call() throws JGitFlowException
{
//TODO: we should test for remote feature and pull it if it exists
final String prefixedBranchName = gfConfig.getPrefixValue(JGitFlowConstants.PREFIXES.FEATURE.configKey()) + branchName;
requireGitFlowInitialized();
requireLocalBranchAbsent(prefixedBranchName);
if(fetchDevelop)
{
RefSpec spec = new RefSpec("+" + Constants.R_HEADS + gfConfig.getDevelop() + ":" + Constants.R_REMOTES + "origin/" + gfConfig.getDevelop());
try
{
FetchResult result = git.fetch().setRefSpecs(spec).call();
}
catch (GitAPIException e)
{
throw new JGitFlowException(e);
}
}
try
{
//ensure local develop isn't behind remote develop
if(GitHelper.remoteBranchExists(git,gfConfig.getDevelop()))
{
requireLocalBranchNotBehindRemote(gfConfig.getDevelop());
}
//go ahead and create the feature branch
RevCommit developCommit = GitHelper.getLatestCommit(git,gfConfig.getDevelop());
return git.checkout()
.setName(prefixedBranchName)
.setCreateBranch(true)
.setStartPoint(developCommit)
.call();
}
catch (IOException e)
{
throw new JGitFlowException(e);
}
catch (GitAPIException e)
{
throw new JGitFlowException(e);
}
}
public FeatureStartCommand setFetchDevelop(boolean fetch)
{
this.fetchDevelop = fetch;
return this;
}
}