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:com.tasktop.c2c.server.internal.profile.service.template.GitServiceCloner.java

License:Open Source License

private void copyRepo(ScmRepository scmRepo, CloneContext context)
        throws IOException, JGitInternalException, GitAPIException {

    File workDirectory = null;//ww w.j a va  2 s  .  c om
    try {
        Project templateProject = context.getTemplateService().getProjectServiceProfile().getProject();
        String cloneUrl = jgitProvider.computeRepositoryUrl(templateProject.getIdentifier(), scmRepo.getName());

        AuthUtils.assumeSystemIdentity(templateProject.getIdentifier());
        tenancyManager.establishTenancyContext(context.getTemplateService());

        workDirectory = createTempDirectory();
        Git git = Git.cloneRepository().setDirectory(workDirectory)
                .setBranch(Constants.R_HEADS + Constants.MASTER).setURI(cloneUrl).call();

        AuthUtils.assumeSystemIdentity(
                context.getTargetService().getProjectServiceProfile().getProject().getIdentifier());
        tenancyManager.establishTenancyContext(context.getTargetService());

        FileUtils.deleteDirectory(git.getRepository().getDirectory());

        git = Git.init().setDirectory(git.getRepository().getDirectory().getParentFile()).call();

        maybeRewriteRepo(workDirectory, context);

        String pushUrl = jgitProvider.computeRepositoryUrl(
                context.getTargetService().getProjectServiceProfile().getProject().getIdentifier(),
                scmRepo.getName());

        // FIXME: User's locale is not defined here
        String commitMessage = messageSource.getMessage("project.template.git.commitMessage",
                new Object[] { templateProject.getName() }, null);

        git.add().addFilepattern(".").call();
        git.commit().setCommitter(committerName, committerEmail).setMessage(commitMessage).call();
        git.getRepository().getConfig().setString("remote", "target", "url", pushUrl);
        git.push().setRemote("target").setPushAll().call();
    } finally {
        if (workDirectory != null) {
            FileUtils.deleteDirectory(workDirectory);
        }
    }
}

From source file:com.tasktop.c2c.server.scm.service.GitServiceTestBase.java

License:Open Source License

protected void commitAndPushFile(Git git, String path, String content, String message)
        throws GitAPIException, JGitInternalException, IOException {
    File f = new File(git.getRepository().getDirectory().getParentFile(), path);
    ensureDirExists(f.getParentFile());/*from   w  w w. j a v a  2 s .  c  o  m*/
    FileOutputStream writer = new FileOutputStream(f);
    writer.write(content.getBytes());
    writer.close();
    git.add().addFilepattern(path).call();
    git.commit().setMessage(message).call();
    git.push().call();
}

From source file:com.tenxdev.ovcs.command.AbstractSyncCommand.java

License:Open Source License

/**
 * Commit all changes and push to remote repository
 *
 * @throws OvcsException//from  w w  w .  ja v  a  2s  .c  o  m
 *             if changes could not be committed or pushed
 */
protected void commitAndPush() throws OvcsException {
    try {
        final FileRepository fileRepository = getRepoForCurrentDir();
        final Git git = new Git(fileRepository);
        final Status status = git.status().setProgressMonitor(new TextProgressMonitor()).call();
        if (!status.isClean()) {
            git.add().addFilepattern(".").call();
            git.commit().setMessage("initial synchronization").setAll(true).call();
            doPush(git);
        }
    } catch (final GitAPIException e) {
        throw new OvcsException("Unable to commit to git repo: " + e.getMessage(), e);
    }
}

From source file:com.tenxdev.ovcs.command.CommitCommand.java

License:Open Source License

@Override
/**//from www. j  av  a 2 s.  c  o m
 * {@inheritDoc}
 */
public void execute(final String... args) throws OvcsException {
    if (args.length != 1) {
        throw new OvcsException(USAGE);
    }
    System.out.println("Fetching changes from database...");
    final FileRepository repository = getRepoForCurrentDir();
    try {
        try (Connection conn = getDbConnectionForRepo(repository)) {
            final Git git = new Git(repository);
            final List<ChangeEntry> changes = writeChanges(repository);
            if (changes.isEmpty()) {
                System.out.println("No changes have been made, ending session");
            } else {
                try {
                    for (final ChangeEntry changeEntry : changes) {
                        git.add()
                                .addFilepattern(changeEntry.getName().toUpperCase(Locale.getDefault()) + ".sql")
                                .call();
                    }
                    git.commit().setMessage(getCommitMessage()).setAll(true).call();
                } catch (final GitAPIException e) {
                    throw new OvcsException("Unable to commit: " + e.getMessage(), e);
                }
            }
            try (CallableStatement stmt = conn.prepareCall("begin ovcs.handler.end_session; end;")) {
                stmt.execute();
                conn.commit();
            } catch (final SQLException e) {
                throw new OvcsException(
                        "Unexpected error while committing database changes, you may have to call "
                                + "ovcs.handler.end_session from your schema and commit to bring the database into a consistent state.",
                        e);
            }
            if (!changes.isEmpty()) {
                try {
                    doPush(git);
                    System.out.println("All changes committed and sent to remote repository.");
                } catch (final GitAPIException e) {
                    throw new OvcsException(String.format(
                            "All changes have been committed, but were not sent to the remote repository%n"
                                    + "Please run the ovcs push command to retry sending to the remote repository%nError: %s",
                            e.getMessage()), e);
                }
            }
        } catch (final SQLException e) {
            throw new OvcsException("Unexpected error while closing database connection, you may have to call "
                    + "ovcs.handler.end_session from your schema and commit to bring the database into a consistent state.",
                    e);
        }
    } finally {
        repository.close();
    }

}

From source file:com.uber.stream.kafka.mirrormaker.controller.core.GitBackUpHandler.java

License:Apache License

public void writeToFile(String fileName, String data) throws Exception {
    Repository backupRepo = null;/*ww  w . j  a  v  a  2  s  .c  o m*/
    BufferedWriter output = null;
    Git git = null;
    Git result = null;
    try {
        try {
            FileUtils.deleteDirectory(new File(localPath));
        } catch (IOException e) {
            LOGGER.error("Error deleting exisiting backup directory");
            throw e;
        }

        try {
            result = Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
        } catch (Exception e) {
            LOGGER.error("Error cloning backup git repo");
            throw e;
        }

        try {
            backupRepo = new FileRepository(localPath + "/.git");
        } catch (IOException e) {
            throw e;
        }

        git = new Git(backupRepo);
        File myfile = new File(localPath + "/" + fileName);

        try {
            output = new BufferedWriter(new FileWriter(myfile));
            output.write(data);
            output.flush();
        } catch (IOException e) {
            LOGGER.error("Error writing backup to the file with name " + fileName);
            throw e;
        }

        try {
            git.add().addFilepattern(".").call();
        } catch (GitAPIException e) {
            LOGGER.error("Error adding files to git");
            throw e;
        }

        try {
            git.commit().setMessage("Taking backup on " + new Date()).call();

        } catch (GitAPIException e) {
            LOGGER.error("Error commiting files to git");
            throw e;
        }

        try {
            git.push().call();
        } catch (GitAPIException e) {
            LOGGER.error("Error pushing files to git");
            throw e;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        output.close();
        git.close();
        if (result != null)
            result.getRepository().close();
        backupRepo.close();
    }
}

From source file:com.wadpam.gimple.GimpleMojo.java

License:Open Source License

private RevCommit transformPomVersions(Git git, String newVersion)
        throws MojoExecutionException, GitAPIException {
    executeMojo(plugin("org.codehaus.mojo", "versions-maven-plugin", "2.1"), goal("set"),
            configuration(element(name("newVersion"), newVersion)),
            executionEnvironment(mavenProject, mavenSession, pluginManager));

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

    // git add/*from   w  w w .ja  v a2s.  com*/
    for (String uncommitted : status.getUncommittedChanges()) {
        getLog().info("  adding to git index: " + uncommitted);
        AddCommand add = git.add();
        add.addFilepattern(uncommitted);
        add.call();
    }

    // git commit
    CommitCommand commit = git.commit();
    commit.setMessage(GIMPLE_MAVEN_PLUGIN + "pom version " + newVersion);
    return commit.call();
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Adds all the files of the specified directory in the local git repository
 * (git add .), then commits the changes (git commit .), and finally pushes
 * the changes on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication/*from ww  w .  j a va 2  s .c  o  m*/
 * @param message   the commit message to be used
 * @throws GitAPIException if something's going wrong while interacting with Git
 * @throws IOException     if something's going wrong while manipulating the local
 *                         repository
 */
public static void commitAndPush(@NonNull File directory, String username, String password, String message)
        throws GitAPIException, IOException {
    try {
        final Git git = Git.open(directory);
        // run the add
        final AddCommand addCommand = git.add();
        for (final String filePath : directory.list())
            if (!".git".equals(filePath))
                addCommand.addFilepattern(filePath);
        addCommand.call();
        log.info("Added content of the directory" + directory + " in the Git repository located in "
                + directory.toString());
        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info("Commited the changes in the Git repository...");
        // and finally push
        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);
        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");
    } catch (final GitAPIException e) {
        log.error(e.getMessage(), e);
        throw e;
    }
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
* Create a new branch in the local git repository
* (git checkout -b branchname) and finally pushes new branch on the remote repository (git push)
*
* @param directory the directory in which the local git repository is located
* @param username  the username to be used while pushing
* @param password  the password matching with the provided username to be used
*                  for authentication// www  .  j  a v a 2 s .  c  o m
* @param message   the commit message to be used    
*/
public static void createBranch(@NonNull File directory, String branchName, String username, String password,
        String message) throws GitAPIException {

    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);

        CreateBranchCommand branchCommand = git.branchCreate();
        branchCommand.setName(branchName);
        branchCommand.call();

        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info(message);

        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");
    } catch (final GitAPIException | IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Delete a branch in the local git repository
 * (git branch -d branchname) and finally pushes new branch on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication//from   w  w w .  j a  v  a 2s . c o m
 * @param message   the commit message to be used    
 */
public static void deleteBranch(@NonNull File directory, String branchName, String username, String password,
        String message) {

    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);

        DeleteBranchCommand deleteBranchCommand = git.branchDelete();

        deleteBranchCommand.setBranchNames(branchName);
        deleteBranchCommand.call();
        log.info("Develop branch deleted");

        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info(message);

        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");

    } catch (final GitAPIException | IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.worldline.easycukes.scm.utils.GitHelper.java

License:Open Source License

/**
 * Create a new tag in the local git repository
 * (git checkout tagname) and finally pushes new branch on the remote repository (git push)
 *
 * @param directory the directory in which the local git repository is located
 * @param username  the username to be used while pushing
 * @param password  the password matching with the provided username to be used
 *                  for authentication/*from  www.  ja  v a 2s  .  co m*/
 * @param message   the commit message to be used    
 */
public static void createTag(@NonNull File directory, String tagName, String username, String password,
        String message) {

    try {
        final Git git = Git.open(directory);

        final UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                username, password);

        TagCommand tagCommand = git.tag();
        tagCommand.setName(tagName);
        tagCommand.setMessage(message);
        tagCommand.call();
        log.info("Tag created");

        // and then commit
        final PersonIdent author = new PersonIdent(username, "");
        git.commit().setCommitter(author).setMessage(message).setAuthor(author).call();
        log.info(message);

        git.push().setCredentialsProvider(userCredential).call();
        log.info("Pushed the changes in remote Git repository...");
    } catch (final GitAPIException | IOException e) {
        log.error(e.getMessage(), e);
    }
}