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

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

Introduction

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

Prototype

public StashCreateCommand stashCreate() 

Source Link

Document

Return a command object used to create 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 ww  w .  ja  v a2  s. c om
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//ww  w .  jav  a2 s .  c  o m
 * @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:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java

License:Apache License

protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent,
        UserDetails userDetails) {/*from  w  w  w.j  ava 2s.  co m*/
    StopWatch watch = new StopWatch();
    try {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();

        Git git = new Git(repository);

        File projectFolder = repository.getDirectory();

        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remote, "url");
        if (io.fabric8.utils.Strings.isNullOrBlank(url)) {
            LOG.warn("No remote repository url for " + branch + " defined for the git repository at "
                    + projectFolder.getCanonicalPath() + " so cannot pull");
            //return;
        }
        String mergeUrl = config.getString("branch", branch, "merge");
        if (io.fabric8.utils.Strings.isNullOrBlank(mergeUrl)) {
            LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at "
                    + projectFolder.getCanonicalPath() + " so not doing a pull");
            //return;
        }

        // lets trash any failed changes
        LOG.debug("Stashing local changes to the repo");
        boolean hasHead = true;
        try {
            git.log().all().call();
            hasHead = git.getRepository().getAllRefs().containsKey("HEAD");
        } catch (NoHeadException e) {
            hasHead = false;
        }
        if (hasHead) {
            // lets stash any local changes just in case..
            try {
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .setRef("HEAD").call();
            } catch (Throwable e) {
                LOG.error("Failed to stash changes: " + e, e);
                Throwable cause = e.getCause();
                if (cause != null && cause != e) {
                    LOG.error("Cause: " + cause, cause);
                }
            }
        }

        //LOG.debug("Resetting the repo");
        //git.reset().setMode(ResetCommand.ResetType.HARD).call();

        LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: "
                + url);
        PullCommand pull = git.pull();
        GitUtils.configureCommand(pull, userDetails);
        pull.setRebase(true).call();
    } catch (Throwable e) {
        LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage()
                + ". This exception is ignored.", e);
    } finally {
        LOG.debug("doPull took " + watch.taken());
    }
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected <T> T gitOperation(final GitContext context, final GitOperation<T> operation) throws Exception {
    return lockManager.withLock(gitFolder, new Callable<T>() {

        @Override//from   w  w  w. j  a  va 2s  . co  m
        public T call() throws Exception {
            projectFileSystem.cloneRepoIfNotExist(userDetails, basedir, cloneUrl);

            FileRepositoryBuilder builder = new FileRepositoryBuilder();
            Repository repository = builder.setGitDir(gitFolder).readEnvironment() // scan environment GIT_* variables
                    .findGitDir() // scan up the file system tree
                    .build();

            Git git = new Git(repository);
            if (Strings.isNullOrBlank(origin)) {
                throw new IOException("Could not find remote git URL for folder " + gitFolder.getPath());
            }

            CredentialsProvider credentials = userDetails.createCredentialsProvider();
            createPersonIdent();

            disableSslCertificateChecks();
            LOG.info("Stashing local changes to the repo");
            boolean hasHead = true;
            try {
                git.log().all().call();
                hasHead = git.getRepository().getAllRefs().containsKey("HEAD");
            } catch (NoHeadException e) {
                hasHead = false;
            }
            if (hasHead) {
                // lets stash any local changes just in case..
                try {
                    git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                            .setRef("HEAD").call();
                } catch (Throwable e) {
                    LOG.error("Failed to stash changes: " + e, e);
                    Throwable cause = e.getCause();
                    if (cause != null && cause != e) {
                        LOG.error("Cause: " + cause, cause);
                    }
                }
            }

            checkoutBranch(git, context);
            if (context.isRequirePull()) {
                doPull(git, context);
            }

            T result = operation.call(git, context);

            if (Strings.isNullOrBlank(message)) {
                message = "";
            }
            if (context.isRequireCommit() && hasGitChanges(git)) {
                doAddCommitAndPushFiles(git, userDetails, personIdent, branch, origin, message,
                        isPushOnCommit());
            }
            return result;
        }

    });
}

From source file:io.fabric8.git.internal.GitDataStore.java

License:Apache License

public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst,
        GitContext context) {//  w  w w  . j  a  v  a  2s .  c o  m
    synchronized (gitOperationMonitor) {
        assertValid();

        // must set the TCCL to the classloader that loaded GitDataStore as we need the classloader
        // that could load this class, as jgit will load resources from classpath using the TCCL
        // and that requires the TCCL to the classloader that could load GitDataStore as the resources
        // jgit requires are in the same bundle as GitDataSource (eg embedded inside fabric-git)
        // see FABRIC-887
        ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        ClassLoader cl = GitDataStore.class.getClassLoader();
        Thread.currentThread().setContextClassLoader(cl);
        LOG.trace("Setting ThreadContextClassLoader to {} instead of {}", cl, oldCl);
        try {
            Git git = getGit();
            Repository repository = git.getRepository();
            // lets default the identity if none specified
            if (personIdent == null) {
                personIdent = new PersonIdent(repository);
            }

            if (GitHelpers.hasGitHead(git)) {
                // lets stash any local changes just in case..
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .call();
            }

            if (pullFirst) {
                doPull(git, getCredentialsProvider(), false);
            }

            T answer = operation.call(git, context);
            boolean requirePush = context.isRequirePush();
            if (context.isRequireCommit()) {
                requirePush = true;
                String message = context.getCommitMessage().toString();
                if (message.length() == 0) {
                    LOG.warn("No commit message from " + operation + ". Please add one! :)");
                }
                git.commit().setMessage(message).call();
                if (--commitsWithoutGC < 0) {
                    commitsWithoutGC = MAX_COMMITS_WITHOUT_GC;
                    LOG.debug("Performing \"git gc\" after {} commits", MAX_COMMITS_WITHOUT_GC);
                    git.gc().call();
                }
            }

            if (requirePush) {
                doPush(git, context, getCredentialsProvider());
            }

            if (context.isRequireCommit()) {
                clearCaches();
                fireChangeNotifications();
            }
            return answer;
        } catch (Exception e) {
            throw FabricException.launderThrowable(e);
        } finally {
            LOG.trace("Restoring ThreadContextClassLoader to {}", oldCl);
            Thread.currentThread().setContextClassLoader(oldCl);
        }
    }
}

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

License:Open Source License

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

    JSONObject requestPayload = requestInfo.getJSONRequest();
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;
    Repository db = requestInfo.db;/*  w w  w  .  j  a  va2 s .c om*/

    String indexMessage = requestPayload.optString(GitConstants.KEY_STASH_INDEX_MESSAGE);
    String workingDirectoryMessage = requestPayload.optString(GitConstants.KEY_STASH_WORKING_DIRECTORY_MESSAGE);
    boolean includeUntracked = requestPayload.optBoolean(GitConstants.KEY_STASH_INCLUDE_UNTRACKED, false);

    try {

        Git git = new Git(db);
        StashCreateCommand stashCreate = git.stashCreate();
        stashCreate.setPerson(new PersonIdent(db));
        stashCreate.setIncludeUntracked(includeUntracked);

        if (!indexMessage.isEmpty())
            stashCreate.setIndexMessage(indexMessage);

        if (!workingDirectoryMessage.isEmpty())
            stashCreate.setWorkingDirectoryMessage(workingDirectoryMessage);

        stashCreate.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.fusesource.fabric.git.internal.GitDataStore.java

License:Apache License

public <T> T gitOperation(PersonIdent personIdent, GitOperation<T> operation, boolean pullFirst,
        GitContext context) {//from   w  w w.  j a  v a 2 s. c o m
    synchronized (gitOperationMonitor) {
        assertValid();
        try {
            Git git = getGit();
            Repository repository = git.getRepository();
            CredentialsProvider credentialsProvider = getCredentialsProvider();
            // lets default the identity if none specified
            if (personIdent == null) {
                personIdent = new PersonIdent(repository);
            }

            if (GitHelpers.hasGitHead(git)) {
                // lets stash any local changes just in case..
                git.stashCreate().setPerson(personIdent).setWorkingDirectoryMessage("Stash before a write")
                        .call();
            }
            String originalBranch = repository.getBranch();
            RevCommit statusBefore = CommitUtils.getHead(repository);

            if (pullFirst) {
                doPull(git, credentialsProvider);
            }

            T answer = operation.call(git, context);
            boolean requirePush = context.isRequirePush();
            if (context.isRequireCommit()) {
                requirePush = true;
                String message = context.getCommitMessage().toString();
                if (message.length() == 0) {
                    LOG.warn("No commit message from " + operation + ". Please add one! :)");
                }
                git.commit().setMessage(message).call();
            }

            git.checkout().setName(originalBranch).call();

            if (requirePush || hasChanged(statusBefore, CommitUtils.getHead(repository))) {
                clearCaches();
                doPush(git, context, credentialsProvider);
                fireChangeNotifications();
            }
            return answer;
        } catch (Exception e) {
            throw FabricException.launderThrowable(e);
        }
    }
}

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

License:Open Source License

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

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

License:Open Source License

public static void stashCreate(final Git repo) throws GitAPIException {
    repo.stashCreate().call();
}