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.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPush() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master.git");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).setBare(true).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();//www  .  j  ava  2 s . co m
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(cloneRepoDir, "test");
    testFile.createNewFile();

    cloneGit.add().addFilepattern("test").call();
    cloneGit.commit().setMessage("Test message").call();

    cloneRepo.push();

    List<RevCommit> commits = IterableUtils.toList(masterGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(masterGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}

From source file:org.craftercms.commons.git.impl.GitRepositoryImplTest.java

License:Open Source License

@Test
public void testPull() throws Exception {
    File masterRepoDir = tmpDir.newFolder("master");
    File cloneRepoDir = tmpDir.newFolder("clone");

    Git masterGit = Git.init().setDirectory(masterRepoDir).call();
    Git cloneGit = Git.cloneRepository().setURI(masterRepoDir.getCanonicalPath()).setDirectory(cloneRepoDir)
            .call();/*  ww w.  j  av  a2 s.c o  m*/
    GitRepositoryImpl cloneRepo = new GitRepositoryImpl(cloneGit);

    File testFile = new File(masterRepoDir, "test");
    testFile.createNewFile();

    masterGit.add().addFilepattern("test").call();
    masterGit.commit().setMessage("Test message").call();

    cloneRepo.pull();

    List<RevCommit> commits = IterableUtils.toList(cloneGit.log().all().call());

    assertNotNull(commits);
    assertEquals(1, commits.size());
    assertEquals("Test message", commits.get(0).getFullMessage());

    List<String> committedFiles = getCommittedFiles(cloneGit.getRepository(), commits.get(0));

    assertNotNull(committedFiles);
    assertEquals(1, committedFiles.size());
    assertEquals("test", committedFiles.get(0));
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void checkoutEnvironment(Repository repository, String site) {
    Git git = null;
    try {/*from   w ww  .j  a va 2s  . c o  m*/
        Ref branchRef = repository.findRef(environment);
        git = new Git(repository);
        git.checkout().setCreateBranch(true).setName(environment)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
                .setStartPoint("origin/" + environment).call();
        git.fetch().call();
        git.pull().call();
    } catch (RefNotFoundException e) {
        try {
            git.checkout().setOrphan(true).setName(environment).call();
            ProcessBuilder pb = new ProcessBuilder();
            pb.command("git", "rm", "-rf", ".");
            pb.directory(repository.getDirectory().getParentFile());
            Process p = pb.start();
            p.waitFor();

            git.commit().setMessage("initial content").setAllowEmpty(true).call();
        } catch (GitAPIException | InterruptedException | IOException e1) {
            logger.error("Error checking out environment store branch for site " + site + " environment "
                    + environment, e1);
        }
    } catch (IOException | GitAPIException e) {
        logger.error(
                "Error checking out environment store branch for site " + site + " environment " + environment,
                e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private void pushChanges(Repository repository) {
    Git git = new Git(repository);
    try {//from  w  w w  .jav a  2  s.c o m
        git.add().addFilepattern(".").call();
        git.commit().setMessage("deployment to environment store").call();
        git.push().call();
    } catch (GitAPIException e) {
        logger.error("Error while pushing workflow changes.", e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

private boolean createEnvironmentStoreRepository(String site) {
    boolean success = true;
    Path siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment);
    try {//from   w  w w.  j a  va  2 s  .c o  m
        Files.deleteIfExists(siteEnvironmentStoreRepoPath);
        siteEnvironmentStoreRepoPath = Paths.get(environmentsStoreRootPath, site, environment, ".git");
        Repository repository = FileRepositoryBuilder.create(siteEnvironmentStoreRepoPath.toFile());
        repository.create();

        Git git = new Git(repository);
        git.add().addFilepattern(".").call();
        RevCommit commit = git.commit().setMessage("initial content").setAllowEmpty(true).call();
    } catch (IOException | GitAPIException e) {
        logger.error("Error while creating repository for site " + site, e);
        success = false;
    }
    return success;
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

License:Open Source License

@Override
public void deleteFile(String site, String path) {
    try {/*from www .  jav  a  2s .  c o  m*/
        Repository repo = getEnvironmentStoreRepositoryInstance(site);
        Git git = new Git(repo);
        git.rm().addFilepattern(getGitPath(path)).setCached(false).call();

        RevCommit commit = git.commit().setOnly(getGitPath(path)).setMessage(StringUtils.EMPTY).call();
    } catch (GitAPIException | IOException | JGitInternalException e) {
        logger.error("Error while deleting content from environment store for site: " + site + " path: " + path
                + " environment: " + environment, e);
    }
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitDeployer.java

License:Open Source License

@Override
public void deployFile(String site, String path) {
    try (Repository envStoreRepo = getEnvironmentStoreRepositoryInstance(site)) {
        fetchFromRemote(site, envStoreRepo);
        createPatch(envStoreRepo, site, path);
        Git git = new Git(envStoreRepo);
        applyPatch(envStoreRepo, site);/*from   w  w  w  .  ja va 2  s  .  co m*/
        git.add().addFilepattern(".").call();
        git.commit().setMessage("deployment").call();

    } catch (IOException | GitAPIException e) {
        logger.error("Error while deploying file for site: " + site + " path: " + path, e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

License:Open Source License

/**
 * Perform an initial commit after large changes to a site. Will not work against the global config repo.
 * @param site/*from ww w.  j  a va 2 s .  c o m*/
 * @param message
 * @return true if successful, false otherwise
 */
public boolean performInitialCommit(String site, String message) {
    boolean toReturn = true;

    try {
        Repository repo = getRepository(site, GitRepositories.SANDBOX);

        Git git = new Git(repo);

        Status status = git.status().call();

        if (status.hasUncommittedChanges() || !status.isClean()) {
            DirCache dirCache = git.add().addFilepattern(GIT_COMMIT_ALL_ITEMS).call();
            RevCommit commit = git.commit().setMessage(message).call();
            // TODO: SJ: Do we need the commit id?
            // commitId = commit.getName();
        }
    } catch (GitAPIException err) {
        logger.error("error creating initial commit for site:  " + site, err);
        toReturn = false;
    }

    return toReturn;
}

From source file:org.debian.dependency.sources.TestJGitSource.java

License:Apache License

/**
 * We should be able to create a git repo over top of other version control systems, public void testInitOtherVcs() throws
 * Exception { }// w  w w.  ja v  a2  s  .c om
 *
 * /** When cleaning the source, we must take into account all types of dirty file states.
 */
@Test
public void testClean() throws Exception {
    Git git = Git.open(directory);

    File.createTempFile("unchanged", "file", directory);

    File subChanged = new File(new File(directory, "directory"), "changed");
    subChanged.getParentFile().mkdirs();
    subChanged.createNewFile();
    File changed = File.createTempFile("changed", "file", directory);

    git.add().addFilepattern(".").call();
    git.commit().setMessage("Prepare for test").call();

    source.initialize(directory, ORIGIN);

    Files.write("some data", subChanged, Charset.defaultCharset());
    Files.write("more data", changed, Charset.defaultCharset());
    File.createTempFile("new", "file", directory);

    File untrackedDir = new File(directory, "untracked");
    untrackedDir.mkdirs();
    File.createTempFile("another", "file", untrackedDir);

    source.clean();

    Status status = git.status().call();
    assertThat(status.getUntracked(), hasSize(0));
    assertThat(status.getUntrackedFolders(), hasSize(0));
    assertThat(status.getIgnoredNotInIndex(), hasSize(0));
    assertTrue("No changes", status.isClean());
}

From source file:org.eclipse.egit.core.op.CommitOperation.java

License:Open Source License

public void execute(IProgressMonitor m) throws CoreException {
    IProgressMonitor monitor;/*from  w w w. ja va2  s . c o m*/
    if (m == null)
        monitor = new NullProgressMonitor();
    else
        monitor = m;
    IWorkspaceRunnable action = new IWorkspaceRunnable() {

        public void run(IProgressMonitor actMonitor) throws CoreException {
            final Date commitDate = new Date();
            final TimeZone timeZone = TimeZone.getDefault();
            final PersonIdent authorIdent = RawParseUtils.parsePersonIdent(author);
            final PersonIdent committerIdent = RawParseUtils.parsePersonIdent(committer);
            if (commitAll) {
                for (Repository repo : repos) {
                    Git git = new Git(repo);
                    try {
                        git.commit().setAll(true).setAuthor(new PersonIdent(authorIdent, commitDate, timeZone))
                                .setCommitter(new PersonIdent(committerIdent, commitDate, timeZone))
                                .setMessage(message).call();
                    } catch (NoHeadException e) {
                        throw new TeamException(e.getLocalizedMessage(), e);
                    } catch (NoMessageException e) {
                        throw new TeamException(e.getLocalizedMessage(), e);
                    } catch (UnmergedPathException e) {
                        throw new TeamException(e.getLocalizedMessage(), e);
                    } catch (ConcurrentRefUpdateException e) {
                        throw new TeamException(CoreText.MergeOperation_InternalError, e);
                    } catch (JGitInternalException e) {
                        throw new TeamException(CoreText.MergeOperation_InternalError, e);
                    } catch (WrongRepositoryStateException e) {
                        throw new TeamException(e.getLocalizedMessage(), e);
                    }
                }
            }

            else if (amending || filesToCommit != null && filesToCommit.length > 0) {
                actMonitor.beginTask(CoreText.CommitOperation_PerformingCommit, filesToCommit.length * 2);
                actMonitor.setTaskName(CoreText.CommitOperation_PerformingCommit);
                HashMap<Repository, Tree> treeMap = new HashMap<Repository, Tree>();
                try {
                    if (!prepareTrees(filesToCommit, treeMap, actMonitor)) {
                        // reread the indexes, they were changed in memory
                        for (Repository repo : treeMap.keySet())
                            repo.getIndex().read();
                        return;
                    }
                } catch (IOException e) {
                    throw new TeamException(CoreText.CommitOperation_errorPreparingTrees, e);
                }

                try {
                    doCommits(message, treeMap);
                    actMonitor.worked(filesToCommit.length);
                } catch (IOException e) {
                    throw new TeamException(CoreText.CommitOperation_errorCommittingChanges, e);
                }
            } else if (commitWorkingDirChanges) {
                // TODO commit -a
            } else {
                // TODO commit
            }
        }
    };
    ResourcesPlugin.getWorkspace().run(action, monitor);
}