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:org.fusesource.fabric.itests.basic.git.FabricGitTestSupport.java

License:Apache License

/**
 * Create a profile in git and check that its bridged to the registry.
 *
 * @param git     The git object of the test repository.
 * @param version The version of the profile.
 * @param profile The profile name./*from  w w  w  . jav a 2s. c om*/
 * @throws Exception
 */
public void createAndTestProfileInGit(Git git, String version, String profile) throws Exception {
    //Create the test profile in git
    System.err.println("Create test profile:" + profile + " in git.");
    GitUtils.checkoutBranch(git, "origin", version);
    File testProfileDir = new File(git.getRepository().getWorkTree(), profile);
    testProfileDir.mkdirs();
    File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
    testProfileConfig.createNewFile();
    Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
    git.add().addFilepattern(profile).call();
    git.commit().setMessage("Create " + profile).call();
    PullResult pullResult = git.pull().setCredentialsProvider(getCredentialsProvider()).setRebase(true).call();
    git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
    GitUtils.waitForBranchUpdate(getCurator(), version);
    //Check that it has been bridged in zookeeper
    Thread.sleep(5000);
    assertNotNull(getCurator().checkExists().forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath(version, profile)));
}

From source file:org.fusesource.fabric.itests.basic.git.GitBridgeTest.java

License:Apache License

public void testWithProfiles() throws Exception {
    String testProfileNameBase = "mytestprofile-";
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(1, 1).withName("child").assertProvisioningResult()
            .build();//from   w w  w.j  a va 2 s.  com
    String gitRepoUrl = GitUtils.getMasterUrl(getCurator());

    GitUtils.waitForBranchUpdate(getCurator(), "1.0");

    Git.cloneRepository().setURI(gitRepoUrl).setCloneAllBranches(true).setDirectory(testrepo)
            .setCredentialsProvider(getCredentialsProvider()).call();
    Git git = Git.open(testrepo);
    GitUtils.configureBranch(git, "origin", gitRepoUrl, "1.0");
    git.fetch().setCredentialsProvider(getCredentialsProvider());
    GitUtils.checkoutBranch(git, "origin", "1.0");

    //Check that the default profile exists
    assertTrue(new File(testrepo, "default").exists());

    //Create test profile
    for (int i = 1; i <= 3; i++) {
        String testProfileName = testProfileNameBase + i;
        System.err.println("Create test profile:" + testProfileName + " in zookeeper");
        getFabricService().getVersion("1.0").createProfile(testProfileName);
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        git.pull().setRebase(true).setCredentialsProvider(getCredentialsProvider()).call();
        //Check that a newly created profile exists
        assertTrue(new File(testrepo, testProfileName).exists());
        //Delete test profile
        System.err.println("Delete test profile:" + testProfileName + " in git.");
        git.rm().addFilepattern(testProfileName).call();
        git.commit().setMessage("Delete " + testProfileName).call();
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        Thread.sleep(5000);
        assertFalse(new File(testrepo, testProfileName).exists());
        assertNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));

        //Create the test profile in git
        System.err.println("Create test profile:" + testProfileName + " in git.");
        File testProfileDir = new File(testrepo, testProfileName);
        testProfileDir.mkdirs();
        File testProfileConfig = new File(testProfileDir, "org.fusesource.fabric.agent.properties");
        testProfileConfig.createNewFile();
        Files.writeToFile(testProfileConfig, "", Charset.defaultCharset());
        git.add().addFilepattern(testProfileName).call();
        RevCommit commit = git.commit().setMessage("Create " + testProfileName).call();
        FileTreeIterator fileTreeItr = new FileTreeIterator(git.getRepository());
        IndexDiff indexDiff = new IndexDiff(git.getRepository(), commit.getId(), fileTreeItr);
        System.out.println(indexDiff.getChanged());
        System.out.println(indexDiff.getAdded());
        git.push().setCredentialsProvider(getCredentialsProvider()).setRemote("origin").call();
        GitUtils.waitForBranchUpdate(getCurator(), "1.0");
        //Check that it has been bridged in zookeeper
        Thread.sleep(15000);
        assertNotNull(getCurator().checkExists()
                .forPath(ZkPath.CONFIG_VERSIONS_PROFILE.getPath("1.0", testProfileName)));
    }
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Add file to test repository//w w w.  j a  va2  s  . c  om
 *
 * @param repo
 * @param path
 * @param content
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit add(File repo, String path, String content, String message) throws Exception {
    File file = new File(repo.getParentFile(), path);
    if (!file.getParentFile().exists())
        assertTrue(file.getParentFile().mkdirs());
    if (!file.exists())
        assertTrue(file.createNewFile());
    PrintWriter writer = new PrintWriter(file);
    if (content == null)
        content = "";
    try {
        writer.print(content);
    } finally {
        writer.close();
    }
    Git git = Git.open(repo);
    git.add().addFilepattern(path).call();
    RevCommit commit = git.commit().setOnly(path).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Move file in test repository//from   w  w  w . j  a  v a 2 s  .  c om
 *
 * @param repo
 * @param from
 * @param to
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit mv(File repo, String from, String to, String message) throws Exception {
    File file = new File(repo.getParentFile(), from);
    file.renameTo(new File(repo.getParentFile(), to));
    Git git = Git.open(repo);
    git.rm().addFilepattern(from);
    git.add().addFilepattern(to).call();
    RevCommit commit = git.commit().setAll(true).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Add files to test repository/*ww w  . j  a v  a 2  s. co m*/
 *
 * @param repo
 * @param paths
 * @param contents
 * @param message
 * @return commit
 * @throws Exception
 */
protected RevCommit add(File repo, List<String> paths, List<String> contents, String message) throws Exception {
    Git git = Git.open(repo);
    for (int i = 0; i < paths.size(); i++) {
        String path = paths.get(i);
        String content = contents.get(i);
        File file = new File(repo.getParentFile(), path);
        if (!file.getParentFile().exists())
            assertTrue(file.getParentFile().mkdirs());
        if (!file.exists())
            assertTrue(file.createNewFile());
        PrintWriter writer = new PrintWriter(file);
        if (content == null)
            content = "";
        try {
            writer.print(content);
        } finally {
            writer.close();
        }
        git.add().addFilepattern(path).call();
    }
    RevCommit commit = git.commit().setMessage(message).setAuthor(author).setCommitter(committer).call();
    assertNotNull(commit);
    return commit;
}

From source file:org.gitective.tests.GitTestCase.java

License:Open Source License

/**
 * Delete and commit file at path/* www  .  j a v  a2s. c o m*/
 *
 * @param path
 * @return commit
 * @throws Exception
 */
protected RevCommit delete(String path) throws Exception {
    String message = MessageFormat.format("Committing {0} at {1}", path, new Date());
    Git git = Git.open(testRepo);
    git.rm().addFilepattern(path).call();
    RevCommit commit = git.commit().setOnly(path).setMessage(message).setAuthor(author).setCommitter(committer)
            .call();
    assertNotNull(commit);
    return commit;
}

From source file:org.guvnor.ala.build.maven.executor.MavenTestUtils.java

License:Apache License

public static String createGitRepoWithPom(final File path, final InputStream pom, final File... files)
        throws Exception {
    File repo = new File(path, "repo");
    if (repo.exists() == false) {
        Files.createDirectory(repo.toPath());
    }//from w w w  .  ja va2  s.c  o  m
    Git git = Git.init().setDirectory(repo).call();
    String gitUrl = "file://" + repo.getAbsolutePath();

    FileUtils.copyInputStreamToFile(pom, new File(repo, "pom.xml"));
    AddCommand add = git.add();
    add.addFilepattern("pom.xml");
    for (File f : files) {
        add.addFilepattern(f.getName());
    }
    add.call();
    CommitCommand commit = git.commit();
    commit.setMessage("initial commit").call();
    return gitUrl;
}

From source file:org.ihtsdo.ttk.services.sync.Example.java

License:Apache License

/**
 * Method description/*from   www.j a  va 2s.  co  m*/
 *
 *
 * @param args
 */
public static void main(String[] args) {
    try {

        // jGit provides the ability to manage the git repositories from 
        // your code in a very easy manner. For example, to create the new 
        // repository, you just have to indicate the target directory:
        File targetDir = new File("target/newRepository.git");
        Repository repo = new FileRepository(targetDir);
        repo.create(true);

        //Cloning the existing git repository is also very easy and nice:
        Git.cloneRepository().setURI(targetDir.toURI().toString()).setDirectory(new File("target/working-copy"))
                .setBranch("master").setBare(false).setRemote("origin").setNoCheckout(false).call();

        // And here is the way how you can add the changes, 
        // commit and push them to the origin:
        Git git = new Git(new FileRepository(new File("target/working-copy")));
        git.add().addFilepattern(".").call();
        git.commit().setMessage("some comment").call();
        git.push().setPushAll().setRemote("origin").call();

        // http://jzelenkov.com/post/35653947951/diving-into-jgit

        // http://download.eclipse.org/jgit/docs/jgit-2.0.0.201206130900-r/apidocs/org/eclipse/jgit/api/package-summary.html

        // http://blogs.atlassian.com/2013/04/git-flow-comes-to-java/
    } catch (IOException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    } catch (GitAPIException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jabylon.team.git.GitTeamProvider.java

License:Open Source License

@Override
public void commit(ProjectVersion project, IProgressMonitor monitor) throws TeamProviderException {
    try {//from  w w  w  . ja  v  a 2  s. co m
        Repository repository = createRepository(project);
        SubMonitor subMon = SubMonitor.convert(monitor, "Commit", 100);
        Git git = new Git(repository);
        // AddCommand addCommand = git.add();
        List<String> changedFiles = addNewFiles(git, subMon.newChild(30));
        if (!changedFiles.isEmpty()) {
            checkCanceled(subMon);
            CommitCommand commit = git.commit();
            Preferences node = PreferencesUtil.scopeFor(project.getParent());
            String username = node.get(GitConstants.KEY_USERNAME, "Jabylon");
            String email = node.get(GitConstants.KEY_EMAIL, "jabylon@example.org");
            String message = node.get(GitConstants.KEY_MESSAGE, "Auto Sync-up by Jabylon");
            boolean insertChangeId = node.getBoolean(GitConstants.KEY_INSERT_CHANGE_ID, false);
            commit.setAuthor(username, email);
            commit.setCommitter(username, email);
            commit.setInsertChangeId(insertChangeId);
            commit.setMessage(message);
            for (String path : changedFiles) {
                checkCanceled(subMon);
                commit.setOnly(path);

            }
            commit.call();
            subMon.worked(10);
        } else {
            LOGGER.info("No changed files, skipping commit phase");
        }
        checkCanceled(subMon);
        PushCommand push = git.push();
        URI uri = project.getParent().getRepositoryURI();
        if (uri != null)
            push.setRemote(stripUserInfo(uri).toString());
        push.setProgressMonitor(new ProgressMonitorWrapper(subMon.newChild(60)));
        if (!"https".equals(uri.scheme()) && !"http".equals(uri.scheme()))
            push.setTransportConfigCallback(createTransportConfigCallback(project.getParent()));
        push.setCredentialsProvider(createCredentialsProvider(project.getParent()));

        RefSpec spec = createRefSpec(project);
        push.setRefSpecs(spec);

        Iterable<PushResult> result = push.call();
        for (PushResult r : result) {
            for (RemoteRefUpdate rru : r.getRemoteUpdates()) {
                if (rru.getStatus() != RemoteRefUpdate.Status.OK
                        && rru.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE) {
                    String error = "Push failed: " + rru.getStatus();
                    LOGGER.error(error);
                    throw new TeamProviderException(error);
                }
            }
        }

        Ref ref = repository.getRef(project.getName());
        if (ref != null) {
            LOGGER.info("Successfully pushed {} to {}", ref.getObjectId(),
                    project.getParent().getRepositoryURI());
        }
    } catch (NoHeadException e) {
        throw new TeamProviderException(e);
    } catch (NoMessageException e) {
        throw new TeamProviderException(e);
    } catch (ConcurrentRefUpdateException e) {
        throw new TeamProviderException(e);
    } catch (JGitInternalException e) {
        throw new TeamProviderException(e);
    } catch (WrongRepositoryStateException e) {
        throw new TeamProviderException(e);
    } catch (InvalidRemoteException e) {
        throw new TeamProviderException(e);
    } catch (IOException e) {
        throw new TeamProviderException(e);
    } catch (GitAPIException e) {
        throw new TeamProviderException(e);
    } finally {
        if (monitor != null)
            monitor.done();
    }
}

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

License:Open Source License

@Override
public void commit(final Git repo, String message) throws GitAPIException {
    repo.commit().setMessage(message).call();
}