Example usage for org.eclipse.jgit.api Git stashDrop

List of usage examples for org.eclipse.jgit.api Git stashDrop

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git stashDrop.

Prototype

public StashDropCommand stashDrop() 

Source Link

Document

Return a command object used to drop a stashed commit

Usage

From source file:ezbake.deployer.publishers.openShift.RhcApplication.java

License:Apache License

/**
 * This will make sure that a directory is on disk for the git repository.  It will clone the git repo to the directory
 * if needed, or git pull the new contents if required.
 *
 * @return git repository created/retrieved from OpenShift with the remote pointing to OpenShift
 * @throws DeploymentException - on any exception getting it from git
 *//*from w ww  . j av  a 2 s.c o  m*/
public Git getOrCreateGitRepo() throws DeploymentException {
    String gitUrl = applicationInstance.getGitUrl();

    Files.createDirectories(appTmpDir);
    File gitDir = new File(appTmpDir, ".git");
    if (gitRepo != null || gitDir.exists() && gitDir.isDirectory()) {
        try {
            Git git = gitRepo != null ? gitRepo : Git.open(appTmpDir);
            // stash to get to a clean state of git dir so that we can pull without conflicts
            git.stashCreate();
            git.stashDrop();
            PullCommand pullCommand = git.pull();
            if (gitCredentialsProvider != null)
                pullCommand.setCredentialsProvider(gitCredentialsProvider);
            PullResult result = pullCommand.call();
            if (!result.isSuccessful())
                throw new DeploymentException("Git pull was not successful: " + result.toString());
            setGitRepo(git);
            return git;
        } catch (IOException | GitAPIException e) {
            log.error("Error opening existing cached git repo", e);
            throw new DeploymentException("Error opening existing cached git repo: " + e.getMessage());
        }
    } else {
        try {
            log.info("Cloning to " + appTmpDir.toString());
            CloneCommand cloneCommand = Git.cloneRepository().setURI(gitUrl).setTimeout(10000)
                    .setDirectory(appTmpDir);
            if (gitCredentialsProvider != null)
                cloneCommand.setCredentialsProvider(gitCredentialsProvider);
            gitRepo = cloneCommand.call();
            log.info("Cloned to directory: "
                    + gitRepo.getRepository().getDirectory().getParentFile().getAbsolutePath());
            return gitRepo;
        } catch (GitAPIException | JGitInternalException e) {
            log.error("Error cloning repository from OpenShift", e);
            throw new DeploymentException("Error cloning repository from OpenShift: " + e.getMessage());
        }
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

/**
 * @throws MergeFailure//from w  ww.java2s.c  om
 * @throws AuthenticationException 
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateFromRemote(java.io.File, java.lang.String, java.lang.String,
 * gov.va.isaac.interfaces.sync.MergeFailOption)
 */
@Override
public Set<String> updateFromRemote(String username, String password, MergeFailOption mergeFailOption)
        throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException {
    Set<String> filesChangedDuringPull;
    try {
        log.info("update from remote called ");

        Git git = getGit();

        log.debug("Fetching from remote");

        if (git.status().call().getConflicting().size() > 0) {
            log.info("Previous merge failure not yet resolved");
            throw new MergeFailure(git.status().call().getConflicting(), new HashSet<>());
        }

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));
        log.debug("Fetch Message" + git.fetch().setCredentialsProvider(cp).call().getMessages());

        ObjectId masterIdBeforeMerge = git.getRepository().getRef("master").getObjectId();
        if (git.getRepository().getRef("refs/remotes/origin/master").getObjectId().getName()
                .equals(masterIdBeforeMerge.getName())) {
            log.info("No changes to merge");
            return new HashSet<String>();
        }

        RevCommit stash = null;
        if (git.status().call().getUncommittedChanges().size() > 0) {
            log.info("Stashing uncommitted changes");
            stash = git.stashCreate().call();
        }

        {
            log.debug("Merging from remotes/origin/master");
            MergeResult mr = git.merge().include(git.getRepository().getRef("refs/remotes/origin/master"))
                    .call();
            AnyObjectId headAfterMergeID = mr.getNewHead();

            if (!mr.getMergeStatus().isSuccessful()) {
                if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) {
                    addNote(NOTE_FAILED_MERGE_HAPPENED_ON_REMOTE
                            + (stash == null ? ":NO_STASH" : STASH_MARKER + stash.getName()), git);
                    //We can use the status here - because we already stashed the stuff that they had uncommitted above.
                    throw new MergeFailure(mr.getConflicts().keySet(),
                            git.status().call().getUncommittedChanges());
                } else if (MergeFailOption.KEEP_LOCAL == mergeFailOption
                        || MergeFailOption.KEEP_REMOTE == mergeFailOption) {
                    HashMap<String, MergeFailOption> resolutions = new HashMap<>();
                    for (String s : mr.getConflicts().keySet()) {
                        resolutions.put(s, mergeFailOption);
                    }
                    log.debug("Resolving merge failures with option {}", mergeFailOption);
                    filesChangedDuringPull = resolveMergeFailures(MergeFailType.REMOTE_TO_LOCAL,
                            (stash == null ? null : stash.getName()), resolutions);
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            } else {
                //Conflict free merge - or perhaps, no merge at all.
                if (masterIdBeforeMerge.getName().equals(headAfterMergeID.getName())) {
                    log.debug("Merge didn't result in a commit - no incoming changes");
                    filesChangedDuringPull = new HashSet<>();
                } else {
                    filesChangedDuringPull = listFilesChangedInCommit(git.getRepository(), masterIdBeforeMerge,
                            headAfterMergeID);
                }
            }
        }

        if (stash != null) {
            log.info("Replaying stash");
            try {
                git.stashApply().setStashRef(stash.getName()).call();
                log.debug("stash applied cleanly, dropping stash");
                git.stashDrop().call();
            } catch (StashApplyFailureException e) {
                log.debug("Stash failed to merge");
                if (mergeFailOption == null || MergeFailOption.FAIL == mergeFailOption) {
                    addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git);
                    throw new MergeFailure(git.status().call().getConflicting(), filesChangedDuringPull);
                }

                else if (MergeFailOption.KEEP_LOCAL == mergeFailOption
                        || MergeFailOption.KEEP_REMOTE == mergeFailOption) {
                    HashMap<String, MergeFailOption> resolutions = new HashMap<>();
                    for (String s : git.status().call().getConflicting()) {
                        resolutions.put(s, mergeFailOption);
                    }
                    log.debug("Resolving stash apply merge failures with option {}", mergeFailOption);
                    resolveMergeFailures(MergeFailType.STASH_TO_LOCAL, null, resolutions);
                    //When we auto resolve to KEEP_LOCAL - these files won't have really changed, even though we recorded a change above.
                    for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
                        if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                            filesChangedDuringPull.remove(r.getKey());
                        }
                    }
                } else {
                    throw new IllegalArgumentException("Unexpected option");
                }
            }
        }
        log.info("Files changed during updateFromRemote: {}", filesChangedDuringPull);
        return filesChangedDuringPull;
    } catch (CheckoutConflictException e) {
        log.error("Unexpected", e);
        throw new IOException(
                "A local file exists (but is not yet added to source control) which conflicts with a file from the server."
                        + "  Either delete the local file, or call addFile(...) on the offending file prior to attempting to update from remote.",
                e);
    } catch (TransportException te) {
        if (te.getMessage().contains("Auth fail")) {
            log.info("Auth fail", te);
            throw new AuthenticationException("Auth fail");
        } else {
            log.error("Unexpected", te);
            throw new IOException("Internal error", te);
        }
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

From source file:gov.va.isaac.sync.git.SyncServiceGIT.java

License:Apache License

private Set<String> resolveMergeFailures(MergeFailType mergeFailType, String stashIDToApply,
        Map<String, MergeFailOption> resolutions) throws IllegalArgumentException, IOException, MergeFailure {
    log.debug("resolve merge failures called - mergeFailType: {} stashIDToApply: {} resolutions: {}",
            mergeFailType, stashIDToApply, resolutions);
    try {/*ww w.ja v  a  2s  .  c  om*/
        Git git = getGit();

        //We unfortunately, must know the mergeFailType option, because the resolution mechanism here uses OURS and THEIRS - but the 
        //meaning of OURS and THEIRS reverse, depending on if you are recovering from a merge failure, or a stash apply failure.

        for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
            if (MergeFailOption.FAIL == r.getValue()) {
                throw new IllegalArgumentException("MergeFailOption.FAIL is not a valid option");
            } else if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                log.debug("Keeping our local file for conflict {}", r.getKey());
                git.checkout().addPath(r.getKey())
                        .setStage(MergeFailType.REMOTE_TO_LOCAL == mergeFailType ? Stage.OURS : Stage.THEIRS)
                        .call();
            } else if (MergeFailOption.KEEP_REMOTE == r.getValue()) {
                log.debug("Keeping remote file for conflict {}", r.getKey());
                git.checkout().addPath(r.getKey())
                        .setStage(MergeFailType.REMOTE_TO_LOCAL == mergeFailType ? Stage.THEIRS : Stage.OURS)
                        .call();
            } else {
                throw new IllegalArgumentException("MergeFailOption is required");
            }

            log.debug("calling add to mark merge resolved");
            git.add().addFilepattern(r.getKey()).call();
        }

        if (mergeFailType == MergeFailType.STASH_TO_LOCAL) {
            //clean up the stash
            log.debug("Dropping stash");
            git.stashDrop().call();
        }

        RevWalk walk = new RevWalk(git.getRepository());
        Ref head = git.getRepository().getRef("refs/heads/master");
        RevCommit commitWithPotentialNote = walk.parseCommit(head.getObjectId());

        log.info("resolve merge failures Complete.  Current status: " + statusToString(git.status().call()));

        RevCommit rc = git.commit().setMessage(
                "Merging with user specified merge failure resolution for files " + resolutions.keySet())
                .call();

        git.notesRemove().setObjectId(commitWithPotentialNote).call();
        Set<String> filesChangedInCommit = listFilesChangedInCommit(git.getRepository(),
                commitWithPotentialNote.getId(), rc);

        //When we auto resolve to KEEP_REMOTE - these will have changed - make sure they are in the list.
        //seems like this shouldn't really be necessary - need to look into the listFilesChangedInCommit algorithm closer.
        //this might already be fixed by the rework on 11/12/14, but no time to validate at the moment. - doesn't do any harm.
        for (Entry<String, MergeFailOption> r : resolutions.entrySet()) {
            if (MergeFailOption.KEEP_REMOTE == r.getValue()) {
                filesChangedInCommit.add(r.getKey());
            }
            if (MergeFailOption.KEEP_LOCAL == r.getValue()) {
                filesChangedInCommit.remove(r.getKey());
            }
        }

        if (!StringUtils.isEmptyOrNull(stashIDToApply)) {
            log.info("Replaying stash identified in note");
            try {
                git.stashApply().setStashRef(stashIDToApply).call();
                log.debug("stash applied cleanly, dropping stash");
                git.stashDrop().call();
            } catch (StashApplyFailureException e) {
                log.debug("Stash failed to merge");
                addNote(NOTE_FAILED_MERGE_HAPPENED_ON_STASH, git);
                throw new MergeFailure(git.status().call().getConflicting(), filesChangedInCommit);
            }
        }

        return filesChangedInCommit;
    } catch (GitAPIException e) {
        log.error("Unexpected", e);
        throw new IOException("Internal error", e);
    }
}

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

License:Open Source License

@Override
protected boolean handlePut(RequestInfo requestInfo) throws ServletException {

    JSONObject requestPayload = requestInfo.getJSONRequest();
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;/*from  w  ww.ja v  a 2 s  . c o  m*/

    /* gitapi/stash/<stashRev>/file/(...) */
    String stashRev = requestInfo.gitSegment;

    boolean applyIndex = requestPayload.optBoolean(GitConstants.KEY_STASH_APPLY_INDEX, true);
    boolean applyUntracked = requestPayload.optBoolean(GitConstants.KEY_STASH_APPLY_UNTRACKED, true);

    try {

        Git git = new Git(db);

        /* check for empty stash */
        if (isStashEmpty(git)) {
            String msg = "Failed to apply stashed changes due to an empty stash.";
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.WARNING, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        StashApplyCommand applyCommand = new StashApplyCommand(db);

        if (stashRev != null) {

            StashRef stashRef = getStashRef(git, stashRev);
            if (stashRef == null) {
                String msg = NLS.bind("Invalid stash reference {0}.", stashRev);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            applyCommand.setStashRef(stashRef.getStringRef());
            applyCommand.setApplyUntracked(applyUntracked);
            applyCommand.setApplyIndex(applyIndex);
            applyCommand.call();

        } else {

            /* git stash pop */
            applyCommand.setApplyUntracked(applyUntracked);
            applyCommand.setApplyIndex(applyIndex);
            applyCommand.call();

            StashDropCommand dropCommand = git.stashDrop();
            dropCommand.setAll(false);
            dropCommand.call();

        }

        return true;

    } catch (Exception ex) {
        String msg = "An error occured for stash command.";
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
    }
}

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

License:Open Source License

@Override
protected boolean handleDelete(RequestInfo requestInfo) throws ServletException {

    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;/* w  w w . j  a v a 2s  . co  m*/

    /* gitapi/stash/<stashRev>/file/(...) */
    String stashRev = requestInfo.gitSegment;

    try {

        Git git = new Git(db);

        /* check for empty stash */
        if (isStashEmpty(git)) {
            String msg = "Failed to drop stashed changes due to an empty stash.";
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.WARNING, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        StashDropCommand dropCommand = git.stashDrop();

        if (stashRev != null) {

            StashRef stashRef = getStashRef(git, stashRev);
            if (stashRef == null) {
                String msg = NLS.bind("Invalid stash reference {0}.", stashRev);
                return statusHandler.handleRequest(request, response,
                        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
            }

            dropCommand.setStashRef(stashRef.getRef());

        } else
            dropCommand.setAll(true);

        dropCommand.call();
        return true;

    } catch (Exception ex) {
        String msg = "An error occured for stash command.";
        return statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg, ex));
    }
}

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

License:Open Source License

@Override
public void stashDrop(final Git repo) throws GitAPIException {
    repo.stashDrop().call();
}

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

License:Open Source License

public static void stashDrop(final Git repo) throws GitAPIException {
    repo.stashDrop().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 w w  w  . j a  v a  2s. 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());
        }
    }

}