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

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

Introduction

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

Prototype

public CheckoutCommand checkout() 

Source Link

Document

Return a command object to execute a checkout command

Usage

From source file:de.blizzy.documentr.repository.ProjectRepositoryManager.java

License:Open Source License

public void importSampleContents() throws IOException, GitAPIException {
    // TODO: synchronization is not quite correct here, but should be okay in this edge case
    if (listBranches().isEmpty()) {
        ILock lock = lockManager.lockAll();
        List<String> branches;
        try {//w w  w  . j a  v  a 2s.co  m
            File gitDir = new File(centralRepoDir, ".git"); //$NON-NLS-1$
            FileUtils.forceDelete(gitDir);

            Git.cloneRepository().setURI(DocumentrConstants.SAMPLE_REPO_URL).setDirectory(gitDir).setBare(true)
                    .call();

            Repository centralRepo = null;
            File centralRepoGitDir;
            try {
                centralRepo = getCentralRepositoryInternal(true);
                centralRepoGitDir = centralRepo.getDirectory();
                StoredConfig config = centralRepo.getConfig();
                config.unsetSection("remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$
                config.unsetSection("branch", "master"); //$NON-NLS-1$ //$NON-NLS-2$
                config.save();
            } finally {
                RepositoryUtil.closeQuietly(centralRepo);
            }

            branches = listBranches();
            for (String branchName : branches) {
                File repoDir = new File(reposDir, branchName);
                Repository repo = null;
                try {
                    repo = Git.cloneRepository().setURI(centralRepoGitDir.toURI().toString())
                            .setDirectory(repoDir).call().getRepository();

                    Git git = Git.wrap(repo);
                    RefSpec refSpec = new RefSpec(
                            "refs/heads/" + branchName + ":refs/remotes/origin/" + branchName); //$NON-NLS-1$ //$NON-NLS-2$
                    git.fetch().setRemote("origin").setRefSpecs(refSpec).call(); //$NON-NLS-1$
                    git.branchCreate().setName(branchName).setStartPoint("origin/" + branchName).call(); //$NON-NLS-1$
                    git.checkout().setName(branchName).call();
                } finally {
                    RepositoryUtil.closeQuietly(repo);
                }
            }
        } finally {
            lockManager.unlock(lock);
        }

        for (String branch : branches) {
            eventBus.post(new BranchCreatedEvent(projectName, branch));
        }
    }
}

From source file:de._692b8c32.cdlauncher.tasks.GITCheckoutTask.java

License:Open Source License

@Override
public void doWork() {
    setProgress(-1);/*from  w w w  .j a  va2s  . c  o  m*/

    try {
        Git git = Git.open(cacheDir);
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
        git.checkout().setAllPaths(true).setForce(true).setName(branch).setStartPoint(startPoint.getValue())
                .call();

        if (destinationDir != null) {
            FileUtils.delete(destinationDir, FileUtils.RECURSIVE | FileUtils.SKIP_MISSING);
            destinationDir.mkdirs();
            Files.list(cacheDir.toPath()).filter(path -> !(".git".equals(path.getFileName().toString())))
                    .forEach(path -> {
                        try {
                            Files.move(path, destinationDir.toPath().resolve(path.getFileName()),
                                    StandardCopyOption.ATOMIC_MOVE);
                        } catch (IOException ex) {
                            throw new RuntimeException("Failed to move " + path.getFileName(), ex);
                        }
                    });
        }
        git.close();
    } catch (RepositoryNotFoundException | InvalidRemoteException ex) {
        throw new RuntimeException("Could not find repository");
    } catch (GitAPIException | IOException ex) {
        throw new RuntimeException("Could not checkout data", ex);
    }
}

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

License:Apache License

/**
 * @throws AuthenticationException //from  www .j  a v a2  s. co m
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#linkAndFetchFromRemote(java.io.File, java.lang.String, java.lang.String, java.lang.String)
 */
@Override
public void linkAndFetchFromRemote(String remoteAddress, String username, String password)
        throws IllegalArgumentException, IOException, AuthenticationException {
    log.info("linkAndFetchFromRemote called - folder: {}, remoteAddress: {}, username: {}", localFolder,
            remoteAddress, username);
    try {
        File gitFolder = new File(localFolder, ".git");
        Repository r = new FileRepository(gitFolder);

        if (!gitFolder.isDirectory()) {
            log.debug("Root folder does not contain a .git subfolder.  Creating new git repository.");
            r.create();
        }

        relinkRemote(remoteAddress, username, password);

        Git git = new Git(r);

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(username,
                (password == null ? new char[] {} : password.toCharArray()));

        log.debug("Fetching");
        FetchResult fr = git.fetch().setCheckFetchedObjects(true).setCredentialsProvider(cp).call();
        log.debug("Fetch messages: {}", fr.getMessages());

        boolean remoteHasMaster = false;
        Collection<Ref> refs = git.lsRemote().setCredentialsProvider(cp).call();
        for (Ref ref : refs) {
            if ("refs/heads/master".equals(ref.getName())) {
                remoteHasMaster = true;
                log.debug("Remote already has 'heads/master'");
                break;
            }
        }

        if (remoteHasMaster) {
            //we need to fetch and (maybe) merge - get onto origin/master.

            log.debug("Fetching from remote");
            String fetchResult = git.fetch().setCredentialsProvider(cp).call().getMessages();
            log.debug("Fetch Result: {}", fetchResult);

            log.debug("Resetting to origin/master");
            git.reset().setMode(ResetType.MIXED).setRef("origin/master").call();

            //Get the files from master that we didn't have in our working folder
            log.debug("Checking out missing files from origin/master");
            for (String missing : git.status().call().getMissing()) {
                log.debug("Checkout {}", missing);
                git.checkout().addPath(missing).call();
            }

            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding " + newFile).setAuthor(username, "42").call();

                for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                    log.debug("Push Message: {}", pr.getMessages());
                }
            }
        } else {
            //just push
            //make sure we have something to push
            for (String newFile : makeInitialFilesAsNecessary(localFolder)) {
                log.debug("Adding and committing {}", newFile);
                git.add().addFilepattern(newFile).call();
                git.commit().setMessage("Adding readme file").setAuthor(username, "42").call();
            }

            log.debug("Pushing repository");
            for (PushResult pr : git.push().setCredentialsProvider(cp).call()) {
                log.debug("Push Result: {}", pr.getMessages());
            }
        }

        log.info("linkAndFetchFromRemote Complete.  Current status: " + statusToString(git.status().call()));
    } 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 {/*  w  w  w.  jav a2 s . c o m*/
        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:io.dpwspoon.github.utils.TravisCIUtils.java

public static void addTravisFileToRepo(final String uri, final String branchName, final String orgName,
        final String repoName, File workingDir)
        throws IOException, InvalidRemoteException, TransportException, GitAPIException {
    File directory = new File(workingDir, repoName);
    Git localRepo = null;
    for (int trys = 0; true; trys++) {
        try {//from   w  w w  . ja  v a  2  s  .c om
            localRepo = Git.cloneRepository().setCredentialsProvider(credentialsProvider)
                    .setDirectory(directory).setURI(uri).call();
            break;
        } catch (TransportException e) {
            // sporadic failure
            FileUtils.deleteFolder(directory);
            if (trys > 3) {
                throw e;
            }
        }
    }
    localRepo.checkout().setCreateBranch(true).setName(branchName).call();
    addTravisFileTo(localRepo, directory, orgName, repoName);
    localRepo.commit().setAll(true).setMessage("Added .travis.yml and badge to README.md").call();
    localRepo.push().setCredentialsProvider(credentialsProvider).call();
}

From source file:io.fabric8.forge.generator.pipeline.JenkinsPipelineLibrary.java

License:Apache License

public static void cloneRepo(File projectFolder, String cloneUrl, CredentialsProvider credentialsProvider,
        final File sshPrivateKey, final File sshPublicKey, String remote, String tag) {
    StopWatch watch = new StopWatch();

    // clone the repo!
    boolean cloneAll = true;
    LOG.info("Cloning git repo " + cloneUrl + " into directory " + projectFolder.getAbsolutePath()
            + " cloneAllBranches: " + cloneAll);
    CloneCommand command = Git.cloneRepository();
    GitUtils.configureCommand(command, credentialsProvider, sshPrivateKey, sshPublicKey);
    command = command.setCredentialsProvider(credentialsProvider).setCloneAllBranches(cloneAll).setURI(cloneUrl)
            .setDirectory(projectFolder).setRemote(remote);

    try {/* w  ww  . j  a  v a 2  s. c o m*/
        Git git = command.call();
        if (tag != null) {
            git.checkout().setName(tag).call();
        }
    } catch (Throwable e) {
        LOG.error("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage(), e);
        throw new RuntimeException("Failed to command remote repo " + cloneUrl + " due: " + e.getMessage());
    } finally {
        LOG.debug("cloneRepo took " + watch.taken());
    }
}

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

License:Apache License

protected void checkoutBranch(Git git, GitContext context) throws GitAPIException {
    String current = currentBranch(git);
    if (Objects.equals(current, branch)) {
        return;/*from   w  w w  . j  a v a2s .  co m*/
    }
    System.out.println("Checking out branch: " + branch);
    // lets check if the branch exists
    CheckoutCommand command = git.checkout().setName(branch);
    boolean exists = localBranchExists(git, branch);
    if (!exists) {
        command = command.setCreateBranch(true).setForce(true)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint(getRemote() + "/" + branch);
    }
    Ref ref = command.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Checked out branch " + branch + " with results " + ref.getName());
    }
    configureBranch(git, branch);
}

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

License:Apache License

/**
 * Performs a pull so the git repo is pretty much up to date before we start performing operations on it.
 *
 * @param git                 The {@link Git} instance to use.
 * @param credentialsProvider The {@link CredentialsProvider} to use.
 * @param doDeleteBranches    Flag that determines if local branches that don't exist in remote should get deleted.
 *///from w  w  w.java 2  s.  c o m
protected void doPull(Git git, CredentialsProvider credentialsProvider, boolean doDeleteBranches) {
    assertValid();
    try {
        Repository repository = git.getRepository();
        StoredConfig config = repository.getConfig();
        String url = config.getString("remote", remoteRef.get(), "url");
        if (Strings.isNullOrBlank(url)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No remote repository defined for the git repository at "
                        + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
            }
            return;
        }
        /*
        String branch = repository.getBranch();
        String mergeUrl = config.getString("branch", branch, "merge");
        if (Strings.isNullOrBlank(mergeUrl)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No merge spec for branch." + branch + ".merge in the git repository at "
                    + GitHelpers.getRootGitDirectory(git) + " so not doing a pull");
        }
        return;
        }
        */
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing a fetch in git repository " + GitHelpers.getRootGitDirectory(git)
                    + " on remote URL: " + url);
        }

        boolean hasChanged = false;
        try {
            FetchResult result = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider)
                    .setRemote(remoteRef.get()).call();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Git fetch result: {}", result.getMessages());
            }
            lastFetchWarning = null;
        } catch (Exception ex) {
            String fetchWarning = ex.getMessage();
            if (!fetchWarning.equals(lastFetchWarning)) {
                LOG.warn("Fetch failed because of: " + fetchWarning);
                LOG.debug("Fetch failed - the error will be ignored", ex);
                lastFetchWarning = fetchWarning;
            }
            return;
        }

        // Get local and remote branches
        Map<String, Ref> localBranches = new HashMap<String, Ref>();
        Map<String, Ref> remoteBranches = new HashMap<String, Ref>();
        Set<String> gitVersions = new HashSet<String>();
        for (Ref ref : git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()) {
            if (ref.getName().startsWith("refs/remotes/" + remoteRef.get() + "/")) {
                String name = ref.getName().substring(("refs/remotes/" + remoteRef.get() + "/").length());
                remoteBranches.put(name, ref);
                gitVersions.add(name);
            } else if (ref.getName().startsWith("refs/heads/")) {
                String name = ref.getName().substring(("refs/heads/").length());
                localBranches.put(name, ref);
                gitVersions.add(name);
            }
        }

        // Check git commits
        for (String version : gitVersions) {
            // Delete unneeded local branches.
            //Check if any remote branches was found as a guard for unwanted deletions.
            if (remoteBranches.isEmpty()) {
                //Do nothing
            } else if (!remoteBranches.containsKey(version)) {
                //We never want to delete the master branch.
                if (doDeleteBranches && !version.equals(MASTER_BRANCH)) {
                    try {
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    } catch (CannotDeleteCurrentBranchException ex) {
                        git.checkout().setName(MASTER_BRANCH).setForce(true).call();
                        git.branchDelete().setBranchNames(localBranches.get(version).getName()).setForce(true)
                                .call();
                    }
                    removeVersion(version);
                    hasChanged = true;
                }
            }
            // Create new local branches
            else if (!localBranches.containsKey(version)) {
                addVersion(version);
                git.checkout().setCreateBranch(true).setName(version)
                        .setStartPoint(remoteRef.get() + "/" + version)
                        .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setForce(true).call();
                hasChanged = true;
            } else {
                String localCommit = localBranches.get(version).getObjectId().getName();
                String remoteCommit = remoteBranches.get(version).getObjectId().getName();
                if (!localCommit.equals(remoteCommit)) {
                    git.clean().setCleanDirectories(true).call();
                    git.checkout().setName("HEAD").setForce(true).call();
                    git.checkout().setName(version).setForce(true).call();
                    MergeResult result = git.merge().setStrategy(MergeStrategy.THEIRS)
                            .include(remoteBranches.get(version).getObjectId()).call();
                    if (result.getMergeStatus() != MergeResult.MergeStatus.ALREADY_UP_TO_DATE
                            && hasChanged(git, localCommit, remoteCommit)) {
                        hasChanged = true;
                    }
                    // TODO: handle conflicts
                }
            }
        }
        if (hasChanged) {
            LOG.debug("Changed after pull!");
            if (credentialsProvider != null) {
                // TODO lets test if the profiles directory is present after checking out version 1.0?
                getProfilesDirectory(git);
            }
            fireChangeNotifications();
        }
    } catch (Throwable ex) {
        LOG.debug("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git), ex);
        LOG.warn("Failed to pull from the remote git repo " + GitHelpers.getRootGitDirectory(git) + " due "
                + ex.getMessage() + ". This exception is ignored.");
    }
}

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

License:Apache License

public static void createOrCheckoutBranch(Git git, String branch, String remote) throws GitAPIException {
    Ref ref = null;/* w  w w  .j a va2 s.co m*/
    String current = currentBranch(git);
    if (!equals(current, branch) && !localBranchExists(git, branch)) {
        ref = git.checkout().setName(branch).setForce(true).setCreateBranch(true).call();
        if (remote != null) {
            configureBranch(git, branch, remote);
        }
    } else {
        ref = git.checkout().setName(branch).setForce(true).call();
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Checked out branch " + branch + " with results " + ref.getName());
    }
}

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

License:Apache License

public static boolean checkoutBranch(Git git, String branch) throws GitAPIException {
    String current = currentBranch(git);
    if (equals(current, branch)) {
        return true;
    } else if (localBranchExists(git, branch)) {
        Ref ref = git.checkout().setName(branch).setForce(true).call();
        LOGGER.debug("Checked out branch {} with results: ", branch, ref.getName());
        return true;
    } else {//from ww w  .ja v a  2  s .co m
        LOGGER.debug("Branch {} not found!", branch);
        return false;
    }
}