Example usage for org.eclipse.jgit.api CheckoutCommand setUpstreamMode

List of usage examples for org.eclipse.jgit.api CheckoutCommand setUpstreamMode

Introduction

In this page you can find the example usage for org.eclipse.jgit.api CheckoutCommand setUpstreamMode.

Prototype

public CheckoutCommand setUpstreamMode(CreateBranchCommand.SetupUpstreamMode mode) 

Source Link

Document

When creating a branch with #setCreateBranch(boolean) , this can be used to configure branch tracking.

Usage

From source file:com.rimerosolutions.ant.git.tasks.CheckoutTask.java

License:Apache License

@Override
protected void doExecute() throws BuildException {
    try {//from ww w  . ja v a2s .  c om
        CheckoutCommand checkoutCommand = git.checkout();

        if (createBranch) {
            checkoutCommand.setCreateBranch(true);

            if (trackBranchOnCreate) {
                checkoutCommand.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
            }
        }

        if (!GitTaskUtils.isNullOrBlankString(branchName)) {
            checkoutCommand.setName(branchName);
        }

        if (!GitTaskUtils.isNullOrBlankString(startPoint)) {
            checkoutCommand.setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + startPoint);
        }

        checkoutCommand.call();

        CheckoutResult checkoutResult = checkoutCommand.getResult();

        if (checkoutResult.getStatus().equals(CheckoutResult.Status.CONFLICTS)) {
            String conflicts = checkoutResult.getConflictList().toString();

            throw new GitBuildException(String.format("Conflicts were found:%s.", conflicts));
        } else if (checkoutResult.getStatus().equals(CheckoutResult.Status.NONDELETED)) {
            String undeleted = checkoutResult.getUndeletedList().toString();

            throw new GitBuildException(String.format("Some files could not be deleted:%s.", undeleted));
        }
    } catch (RefAlreadyExistsException e) {
        throw new GitBuildException(
                String.format("Cannot create branch '%s', as it already exists!", branchName), e);
    } catch (RefNotFoundException e) {
        throw new GitBuildException(String.format("The branch '%s' was not found.", branchName), e);
    } catch (InvalidRefNameException e) {
        throw new GitBuildException("An invalid branch name was specified.", e);
    } catch (CheckoutConflictException e) {
        throw new GitBuildException("Some checkout conflicts were found.", e);
    } catch (GitAPIException e) {
        throw new GitBuildException(String.format("Could not checkout branch '%s'.", branchName), e);
    }
}

From source file:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java

License:Open Source License

private @Nonnull Git getActiveRepository(Repository repository) throws IOException {
    try {//  w ww.j ava  2s.com
        // Clone the bare repository
        File cloneDir = File.createTempFile("clone", "");

        if (cloneDir.exists()) {
            if (cloneDir.isDirectory()) {
                FileUtils.deleteDirectory(cloneDir);
            } else {
                if (!cloneDir.delete()) {
                    throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone");
                }
            }
        }
        if (!cloneDir.mkdirs()) {
            throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory");
        }

        String url = repository.getConfig().getString("remote", "origin", "url");
        Git gitClient = Git.cloneRepository().setCloneAllBranches(false)
                .setProgressMonitor(new CloneProgressMonitor(url))
                .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call();

        RemoteRemoveCommand remove = gitClient.remoteRemove();
        remove.setName("origin");
        remove.call();

        RemoteAddCommand add = gitClient.remoteAdd();
        add.setName("origin");
        add.setUri(new URIish(gitSource.getRemote()));
        add.call();

        if (GitUtils.isSshUrl(gitSource.getRemote())) {
            // Get committer info and credentials
            User user = User.current();
            if (user == null) {
                throw new ServiceException.UnauthorizedException("Not authenticated");
            }
            BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user);

            // Make sure up-to-date and credentials work
            GitUtils.fetch(repository, privateKey);
        } else {
            FetchCommand fetch = gitClient.fetch();
            fetch.call();
        }

        if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + sourceBranch);
            checkout.setName(sourceBranch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();

            checkout = gitClient.checkout();
            checkout.setName(branch);
            checkout.setCreateBranch(true); // this *should* be a new branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        } else {
            CheckoutCommand checkout = gitClient.checkout();
            checkout.setStartPoint("origin/" + branch);
            checkout.setName(branch);
            checkout.setCreateBranch(true); // to create a new local branch
            checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK);
            checkout.call();
        }

        return gitClient;
    } catch (GitAPIException | URISyntaxException ex) {
        throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public void checkout(CheckoutRequest request) throws GitException {
    CheckoutCommand checkoutCommand = getGit().checkout();
    String startPoint = request.getStartPoint();
    String name = request.getName();
    String trackBranch = request.getTrackBranch();

    // checkout files?
    List<String> files = request.getFiles();
    boolean shouldCheckoutToFile = name != null && new File(getWorkingDir(), name).exists();
    if (shouldCheckoutToFile || !files.isEmpty()) {
        if (shouldCheckoutToFile) {
            checkoutCommand.addPath(request.getName());
        } else {//  ww  w  .j  a  v  a 2s.  co m
            files.forEach(checkoutCommand::addPath);
        }
    } else {
        // checkout branch
        if (startPoint != null && trackBranch != null) {
            throw new GitException("Start point and track branch can not be used together.");
        }
        if (request.isCreateNew() && name == null) {
            throw new GitException("Branch name must be set when createNew equals to true.");
        }
        if (startPoint != null) {
            checkoutCommand.setStartPoint(startPoint);
        }
        if (request.isCreateNew()) {
            checkoutCommand.setCreateBranch(true);
            checkoutCommand.setName(name);
        } else if (name != null) {
            checkoutCommand.setName(name);
            List<String> localBranches = branchList(
                    newDto(BranchListRequest.class).withListMode(BranchListRequest.LIST_LOCAL)).stream()
                            .map(Branch::getDisplayName).collect(Collectors.toList());
            if (!localBranches.contains(name)) {
                Optional<Branch> remoteBranch = branchList(
                        newDto(BranchListRequest.class).withListMode(BranchListRequest.LIST_REMOTE)).stream()
                                .filter(branch -> branch.getName().contains(name)).findFirst();
                if (remoteBranch.isPresent()) {
                    checkoutCommand.setCreateBranch(true);
                    checkoutCommand.setStartPoint(remoteBranch.get().getName());
                }
            }
        }
        if (trackBranch != null) {
            if (name == null) {
                checkoutCommand.setName(cleanRemoteName(trackBranch));
            }
            checkoutCommand.setCreateBranch(true);
            checkoutCommand.setStartPoint(trackBranch);
        }
        checkoutCommand.setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM);
    }
    try {
        checkoutCommand.call();
    } catch (GitAPIException exception) {
        if (exception.getMessage().endsWith("already exists")) {
            throw new GitException(String.format(ERROR_BRANCH_NAME_EXISTS,
                    name != null ? name : cleanRemoteName(trackBranch)));
        }
        throw new GitException(exception.getMessage(), exception);
    }
}

From source file:org.jboss.forge.addon.git.GitUtilsImpl.java

License:Open Source License

@Override
public Ref checkout(final Git git, final String remote, final boolean createBranch,
        final SetupUpstreamMode mode, final boolean force) throws GitAPIException {
    CheckoutCommand checkout = git.checkout();
    checkout.setCreateBranch(createBranch);
    checkout.setName(remote);//from   w ww . ja  v  a2 s . com
    checkout.setForce(force);
    checkout.setUpstreamMode(mode);
    return checkout.call();
}

From source file:org.jboss.forge.addon.git.GitUtilsImpl.java

License:Open Source License

@Override
public Ref checkout(final Git git, final Ref localRef, final SetupUpstreamMode mode, final boolean force)
        throws GitAPIException {
    CheckoutCommand checkout = git.checkout();
    checkout.setName(Repository.shortenRefName(localRef.getName()));
    checkout.setForce(force);// w w w  .j  a v a 2  s  .com
    checkout.setUpstreamMode(mode);
    return checkout.call();
}

From source file:org.jboss.forge.git.GitUtils.java

License:Open Source License

public static Ref checkout(final Git git, final String remote, final boolean createBranch,
        final SetupUpstreamMode mode, final boolean force) throws GitAPIException {
    CheckoutCommand checkout = git.checkout();
    checkout.setCreateBranch(createBranch);
    checkout.setName(remote);/*from  w  ww . j a  v a 2 s .co  m*/
    checkout.setForce(force);
    checkout.setUpstreamMode(mode);
    return checkout.call();
}

From source file:org.jboss.forge.git.GitUtils.java

License:Open Source License

public static Ref checkout(final Git git, final Ref localRef, final boolean createBranch,
        final SetupUpstreamMode mode, final boolean force) throws GitAPIException {
    CheckoutCommand checkout = git.checkout();
    checkout.setName(Repository.shortenRefName(localRef.getName()));
    checkout.setForce(force);/*w w  w.java  2 s . c o  m*/
    checkout.setUpstreamMode(mode);
    return checkout.call();
}

From source file:replicatorg.app.ui.panels.UpdateChecker.java

License:Open Source License

private void updateFilaments() {
    final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
    final Git git;
    final Status repoStatus;
    final RemoteAddCommand remoteAddCmd;
    ResetCommand resetCmd;//from   www  .  ja va2  s  .  c  o  m
    CheckoutCommand checkoutCmd;
    final String currentBranch, newBranch;
    final List<Ref> branchList;
    Repository filamentsRepo;
    boolean branchFoundLocally = false;
    RevCommit stash = null;

    repoBuilder.setMustExist(true);
    repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git"));

    try {
        try {
            Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass());
            filamentsRepo = repoBuilder.build();
        } catch (RepositoryNotFoundException ex) {
            try {
                Base.writeLog("Repository wasn't initialized, initializing it to the given URL: "
                        + FILAMENTS_REPO_URL, this.getClass());
                repoBuilder.setMustExist(false);
                filamentsRepo = repoBuilder.build();
                filamentsRepo.create();
            } catch (IOException ex1) {
                Base.writeLog("IOException while attempting to initialize repository, not updating filaments",
                        this.getClass());
                return;
            }
        }

        currentBranch = filamentsRepo.getBranch();

    } catch (IOException ex) {
        Base.writeLog("IOException while attempting to open repository, not updating filaments",
                this.getClass());
        return;
    }

    git = new Git(filamentsRepo);

    try {
        // it should be only 1, but it shortens the code needed, as the call()
        // method returns an iterable
        for (RevCommit commit : git.log().setMaxCount(1).call()) {
            Base.writeLog("Current commit hash: " + commit, this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog(
                "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update",
                this.getClass());
    }

    try {
        remoteAddCmd = git.remoteAdd();
        remoteAddCmd.setName("origin");
        remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL));
        remoteAddCmd.call();
    } catch (URISyntaxException ex) {
        Base.writeLog("Invalid git filament repo remote URL!", this.getClass());
        return;
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass());
        return;
    }

    try {

        if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) {
            Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH
                    + ", searching for it", this.getClass());
            checkoutCmd = git.checkout();
            checkoutCmd.setName(FILAMENTS_REPO_BRANCH);

            branchList = git.branchList().call();

            for (Ref ref : branchList) {
                if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) {
                    Base.writeLog("Correct branch was found locally", this.getClass());
                    branchFoundLocally = true;
                    break;
                }
            }

            if (branchFoundLocally == false) {
                Base.writeLog(
                        "No correct branch was found locally, attempting to checkout a new branch tracking the remote",
                        this.getClass());
                checkoutCmd.setCreateBranch(true);
                checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
                checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH);
                git.fetch().call();
            }

            RevCommit backup = null;
            if (git.status().call().isClean() == false) {
                git.add().addFilepattern(".").call();
                backup = git.commit().setMessage("local backup of user modifications").call();
            }

            newBranch = checkoutCmd.call().getName();

            if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) {
                Base.writeLog("Unable to change to correct branch, aborting update", this.getClass());
                return;
            } else {
                Base.writeLog("Changed to correct branch, " + newBranch, this.getClass());
            }

            try {
                for (RevCommit commit : git.log().setMaxCount(1).call()) {
                    Base.writeLog("Commit hash after branch change: " + commit, this.getClass());

                }
            } catch (GitAPIException ex) {
                // we don't want all the process to stop just because we couldn't acquire the hash here,
                // hence this catch
                Base.writeLog(
                        "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update",
                        this.getClass());
            }

            if (backup != null) {
                // TODO: restore backup of user modifications
                //git.cherryPick().setNoCommit(true).include(backup).call();
            }
        }

        repoStatus = git.status().call();

        checkoutCmd = git.checkout();
        checkoutCmd.setName(FILAMENTS_REPO_BRANCH);
        checkoutCmd.call();

        git.fetch();
        resetCmd = git.reset();
        resetCmd.setMode(ResetType.HARD);
        resetCmd.call();

        git.pull().call();

        /*
        repoStatus = git.status().call();
        if (repoStatus.hasUncommittedChanges()) {
        Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass());
        stash = git.stashCreate().call();
        git.pull().call();
        git.stashApply().call();        // will apply the last stash made
        git.stashDrop().call();         // remove the last stash made
        } else {
        Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass());
        git.pull().call();
        }
        */

        Base.writeLog("Filament update concluded successfully!", this.getClass());

        try {
            for (RevCommit commit : git.log().setMaxCount(1).call()) {
                Base.writeLog("Commit hash after update process finished: " + commit, this.getClass());

            }
        } catch (GitAPIException ex) {
            // we don't want all the process to stop just because we couldn't acquire the hash here,
            // hence this catch
            Base.writeLog(
                    "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update",
                    this.getClass());
        }
    } catch (GitAPIException ex) {
        Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass());
        try {
            resetCmd = git.reset();
            resetCmd.setMode(ResetType.HARD);
            resetCmd.call();

            if (stash != null) {
                git.stashApply().call();
                git.stashDrop().call();
            }

        } catch (GitAPIException ex1) {
            Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...",
                    this.getClass());
        }
    }

}