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

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

Introduction

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

Prototype

public AddCommand add() 

Source Link

Document

Return a command object to execute a Add command

Usage

From source file:org.kie.workbench.common.screens.examples.backend.server.ExamplesServiceImpl.java

License:Apache License

@PostConstruct
public void initPlaygroundRepository() {
    try {//from w w  w . j a v a 2s  .c o  m
        String userDir = System.getProperty("user.dir");

        File playgroundDirectory = new File(userDir, ".kie-wb-playground");
        if (playgroundDirectory.exists()) {
            cleanPlaygroundDirectory(playgroundDirectory.toPath());
        }
        playgroundDirectory.mkdirs();

        URL resource = getClass().getClassLoader().getResource(KIE_WB_PLAYGROUND_ZIP);
        if (resource == null) {
            logger.warn("Playground repository jar not found on classpath.");
            return;
        }

        try (ZipInputStream inputStream = new ZipInputStream(resource.openStream())) {
            ZipEntry zipEntry = null;
            while ((zipEntry = inputStream.getNextEntry()) != null) {
                byte[] buffer = new byte[1024];
                File file = new File(playgroundDirectory, zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                } else {
                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        int read = -1;
                        while ((read = inputStream.read(buffer)) != -1) {
                            fos.write(buffer, 0, read);
                        }
                    }
                }
            }

            final Git git = Git.init().setBare(false).setDirectory(playgroundDirectory).call();
            git.add().addFilepattern(".").call();
            git.commit().setMessage("Initial commit").call();

            String repositoryUrl = resolveRepositoryUrl(playgroundDirectory.getAbsolutePath());
            playgroundRepository = new ExampleRepository(repositoryUrl);
        }
    } catch (java.io.IOException | GitAPIException e) {
        logger.error(
                "Unable to initialize playground git repository. Only custom repository definition will be available in the Workbench.",
                e);
    }
}

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. ja  v a 2 s . c o  m*/

    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 w w . ja  va  2 s .c  o m*/

    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 {

    /*/*from   w w  w.j a va2 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);
    }/*from w ww .j a v  a2s.  c o  m*/

    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. j a  va 2 s .  c  om
    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();
    for (String file : files) {
        add.addFilepattern(file);/*from ww w  .  j av  a  2 s. com*/
    }
    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 add(@PName("name") String name, @PName("pattern") String pattern) throws RpcException {
    try {/*from ww  w .  ja  va  2  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.add:Repo(" + name + ") not exists");
        }
        Git git = Git.open(dir);
        AddCommand add = git.add();
        add.addFilepattern(pattern);
        add.call();
        return;
    } catch (Exception e) {
        throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.add:", e);
    } finally {
    }
}

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

License:Open Source License

/**
 * Add file contents to the index/*from   w  ww.j ava  2 s  .  co m*/
 *
 * {@sample.xml ../../../doc/mule-module-git.xml.sample git:add}
 *
 * @param filePattern File to add content from. Also a leading directory name (e.g. dir to add dir/file1 and dir/file2) can be given to add all files in the directory, recursively.
 * @param overrideDirectory Name of the directory to use for git repository
 */
@Processor
public void add(String filePattern, @Optional String overrideDirectory) {
    try {
        Git git = new Git(getGitRepo(overrideDirectory));
        AddCommand add = git.add();
        add.addFilepattern(filePattern);

        add.call();
    } catch (Exception e) {
        throw new RuntimeException("Cannot add " + filePattern, 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();//from ww w . j a va 2 s . c o  m

    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));
}