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.komodo.rest.service.KomodoImportExportServiceTest.java

License:Open Source License

private void initGitRepository() throws Exception {
    String tmpDirPath = System.getProperty("java.io.tmpdir");
    File tmpDir = new File(tmpDirPath);

    long timestamp = System.currentTimeMillis();
    myGitDir = new File(tmpDir, "mygit-" + timestamp);
    assertTrue(myGitDir.mkdir());//from   w ww .j  ava 2s  . c om

    myGit = Git.init().setDirectory(myGitDir).setBare(true).call();
    assertNotNull(myGit);

    // Need to initialise the master branch
    // as jgit does not automatically create on
    File seedDir = new File(tmpDir, "seedDir-" + timestamp);
    Git seedGit = Git.cloneRepository().setURI(myGitDir.getAbsolutePath()).setDirectory(seedDir).call();

    File tweetVdbFile = new File(seedDir,
            TestUtilities.TWEET_EXAMPLE_NAME + TestUtilities.TWEET_EXAMPLE_SUFFIX);
    assertTrue(tweetVdbFile.createNewFile());
    FileUtils.write(TestUtilities.tweetExample(), tweetVdbFile);
    assertTrue(tweetVdbFile.length() > 0);

    File usStatesZipFile = new File(tmpDir, TestUtilities.US_STATES_DATA_SERVICE_NAME + ZIP_SUFFIX);
    FileUtils.write(TestUtilities.usStatesDataserviceExample(), usStatesZipFile);
    try (FileInputStream fis = new FileInputStream(usStatesZipFile)) {
        File usStatesDir = new File(seedDir, TestUtilities.US_STATES_DATA_SERVICE_NAME);
        usStatesDir.mkdir();
        FileUtils.zipExtract(fis, usStatesDir);
        usStatesZipFile.delete();
    }

    seedGit.add().addFilepattern(DOT).call();
    seedGit.commit().setMessage("First Commit").call();
    seedGit.push().call();

    FileUtils.removeDirectoryAndChildren(seedDir);

    //
    // Local git repository
    //
    String dirName = System.currentTimeMillis() + HYPHEN;
    gitRepoDest = new File(FileUtils.tempDirectory(), dirName);
    gitRepoDest.mkdir();
}

From source file:org.komodo.storage.git.TestGitStorageConnector.java

License:Open Source License

@Before
public void setup() throws Exception {
    String tmpDirPath = System.getProperty("java.io.tmpdir");
    tmpDir = new File(tmpDirPath);

    timestamp = System.currentTimeMillis();
    myGitDir = new File(tmpDir, "mygit-" + timestamp);
    assertTrue(myGitDir.mkdir());/* w ww .ja va2 s  . com*/

    myGit = Git.init().setDirectory(myGitDir).setBare(true).call();
    assertNotNull(myGit);

    //
    // Create a clone to seed the repository with a file
    //
    File seedDir = new File(tmpDir, "seedDir-" + timestamp);
    Git seedGit = Git.cloneRepository().setURI(myGitDir.getAbsolutePath()).setDirectory(seedDir).call();

    // Adds a file into the seed repository
    File vdbFile = new File(seedDir, TEST_VDB_XML);
    assertTrue(vdbFile.createNewFile());
    FileUtils.write(TestUtilities.tweetExample(), vdbFile);
    assertTrue(vdbFile.length() > 0);

    File subDir = new File(seedDir, SUB_DIR);
    assertTrue(subDir.mkdir());

    File subDirVdbFile = new File(subDir, TEST_VDB_3_XML);
    assertTrue(subDirVdbFile.createNewFile());
    FileUtils.write(TestUtilities.tweetExample(), subDirVdbFile);
    assertTrue(subDirVdbFile.length() > 0);

    File usStatesZipFile = new File(tmpDir, TestUtilities.US_STATES_VDB_NAME + ZIP_SUFFIX);
    FileUtils.write(TestUtilities.usStatesDataserviceExample(), usStatesZipFile);
    try (FileInputStream fis = new FileInputStream(usStatesZipFile)) {
        File usStatesDir = new File(seedDir, TestUtilities.US_STATES_VDB_NAME);
        usStatesDir.mkdir();
        FileUtils.zipExtract(fis, usStatesDir);
        usStatesZipFile.delete();
    }

    seedGit.add().addFilepattern(DOT).call();
    seedGit.commit().setMessage("Adds Test Files").call();
    seedGit.push().call();

    FileUtils.removeDirectoryAndChildren(seedDir);
}

From source file:org.kuali.student.git.model.TestKSCMContribImport.java

License:Educational Community License

private void setupBase()
        throws FileNotFoundException, IOException, PatchFormatException, PatchApplyException, GitAPIException {

    /*/*www . j ava  2  s .c  o m*/
     * Create the repository and apply the base patch for the source branch.
     * 
     * Also create the Subversion Revision Meta Data.
     */

    ExternalGitUtils.applyPatch("git", repository,
            new BZip2CompressorInputStream(new FileInputStream("src/test/resources/ks-r53642-base.patch.bz2")),
            System.out);

    Git git = new Git(repository);

    DirCache dircache = git.add().addFilepattern(".").call();

    RevCommit result = git.commit().setMessage("create sandbox_ksenroll-8475@53642 base")
            .setCommitter("name", "email").call();

    GitTreeProcessor processor = new GitTreeProcessor(repository);

    GitTreeData tree = processor.extractExistingTreeDataFromCommit(result);

    Assert.assertNotNull(tree.find(repository, "CM"));
    Assert.assertNotNull(tree.find(repository, "aggregate"));

    Ref sandboxBranchRef = git.checkout().setStartPoint("master").setName("sandbox_ksenroll-8475")
            .setCreateBranch(true).call();

    Assert.assertNotNull(sandboxBranchRef);

}

From source file:org.lab41.dendrite.web.controller.GraphExportController.java

License:Apache License

@RequestMapping(value = "/api/graphs/{graphId}/file-save", method = RequestMethod.POST)
public ResponseEntity<Map<String, Object>> save(@PathVariable String graphId, @Valid GraphExportBean item,
        BindingResult result) throws IOException, GitAPIException {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    Map<String, Object> response = new HashMap<>();

    if (result.hasErrors()) {
        response.put("status", "error");
        response.put("msg", result.toString());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }/* www  .  j  ava2  s .  c om*/

    MetaGraphTx metaGraphTx = metaGraphService.buildTransaction().readOnly().start();
    GraphMetadata graphMetadata;
    Git git;

    try {
        graphMetadata = metaGraphTx.getGraph(graphId);
        git = historyService.projectGitRepository(graphMetadata.getProject());
        metaGraphTx.commit();
    } catch (Throwable t) {
        metaGraphTx.rollback();
        throw t;
    }

    DendriteGraph graph = metaGraphService.getGraph(graphId);
    if (graph == null) {
        response.put("status", "error");
        response.put("msg", "cannot find graph '" + graphId + "'");
        return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
    }

    logger.debug("saving graph '" + graphId + "'");

    // extract the storage location for the history
    String format = item.getFormat();

    DendriteGraphTx tx = graph.buildTransaction().readOnly().start();

    try {
        try {
            String path;

            if (format.equalsIgnoreCase("GraphSON")) {
                path = new File(git.getRepository().getWorkTree(), graphId + ".json").getPath();
                GraphSONWriter.outputGraph(tx, path);
            } else if (format.equalsIgnoreCase("GraphML")) {
                path = new File(git.getRepository().getWorkTree(), graphId + ".xml").getPath();
                GraphMLWriter.outputGraph(tx, path);
            } else if (format.equalsIgnoreCase("GML")) {
                path = new File(git.getRepository().getWorkTree(), graphId + ".gml").getPath();
                GMLWriter.outputGraph(tx, path);
            } else {
                tx.rollback();

                response.put("status", "error");
                response.put("msg", "unknown format '" + format + "'");
                return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
            }

            git.add().addFilepattern(".").call();

            git.commit().setAuthor(authentication.getName(), "").setMessage("commit").call();
        } finally {
            git.close();
        }
    } catch (IOException e) {
        tx.rollback();

        response.put("status", "error");
        response.put("msg", "exception: " + e.toString());
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }

    tx.commit();

    response.put("status", "ok");

    return new ResponseEntity<>(response, HttpStatus.NO_CONTENT);
}

From source file:org.moxie.ant.Main.java

License:Apache License

private void initGit() throws GitAPIException {
    // create the repository
    InitCommand init = Git.init();//from w  w  w.  jav  a 2  s. com
    init.setBare(false);
    init.setDirectory(newProject.dir);
    Git git = init.call();

    if (!StringUtils.isEmpty(newProject.gitOrigin)) {
        // set the origin and configure the master branch for merging 
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", "origin", "url", getGitUrl());
        config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
        config.setString("branch", "master", "remote", "origin");
        config.setString("branch", "master", "merge", "refs/heads/master");
        try {
            config.save();
        } catch (IOException e) {
            throw new MoxieException(e);
        }
    }

    // prepare a common gitignore file
    StringBuilder sb = new StringBuilder();
    sb.append("/.directory\n");
    sb.append("/.DS_STORE\n");
    sb.append("/.DS_Store\n");
    sb.append("/.settings\n");
    sb.append("/bin\n");
    sb.append("/build\n");
    sb.append("/ext\n");
    sb.append("/target\n");
    sb.append("/tmp\n");
    sb.append("/temp\n");
    if (!newProject.eclipse.includeClasspath()) {
        // ignore hard-coded .classpath
        sb.append("/.classpath\n");
    }
    FileUtils.writeContent(new File(newProject.dir, ".gitignore"), sb.toString());

    AddCommand add = git.add();
    add.addFilepattern("build.xml");
    add.addFilepattern("build.moxie");
    add.addFilepattern(".gitignore");
    if (newProject.eclipse.includeProject()) {
        add.addFilepattern(".project");
    }
    if (newProject.eclipse.includeClasspath()) {
        // MOXIE_HOME relative dependencies in .classpath
        add.addFilepattern(".classpath");
    }
    if (newProject.idea.includeProject()) {
        add.addFilepattern(".project");
    }
    if (newProject.idea.includeClasspath()) {
        // MOXIE_HOME relative dependencies in .iml
        add.addFilepattern("*.iml");
    }
    try {
        add.call();
        CommitCommand commit = git.commit();
        PersonIdent moxie = new PersonIdent("Moxie", "moxie@localhost");
        commit.setAuthor(moxie);
        commit.setCommitter(moxie);
        commit.setMessage("Project structure created");
        commit.call();
    } catch (Exception e) {
        throw new MoxieException(e);
    }
}

From source file:org.moxie.utils.JGitUtils.java

License:Apache License

public static String commitFiles(File dir, List<String> files, String message, String tagName,
        String tagMessage) throws IOException, GitAPIException {
    Git git = Git.open(dir);
    AddCommand add = git.add();/* w  w  w .  ja  va2  s. co m*/
    for (String file : files) {
        add.addFilepattern(file);
    }
    add.call();

    // execute the commit
    CommitCommand commit = git.commit();
    commit.setMessage(message);
    RevCommit revCommit = commit.call();

    if (!StringUtils.isEmpty(tagName) && !StringUtils.isEmpty(tagMessage)) {
        // tag the commit
        TagCommand tagCommand = git.tag();
        tagCommand.setName(tagName);
        tagCommand.setMessage(tagMessage);
        tagCommand.setForceUpdate(true);
        tagCommand.setObjectId(revCommit);
        tagCommand.call();
    }
    git.getRepository().close();
    return revCommit.getId().getName();
}

From source file:org.ms123.common.git.GitServiceImpl.java

License:Open Source License

public void commitAll(@PName("name") String name, @PName("message") String message) throws RpcException {
    try {/* w  w w  .j ava2 s.c o m*/
        String gitSpace = System.getProperty("git.repos");
        File dir = new File(gitSpace, name);
        if (!dir.exists()) {
            throw new RpcException(ERROR_FROM_METHOD, 100,
                    "GitService.CommitAll:Repo(" + name + ") not exists");
        }
        Git git = Git.open(dir);
        CommitCommand ic = git.commit();
        ic.setAll(true);
        ic.setMessage(message);
        ic.call();
        return;
    } catch (Exception e) {
        if (e instanceof RpcException)
            throw (RpcException) e;
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.commitAll:", e);
    } finally {
    }
}

From source file:org.mule.module.git.GitConnector.java

License:Open Source License

/**
 * Record changes to the repository/*from   w  w  w  .  j  a  v  a2 s.  c om*/
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:commit}
 *
 * @param msg            Commit message
 * @param committerName  Name of the person performing this commit
 * @param committerEmail Email of the person performing this commit
 * @param authorName     Name of the author of the changes to commit
 * @param authorEmail    Email of the author of the changes to commit
 * @param overrideDirectory Name of the directory to use for git repository
 */
@Processor
public void commit(String msg, String committerName, String committerEmail, @Optional String authorName,
        @Optional String authorEmail, @Optional String overrideDirectory) {
    try {
        Git git = new Git(getGitRepo(overrideDirectory));
        CommitCommand commit = git.commit();
        if (authorName != null && authorEmail != null) {
            commit.setAuthor(authorName, authorEmail);
        }

        commit.setCommitter(committerName, committerEmail);
        commit.setMessage(msg);

        commit.call();
    } catch (Exception e) {
        throw new RuntimeException("Unable to commit", e);
    }
}

From source file:org.n52.wps.repository.git.GitAlgorithmRepositoryTest.java

License:Open Source License

@Test
public void initLocalGitRepository() throws IOException, GitAPIException {
    File file = cleanRepository.resolve("hello_world.txt").toFile();
    file.createNewFile();//w w w .j  av a2s  .c  om

    Git repoGit = Git.open(cleanRepository.toFile());
    repoGit.add().addFilepattern(file.getPath());
    repoGit.commit().setMessage("initial commit").call();

    File wc = testRoot.newFolder("workingCopy");

    Git wcGit = Git.cloneRepository().setURI(cleanRepository.toUri().toString()).setDirectory(wc).call();

    int i = 0;
    Iterator<RevCommit> commits = wcGit.log().all().call().iterator();
    while (commits.hasNext()) {
        i++;
        commits.next();
    }
    MatcherAssert.assertThat(i, Is.is(1));
}

From source file:org.obiba.git.command.AbstractGitWriteCommand.java

License:Open Source License

protected Iterable<PushResult> commitAndPush(Git git) throws GitAPIException {
    String name = getAuthorName();
    String email = getAuthorEmail();
    log.debug("Commit: {} <{}> - {}", name, email, getCommitMessage());
    git.commit() //
            .setAuthor(name, email) //
            .setCommitter(name, email) //
            .setMessage(getCommitMessage()) //
            .call();//w  w  w  .  ja v a  2  s .  c o  m
    return git.push().setPushAll().setRemote("origin").call();
}