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:io.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java

License:Open Source License

@Override
void save() throws IOException {
    invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {
        @Override/*from   w  w  w  .  j  a v  a  2 s .  c om*/
        public Void invoke(Repository repository) throws IOException, InterruptedException {
            Git activeRepo = getActiveRepository(repository);
            Repository repo = activeRepo.getRepository();
            File repoDir = repo.getDirectory().getParentFile();
            log.fine("Repo cloned to: " + repoDir.getCanonicalPath());
            try {
                File f = new File(repoDir, filePath);
                if (!f.exists() || f.canWrite()) {
                    try (Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8")) {
                        w.write(new String(contents, "utf-8"));
                    }

                    try {
                        AddCommand add = activeRepo.add();
                        add.addFilepattern(filePath);
                        add.call();

                        CommitCommand commit = activeRepo.commit();
                        commit.setMessage(commitMessage);
                        commit.call();

                        // Push the changes
                        GitUtils.push(gitSource.getRemote(), repo, getCredential(),
                                LOCAL_REF_BASE + sourceBranch, REMOTE_REF_BASE + branch);
                    } catch (GitAPIException ex) {
                        throw new ServiceException.UnexpectedErrorException(ex.getMessage(), ex);
                    }

                    return null;
                }
                throw new ServiceException.UnexpectedErrorException("Unable to write " + filePath);
            } finally {
                FileUtils.deleteDirectory(repoDir);
            }
        }
    });
}

From source file:io.syndesis.git.GitWorkflow.java

License:Apache License

private void commitAndPush(Git git, String authorName, String authorEmail, String message,
        UsernamePasswordCredentialsProvider credentials) throws GitAPIException {

    // git add .//from w w w . j  a  va  2  s .c  o  m
    git.add().addFilepattern(".").call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("git add all file");
    }

    // git commit
    RevCommit commit = git.commit().setAuthor(authorName, authorEmail).setMessage(message).call();
    LOG.info("git commit id {}", commit.getId());

    // git push -f, not merging but simply forcing the push (for now)
    Iterable<PushResult> pushResult = git.push().setCredentialsProvider(credentials).setForce(true).call();
    if (!pushResult.iterator().next().getMessages().equals("")) {
        LOG.warn("git push messages: {}", pushResult.iterator().next().getMessages());
    }
}

From source file:io.vertx.config.git.GitConfigStoreTest.java

License:Apache License

private GitConfigStoreTest add(Git git, File root, File file, String directory)
        throws IOException, GitAPIException {
    if (!file.isFile()) {
        throw new RuntimeException("File not found " + file.getAbsolutePath());
    }/*from   www . ja va  2  s  .  c om*/

    if (!"master".equalsIgnoreCase(git.getRepository().getBranch())) {
        git.checkout().setCreateBranch(true).setName("master").call();
    }

    if (!branch.equalsIgnoreCase(git.getRepository().getBranch())) {
        boolean create = true;
        for (Ref ref : git.branchList().call()) {
            if (ref.getName().equals("refs/heads/" + branch)) {
                create = false;
            }
        }
        git.checkout().setCreateBranch(create).setName(branch).call();
    }

    String relative;
    if (directory != null) {
        relative = directory + File.separator + file.getName();
    } else {
        relative = file.getName();
    }

    File output = new File(root, relative);
    if (output.exists()) {
        output.delete();
    }
    if (!output.getParentFile().isDirectory()) {
        output.getParentFile().mkdirs();
    }

    FileUtils.copyFile(file, output);

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

    git.commit().setAuthor("clement", "clement@apache.org").setCommitter("clement", "clement@apache.org")
            .setMessage("Add " + relative).call();

    return this;
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java

License:Apache License

@TestFor(issues = "TW-20165")
public void push_with_local_mirrors_should_go_to_original_repository() throws Exception {
    AgentRunningBuild build = createRunningBuild(true);
    myVcsSupport.updateSources(myRoot, CheckoutRules.DEFAULT,
            GitUtils.makeVersion("465ad9f630e451b9f2b782ffb09804c6a98c4bb9", 1289483394000L), myCheckoutDir,
            build, false);/*from ww w.ja  v  a  2 s. c om*/

    final File fileToChange = new File(myCheckoutDir, "file");
    FileUtil.writeToFile(fileToChange, "text".getBytes());

    Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build();
    Git git = new Git(r);
    git.add().addFilepattern("file").call();
    RevCommit commitDuringTheBuild = git.commit().setMessage("Commit during the build").call();
    new PushCommand().run(getGitPath(), myCheckoutDir.getAbsolutePath());//push using native git, seems like jgit doesn't respect url.insteadOf settings

    Repository remote = new RepositoryBuilder().setGitDir(myMainRepo).build();
    assertTrue("Push didn't go to the remote repository", remote.hasObject(commitDuringTheBuild));
}

From source file:licenseUtil.Utils.java

License:Apache License

public static void commitAndPushRepository(String gitDir, String message) {
    try {//from w w  w  . j  ava 2  s .co m
        // Open an existing repository
        Repository existingRepo = new FileRepositoryBuilder().setGitDir(new File(gitDir + "/.git")).build();
        Git git = new Git(existingRepo);

        logger.info("commit & push to repo (" + gitDir + "): " + message);
        git.commit().setMessage(message).call();
        git.push().call();
    } catch (GitAPIException e) {
        logger.warn("Could not commit and push local repository: \"" + gitDir + "\" with message: \"" + message
                + "\" because of " + e.getMessage());
    } catch (IOException e) {
        logger.warn("Could not open local git repository directory: \"" + gitDir + "\"");
    }

}

From source file:net.morimekta.idltool.cmd.RemotePublish.java

License:Apache License

@Override
public void execute(IdlTool idlTool) throws IOException, GitAPIException {
    String repository = idlTool.getIdl().getUpstreamRepository();
    File pwd = idlTool.getIdl().getWorkingGitDir();

    Git cacheRepository = idlTool.getRepositoryGitCache(repository);

    Path localIDL = pwd.toPath().resolve(Idl_Constants.IDL);
    Path localPath = localIDL.resolve(idlTool.getLocalRemoteName());

    if (!Files.exists(localPath)) {
        Path relative = pwd.toPath().relativize(localPath);
        System.out.println("No IDL dir in local remote location: .../" + relative);
        return;//from   ww  w  . j ava2  s  . c  om
    }

    Map<String, String> localSha1sums = IdlUtils.buildSha1Sums(localPath);
    if (localSha1sums.isEmpty()) {
        Path relative = pwd.toPath().relativize(localPath);
        System.out.println("No IDL files in local remote location: .../" + relative);
        return;
    }

    Meta cacheMeta = IdlUtils.getMetaInRegistry(cacheRepository.getRepository());
    Remote cacheRemote = cacheMeta.hasRemotes()
            && cacheMeta.getRemotes().containsKey(idlTool.getLocalRemoteName())
                    ? cacheMeta.getRemotes().get(idlTool.getLocalRemoteName())
                    : Remote.builder().build();

    Map<String, String> publishedSha1sums = ImmutableMap.of();
    if (cacheRemote.hasShasums()) {
        publishedSha1sums = cacheMeta.getRemotes().get(idlTool.getLocalRemoteName()).getShasums();
    }

    if (localSha1sums.equals(publishedSha1sums)) {
        // No change.
        System.out.println("No change.");
        return;
    }

    Path remoteIDL = cacheRepository.getRepository().getWorkTree().toPath().resolve(Idl_Constants.IDL);
    Path remotePath = remoteIDL.resolve(idlTool.getLocalRemoteName());
    if (Files.isDirectory(remotePath)) {
        Files.list(remotePath).forEach(file -> {
            try {
                String name = file.getFileName().toString();
                if (Files.isHidden(file) || !Files.isRegularFile(file)) {
                    // Hidden and special files are ignored.
                    return;
                }
                if (!localSha1sums.containsKey(name)) {
                    Files.delete(file);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e.getMessage(), e);
            }
        });
    } else {
        Files.createDirectories(remotePath);
    }

    for (String file : localSha1sums.keySet()) {
        Path source = localPath.resolve(file);
        Path target = remotePath.resolve(file);

        Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
    }

    ZonedDateTime now = ZonedDateTime.now(Clock.systemUTC());
    long timestamp = now.toInstant().toEpochMilli();
    String isoNow = DateTimeFormatter.ISO_DATE_TIME.format(now);

    Remote._Builder remoteBuilder = Remote.builder();
    remoteBuilder.setVersion(timestamp);
    remoteBuilder.setTime(timestamp);
    remoteBuilder.setShasums(localSha1sums);

    Meta._Builder metaBuilder = cacheMeta.mutate();
    metaBuilder.putInRemotes(idlTool.getLocalRemoteName(), remoteBuilder.build());
    metaBuilder.setVersion(timestamp);
    metaBuilder.setTime(isoNow);

    try (FileOutputStream out = new FileOutputStream(
            new File(cacheRepository.getRepository().getWorkTree(), Idl_Constants.META_JSON))) {
        new JsonSerializer().pretty().serialize(out, metaBuilder.build());
        out.write('\n');
    }

    Process add = Runtime.getRuntime().exec(new String[] { "git", "add", "." }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = add.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(add.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }

    cacheRepository.commit().setMessage("Updating " + idlTool.getLocalRemoteName() + " to latest version")
            .call();
    cacheRepository.tag().setName("v" + timestamp).setMessage(isoNow + " " + idlTool.getLocalRemoteName())
            .call();

    Process commit = Runtime.getRuntime().exec(new String[] { "git", "push" }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = commit.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(commit.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }

    commit = Runtime.getRuntime().exec(new String[] { "git", "push", "--tags" }, null,
            cacheRepository.getRepository().getWorkTree());
    try {
        int response = commit.waitFor();
        if (response != 0) {
            throw new IOException(IOUtils.readString(commit.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new IOException(e.getMessage(), e);
    }
}

From source file:net.orpiske.ssps.common.scm.git.GitSCM.java

License:Apache License

@Override
public void commit(final File file, final String message) throws FileCommitException, ScmAccessException {
    Repository repository = accessRepository(file);

    Git git = new Git(repository);
    CommitCommand pullCommand = git.commit();

    try {//from w ww.ja v a2  s. com
        pullCommand.setMessage(message).call();
    } catch (NoHeadException e) {
        throw new FileCommitException("Unable to commit: " + e.getMessage(), e);
    } catch (NoMessageException e) {
        throw new FileCommitException("Unable to commit: " + e.getMessage(), e);
    } catch (UnmergedPathsException e) {
        throw new FileCommitException("Unable to commit: " + e.getMessage(), e);
    } catch (ConcurrentRefUpdateException e) {
        throw new FileCommitException("Unable to commit: " + e.getMessage(), e);
    } catch (WrongRepositoryStateException e) {
        throw new FileCommitException("Unable to commit: " + e.getMessage(), e);
    } catch (GitAPIException e) {
        throw new FileCommitException("Unable to commit: " + e.getMessage(), e);
    }

}

From source file:org.abratuhi.camel.GitLogComponentTest.java

License:Apache License

public void setUp() throws Exception {
    repodir = File.createTempFile("tmp", "repo");
    repodir.delete();//from  w w w  .j  a va 2s. c om
    repodir.mkdir();

    repogit = new File(repodir, ".git");

    final FileRepository repo = new FileRepository(repogit);
    Git git = new Git(repo);

    repo.create();
    final File repofile = File.createTempFile("tmp", "repofile", repodir);
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Test message").call();

    super.setUp();
}

From source file:org.apache.gobblin.service.modules.flow.MultiHopFlowCompilerTest.java

License:Apache License

@Test(dependsOnMethods = "testMulticastPath")
public void testGitFlowGraphMonitorService()
        throws IOException, GitAPIException, URISyntaxException, InterruptedException {
    File remoteDir = new File(TESTDIR + "/remote");
    File cloneDir = new File(TESTDIR + "/clone");
    File flowGraphDir = new File(cloneDir, "/gobblin-flowgraph");

    //Clean up//from ww  w. jav a2  s  . c o m
    cleanUpDir(TESTDIR);

    // Create a bare repository
    RepositoryCache.FileKey fileKey = RepositoryCache.FileKey.exact(remoteDir, FS.DETECTED);
    Repository remoteRepo = fileKey.open(false);
    remoteRepo.create(true);

    Git gitForPush = Git.cloneRepository().setURI(remoteRepo.getDirectory().getAbsolutePath())
            .setDirectory(cloneDir).call();

    // push an empty commit as a base for detecting changes
    gitForPush.commit().setMessage("First commit").call();
    RefSpec masterRefSpec = new RefSpec("master");
    gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

    URI flowTemplateCatalogUri = this.getClass().getClassLoader().getResource("template_catalog").toURI();

    Config config = ConfigBuilder.create()
            .addPrimitive(
                    GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                            + ConfigurationKeys.GIT_MONITOR_REPO_URI,
                    remoteRepo.getDirectory().getAbsolutePath())
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_REPO_DIR, TESTDIR + "/git-flowgraph")
            .addPrimitive(GitFlowGraphMonitor.GIT_FLOWGRAPH_MONITOR_PREFIX + "."
                    + ConfigurationKeys.GIT_MONITOR_POLLING_INTERVAL, 5)
            .addPrimitive(ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY,
                    flowTemplateCatalogUri.toString())
            .build();

    //Create a MultiHopFlowCompiler instance
    specCompiler = new MultiHopFlowCompiler(config, Optional.absent(), false);

    specCompiler.setActive(true);

    //Ensure node1 is not present in the graph
    Assert.assertNull(specCompiler.getFlowGraph().getNode("node1"));

    // push a new node file
    File nodeDir = new File(flowGraphDir, "node1");
    File nodeFile = new File(nodeDir, "node1.properties");
    nodeDir.mkdirs();
    nodeFile.createNewFile();
    Files.write(FlowGraphConfigurationKeys.DATA_NODE_IS_ACTIVE_KEY + "=true\nparam1=val1" + "\n", nodeFile,
            Charsets.UTF_8);

    // add, commit, push node
    gitForPush.add().addFilepattern(formNodeFilePath(flowGraphDir, nodeDir.getName(), nodeFile.getName()))
            .call();
    gitForPush.commit().setMessage("Node commit").call();
    gitForPush.push().setRemote("origin").setRefSpecs(masterRefSpec).call();

    // polling is every 5 seconds, so wait twice as long and check
    TimeUnit.SECONDS.sleep(10);

    //Test that a DataNode is added to FlowGraph
    DataNode dataNode = specCompiler.getFlowGraph().getNode("node1");
    Assert.assertEquals(dataNode.getId(), "node1");
    Assert.assertEquals(dataNode.getRawConfig().getString("param1"), "val1");
}

From source file:org.apache.maven.scm.provider.git.jgit.command.checkin.JGitCheckInCommand.java

License:Apache License

/**
 * {@inheritDoc}/*from ww  w. ja va 2s. com*/
 */
protected CheckInScmResult executeCheckInCommand(ScmProviderRepository repo, ScmFileSet fileSet, String message,
        ScmVersion version) throws ScmException {

    Git git = null;
    try {
        File basedir = fileSet.getBasedir();
        git = Git.open(basedir);

        boolean doCommit = false;

        if (!fileSet.getFileList().isEmpty()) {
            doCommit = JGitUtils.addAllFiles(git, fileSet).size() > 0;
        } else {
            // add all tracked files which are modified manually
            Set<String> changeds = git.status().call().getModified();
            if (changeds.isEmpty()) {
                // warn there is nothing to add
                getLogger().warn("there are no files to be added");
                doCommit = false;
            } else {
                AddCommand add = git.add();
                for (String changed : changeds) {
                    getLogger().debug("add manualy: " + changed);
                    add.addFilepattern(changed);
                    doCommit = true;
                }
                add.call();
            }
        }

        List<ScmFile> checkedInFiles = Collections.emptyList();
        if (doCommit) {
            UserInfo author = getAuthor(repo, git);
            UserInfo committer = getCommitter(repo, git);

            CommitCommand command = git.commit().setMessage(message).setAuthor(author.name, author.email);
            command.setCommitter(committer.name, committer.email);
            RevCommit commitRev = command.call();

            getLogger().info("commit done: " + commitRev.getShortMessage());
            checkedInFiles = JGitUtils.getFilesInCommit(git.getRepository(), commitRev);
            if (getLogger().isDebugEnabled()) {
                for (ScmFile scmFile : checkedInFiles) {
                    getLogger().debug("in commit: " + scmFile);
                }
            }
        }

        if (repo.isPushChanges()) {
            String branch = version != null ? version.getName() : null;
            if (StringUtils.isBlank(branch)) {
                branch = git.getRepository().getBranch();
            }
            RefSpec refSpec = new RefSpec(Constants.R_HEADS + branch + ":" + Constants.R_HEADS + branch);
            getLogger().info("push changes to remote... " + refSpec.toString());
            JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo, refSpec);
        }

        return new CheckInScmResult("JGit checkin", checkedInFiles);
    } catch (Exception e) {
        throw new ScmException("JGit checkin failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}