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

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

Introduction

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

Prototype

public CommitCommand commit() 

Source Link

Document

Return a command object to execute a Commit command

Usage

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

License:Apache License

/**
 * @throws AuthenticationException // www .ja  v a2 s . c o  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

/**
 * @throws MergeFailure /*from  w  w w.  j a va  2  s  . c  o  m*/
 * @throws AuthenticationException 
 * @see gov.va.isaac.interfaces.sync.ProfileSyncI#updateCommitAndPush(java.io.File, java.lang.String, java.lang.String, java.lang.String,
 * java.lang.String[])
 */
@Override
public Set<String> updateCommitAndPush(String commitMessage, String username, String password,
        MergeFailOption mergeFailOption, String... files)
        throws IllegalArgumentException, IOException, MergeFailure, AuthenticationException {
    try {
        log.info("Commit Files called {}", (files == null ? "-null-" : Arrays.toString(files)));
        Git git = getGit();

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

        if (files == null) {
            files = git.status().call().getUncommittedChanges().toArray(new String[0]);
            log.info("Will commit the uncommitted files {}", Arrays.toString(files));
        }

        if (StringUtils.isEmptyOrNull(commitMessage) && files.length > 0) {
            throw new IllegalArgumentException("The commit message is required when files are specified");
        }

        if (files.length > 0) {
            CommitCommand commit = git.commit();
            for (String file : files) {
                commit.setOnly(file);
            }

            commit.setAuthor(username, "42");
            commit.setMessage(commitMessage);
            RevCommit rv = commit.call();
            log.debug("Local commit completed: " + rv.getFullMessage());
        }

        //need to merge origin/master into master now, prior to push
        Set<String> result = updateFromRemote(username, password, mergeFailOption);

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

        Iterable<PushResult> pr = git.push().setCredentialsProvider(cp).call();
        pr.forEach(new Consumer<PushResult>() {
            @Override
            public void accept(PushResult t) {
                log.debug("Push Result Messages: " + t.getMessages());
            }
        });

        log.info("commit and push complete.  Current status: " + statusToString(git.status().call()));
        return result;
    } 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 a 2 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:info.debatty.jinu.Case.java

License:Open Source License

private void commitToGit(final String time_tag) {
    try {//from   w w w . j a v a  2 s  .c  o m
        Repository repo = new FileRepositoryBuilder().findGitDir().build();

        Git git = new Git(repo);
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage("Test case " + time_tag).call();
        git.tag().setName("T" + time_tag).call();
    } catch (Exception ex) {
        System.err.println("Could not commit GIT repo");
        System.err.println(ex.getMessage());
    }
}

From source file:info.plichta.maven.plugins.changelog.RepositoryProcessorTest.java

License:Apache License

private RevCommit commitWithFile(Git git, String commit) throws IOException, GitAPIException {
    writeTrashFile(commit, commit);//from  w w w.  ja v  a2s.c o m
    git.add().addFilepattern(commit).call();
    return git.commit().setMessage(commit).setAll(true).call();
}

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  www .java 2s. co m
            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.collector.git.GitCollectorTest.java

License:Apache License

@Test
public void testCollectionPopulatesElasticSearch() throws Exception {
    GitElasticsearchClient elasticsearchClient = new GitElasticsearchClient("http://127.0.0.1/",
            elasticsearchPort, null, null);
    File cloneFolder = new File(getBaseDir(), "target/test-git-clone/sample");
    Files.recursiveDelete(cloneFolder);
    cloneFolder.getParentFile().mkdirs();

    GitBuildConfigProcessor processor = new GitBuildConfigProcessor(elasticsearchClient, cloneFolder,
            commitLimit);//from  w ww  . java2s  . c  o m

    assertProcessGitrepoCommits(processor, 2, true);
    assertProcessGitrepoCommits(processor, 2, true);
    assertProcessGitrepoCommits(processor, 1, true);
    assertProcessGitrepoCommits(processor, 0, true);

    // now lets make a commit and check we get a new item pushed to ES
    File projectDir = new File(cloneFolder, namespaceName.getNamespace() + "/" + namespaceName.getName());

    Files.writeToFile(new File(projectDir, "README.md"), "Dummy-commit!".getBytes());
    Git git = gitFromGitFolder(new File(projectDir, ".git"));
    git.commit().setMessage("Dummy test commit").call();

    System.out.println("Just done a commit!");

    assertProcessGitrepoCommits(processor, 1, true);
    assertProcessGitrepoCommits(processor, 0, true);
}

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

License:Apache License

public static RevCommit doCommitAndPush(Git git, String message, UserDetails userDetails, PersonIdent author,
        String branch, String origin, boolean pushOnCommit) throws GitAPIException {
    CommitCommand commit = git.commit().setAll(true).setMessage(message);
    if (author != null) {
        commit = commit.setAuthor(author);
    }/*  w  w  w  .j  av  a  2 s  . c o m*/

    RevCommit answer = commit.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
    }

    if (pushOnCommit) {
        PushCommand push = git.push();
        configureCommand(push, userDetails);
        Iterable<PushResult> results = push.setRemote(origin).call();
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch
                        + " updates: " + toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;
}

From source file:io.fabric8.forge.rest.client.ForgeTestSupport.java

License:Apache License

protected Build assertCodeChangeTriggersWorkingBuild(JenkinsServer jenkins, String jenkinsUrl,
        final String projectName, Build firstBuild, String folderName) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {//from   w ww.  ja  va2  s  .  c  om
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }

    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent())
            .setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;

    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JenkinsServer jenkins = createJenkinsServer(forgeClient.getKubernetesClient(), jenkinsNamespace);
            JobWithDetails job = assertJob(jenkins, folderName, projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber())
                    .describedAs("Waiting for latest build for job " + projectName + " to start")
                    .isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(jenkins, jenkinsUrl, folderName, projectName);
}

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

License:Apache License

protected CommitInfo doCreateDirectory(Git git, String path) throws Exception {
    File file = getRelativeFile(path);
    if (file.exists()) {
        return null;
    }//from www.j av a 2s  .com
    file.mkdirs();
    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
    RevCommit revCommit = commitThenPush(git, commit);
    return createCommitInfo(revCommit);
}