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

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

Introduction

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

Prototype

public CheckoutCommand addPath(String path) 

Source Link

Document

Add a single slash-separated path to the list of paths to check out.

Usage

From source file:org.ajoberstar.gradle.git.tasks.GitCheckout.java

License:Apache License

@TaskAction
void checkout() {
    final CheckoutCommand cmd = getGit().checkout();
    cmd.setStartPoint(startPoint);//from   w w  w . ja v  a  2s.  com
    cmd.setName(branchName);
    cmd.setCreateBranch(createBranch);

    if (!patternSet.getExcludes().isEmpty() || !patternSet.getIncludes().isEmpty()) {
        getSource().visit(new FileVisitor() {
            public void visitDir(FileVisitDetails arg0) {
                visitFile(arg0);
            }

            public void visitFile(FileVisitDetails arg0) {
                cmd.addPath(arg0.getPath());
            }
        });
    }

    try {
        cmd.call();
    } catch (Exception e) {
        throw new GradleException("Problem checking out from repository", e);
    }
}

From source file:org.apache.stratos.cartridge.agent.artifact.deployment.synchronizer.git.impl.GitBasedArtifactRepository.java

License:Apache License

private boolean checkoutFromRemoteHead(RepositoryContext gitRepoCtx, List<String> paths) {

    boolean checkoutSuccess = false;

    CheckoutCommand checkoutCmd = gitRepoCtx.getGit().checkout();
    for (String path : paths) {
        checkoutCmd.addPath(path);
        if (log.isDebugEnabled()) {
            log.debug("Added the file path " + path + " to checkout from the remote repository");
        }//www  .  j a  v a  2  s .com
    }
    // specify the start point as the HEAD of remote repository
    checkoutCmd.setStartPoint(GitDeploymentSynchronizerConstants.REMOTES_ORIGIN_MASTER);

    try {
        checkoutCmd.call();
        checkoutSuccess = true;
        log.info("Checked out the conflicting files from the remote repository successfully");

    } catch (GitAPIException e) {
        log.error("Checking out artifacts from index failed", e);
    }

    return checkoutSuccess;
}

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 {/*from   w  w  w  .  ja  v  a  2 s.  c o 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.eclipse.egit.ui.internal.staging.StagingView.java

License:Open Source License

private void replaceWith(String[] files, boolean headRevision) {
    if (files == null || files.length == 0)
        return;/*from  ww w  . j  ava2 s  .c o m*/
    CheckoutCommand checkoutCommand = new Git(currentRepository).checkout();
    if (headRevision)
        checkoutCommand.setStartPoint(Constants.HEAD);
    for (String path : files)
        checkoutCommand.addPath(path);
    try {
        checkoutCommand.call();
    } catch (Exception e) {
        Activator.handleError(UIText.StagingView_checkoutFailed, e, true);
    }
}

From source file:org.eclipse.orion.server.git.servlets.GitCloneHandlerV1.java

License:Open Source License

private boolean handlePut(HttpServletRequest request, HttpServletResponse response, String pathString)
        throws IOException, JSONException, ServletException, URISyntaxException, CoreException,
        JGitInternalException, GitAPIException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { //$NON-NLS-1$

        // make sure a clone is addressed
        WebProject webProject = WebProject.fromId(path.segment(1));
        if (isAccessAllowed(request.getRemoteUser(), webProject)) {
            URI contentLocation = URI.create(webProject.getId());
            IPath projectPath = new Path(contentLocation.getPath()).append(path.removeFirstSegments(2));
            projectPath = path.hasTrailingSeparator() ? projectPath : projectPath.removeLastSegments(1);
            File gitDir = GitUtils.getGitDirs(new Path("file").append(projectPath), Traverse.CURRENT).values() //$NON-NLS-1$
                    .iterator().next();//from  www .  j  av a  2  s.c om

            // make sure required fields are set
            JSONObject toCheckout = OrionServlet.readJSONRequest(request);
            JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
            String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME);
            if ((paths == null || paths.length() == 0) && (branch == null || branch.isEmpty())) {
                String msg = NLS.bind("Either '{0}' or '{1}' should be provided: {2}",
                        new Object[] { ProtocolConstants.KEY_PATH, GitConstants.KEY_BRANCH_NAME, toCheckout });
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            Git git = new Git(new FileRepository(gitDir));
            if (paths != null) {
                CheckoutCommand checkout = git.checkout();
                for (int i = 0; i < paths.length(); i++) {
                    checkout.addPath(paths.getString(i));
                }
                checkout.call();
                return true;
            } else if (branch != null) {
                CheckoutCommand co = git.checkout();
                try {
                    co.setName(branch).call();
                    return true;
                } catch (JGitInternalException e) {
                    if (Status.CONFLICTS.equals(co.getResult().getStatus())) {
                        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                                HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
                    }
                    // TODO: handle other exceptions
                } catch (RefNotFoundException e) {
                    String msg = NLS.bind("Branch name not found: {0}", branch);
                    return statusHandler.handleRequest(request, response,
                            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
                }

            }
        } else {
            String msg = NLS.bind("Nothing found for the given ID: {0}", path);
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
        }
    }
    String msg = NLS.bind("Invalid checkout request {0}", pathString);
    return statusHandler.handleRequest(request, response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
}

From source file:org.eclipse.ptp.internal.rdt.sync.git.core.JGitRepo.java

License:Open Source License

/**
 * Replace given files with the most recent versions in the repository
 * /*from w ww  . jav a2  s .  co  m*/
 * @param paths
 *          Array of paths to checkout
 * @throws GitAPIException
 *          on JGit-specific problems
 */
public void checkout(IPath[] paths) throws GitAPIException {
    CheckoutCommand checkoutCommand = git.checkout();
    for (IPath p : paths) {
        checkoutCommand.addPath(p.toString());
    }
    checkoutCommand.setStartPoint("HEAD"); //$NON-NLS-1$
    checkoutCommand.call();
}

From source file:org.eclipse.ptp.internal.rdt.sync.git.core.JGitRepo.java

License:Open Source License

/**
 * Replace given files with the most recent local copies from the remote (not necessarily the same as the current remote since
 * no transferring of files is done)//  w  ww.ja  va2s  .  c  o m
 * 
 * @param paths
 *          Array of paths to replace
 * @throws GitAPIException
 */
public void checkoutRemoteCopy(IPath[] paths) throws GitAPIException {
    CheckoutCommand checkoutCommand = git.checkout();
    for (IPath p : paths) {
        checkoutCommand.addPath(p.toString());
    }
    checkoutCommand.setStartPoint("refs/remotes/" + remoteBranchName + "/master"); //$NON-NLS-1$ //$NON-NLS-2$
    checkoutCommand.call();
}

From source file:org.omegat.core.team.GITRemoteRepository.java

License:Open Source License

public void restoreBase(File[] files) throws Exception {
    String baseRevisionId = getBaseRevisionId(files[0]);
    Log.logDebug(LOGGER, "GIT restore base {0} for {1}", baseRevisionId, (Object) files);
    //undo local changes of specific file.
    CheckoutCommand checkoutCommand = new Git(repository).checkout();
    for (File f : files) {
        String relativeFileName = FileUtil.computeRelativePath(repository.getWorkTree(), f);
        checkoutCommand.addPath(relativeFileName);
    }//from   w  ww .  j a va2  s  . co  m
    checkoutCommand.call();
    //reset repo to previous version. Can cause conflicts for other files!
    new Git(repository).checkout().setName(baseRevisionId).call();
}

From source file:org.wso2.carbon.deployment.synchronizer.git.GitBasedArtifactRepository.java

License:Open Source License

/**
 * Checkout the artifacts from the local index. Any local working copy changes will be discarded.
 *
 * @param gitRepoCtx TenantGitRepositoryContext instance for the current tenant
 * @param paths List of paths for artifacts with conflicts
 * @return true if successfully checked out all the files from local index, else false
 *//*from ww  w . ja  v a2s  .  co  m*/
private boolean checkoutFromLocalIndex(TenantGitRepositoryContext gitRepoCtx, List<String> paths) {

    boolean checkoutSuccess = false;

    if (paths.isEmpty()) {
        return checkoutSuccess;
    }

    CheckoutCommand checkoutCmd = gitRepoCtx.getGit().checkout();
    for (String path : paths) {
        checkoutCmd.addPath(path);
    }

    try {
        checkoutCmd.call();
        if (log.isDebugEnabled()) {
            for (String path : paths) {
                log.debug("Checked out conflicting file " + path + " from the local index successfully");
            }
        }
        checkoutSuccess = true;
        log.info("Checked out the conflicting files from the local index successfully");

    } catch (GitAPIException e) {
        log.error("Checking out artifacts from index failed", e);
    }

    return checkoutSuccess;
}

From source file:pl.nask.hsn2.framework.workflow.repository.GitWorkflowRepository.java

License:Open Source License

private void checkout(String workflowName, String version) throws WorkflowRepoException {
    CheckoutCommand cmd = newGit().checkout();
    cmd.addPath(workflowName);
    cmd.setStartPoint(version);//from  w w w  .j a v a2  s.  com

    try {
        cmd.call();
    } catch (Exception e) {
        LOGGER.error("Error checking out {}, rev {}", workflowName, version == null ? "HEAD" : version);
        throw new WorkflowRepoException("Error performing checkout" + workflowName, e);
    }
}