org.eclipse.jgit.api.CommitCommand Java Examples

The following examples show how to use org.eclipse.jgit.api.CommitCommand. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected CommitInfo doRename(Git git, String oldPath, String newPath) throws Exception {
    File file = getRelativeFile(oldPath);
    File newFile = getRelativeFile(newPath);
    if (file.exists()) {
        File parentFile = newFile.getParentFile();
        parentFile.mkdirs();
        if (!parentFile.exists()) {
            throw new IOException("Could not create directory " + parentFile + " when trying to move " + file + " to " + newFile + ". Maybe a file permission issue?");
        }
        file.renameTo(newFile);
        String filePattern = getFilePattern(newPath);
        git.add().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
        return createCommitInfo(commitThenPush(git, commit));
    } else {
        return null;
    }
}
 
Example #2
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected CommitInfo doRemove(Git git, List<String> paths) throws Exception {
    if (paths != null && paths.size() > 0) {
        int count = 0;
        for (String path : paths) {
            File file = getRelativeFile(path);
            if (file.exists()) {
                count++;
                Files.recursiveDelete(file);
                String filePattern = getFilePattern(path);
                git.rm().addFilepattern(filePattern).call();
            }
        }
        if (count > 0) {
            CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
            return createCommitInfo(commitThenPush(git, commit));
        }
    }
    return null;
}
 
Example #3
Source File: GitManagerTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private RevCommit writeFileAndCommitWithAuthor(Git git, String authorName, String email, String fileName, String commitMessage,
                                               String... lines) throws IOException, GitAPIException {
    StringBuilder sb = new StringBuilder();
    for (String line : lines) {
        sb.append(line);
        sb.append('\n');
    }
    writeTrashFile(fileName, sb.toString());
    git.add().addFilepattern(fileName).call();

    CommitCommand commitCommand = git.commit().setMessage(commitMessage);

    if (authorName != null && email != null) {
        return commitCommand.setAuthor(authorName, email).call();
    } else {
        return commitCommand.call();
    }
}
 
Example #4
Source File: JGitOperator.java    From verigreen with Apache License 2.0 6 votes vote down vote up
@Override
public String commit(String author, String email, String message) {
    
    RevCommit revCommit = null;
    CommitCommand command = _git.commit();
    command.setCommitter(author, email);
    command.setMessage(message);
    command.setAll(true);
    try {
        revCommit = command.call();
    } catch (Throwable e) {
        throw new RuntimeException("Failed to commit", e);
    }
    
    return revCommit.getId().getName();
}
 
Example #5
Source File: AbstractGitTest.java    From onedev with MIT License 5 votes vote down vote up
protected String commit(String comment) {
	CommitCommand ci = git.commit();
	ci.setMessage(comment);
	ci.setAuthor(user);
	ci.setCommitter(user);
	try {
		return ci.call().name();
	} catch (GitAPIException e) {
		throw new RuntimeException(e);
	}
}
 
Example #6
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected CommitInfo doCreateDirectory(Git git, String path) throws Exception {
    File file = getRelativeFile(path);
    if (file.exists()) {
        return null;
    }
    file.mkdirs();
    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
    RevCommit revCommit = commitThenPush(git, commit);
    return createCommitInfo(revCommit);
}
 
Example #7
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected CommitInfo doRemove(Git git, String path) throws Exception {
    File file = getRelativeFile(path);
    if (file.exists()) {
        Files.recursiveDelete(file);
        String filePattern = getFilePattern(path);
        git.rm().addFilepattern(filePattern).call();
        CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(message);
        return createCommitInfo(commitThenPush(git, commit));
    } else {
        return null;
    }
}
 
Example #8
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected CommitInfo doWrite(Git git, String path, byte[] contents, PersonIdent personIdent, String commitMessage) throws Exception {
    File file = getRelativeFile(path);
    file.getParentFile().mkdirs();

    Files.writeToFile(file, contents);

    String filePattern = getFilePattern(path);
    AddCommand add = git.add().addFilepattern(filePattern).addFilepattern(".");
    add.call();

    CommitCommand commit = git.commit().setAll(true).setAuthor(personIdent).setMessage(commitMessage);
    RevCommit revCommit = commitThenPush(git, commit);
    return createCommitInfo(revCommit);
}
 
Example #9
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected RevCommit commitThenPush(Git git, CommitCommand commit) throws Exception {
    RevCommit answer = commit.call();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage());
    }
    if (isPushOnCommit()) {
        Iterable<PushResult> results = doPush(git);
        for (PushResult result : results) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates()));
            }
        }
    }
    return answer;
}
 
Example #10
Source File: GitCacheCloneReadSaveRequest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
void save() throws IOException {
    invokeOnScm(new GitSCMFileSystem.FSFunction<Void>() {
        @Override
        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);
            }
        }
    });
}
 
Example #11
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
private void makeRepoOrphan(Repository repository, String site) throws IOException, GitAPIException,
        ServiceLayerException, UserNotFoundException {
    logger.debug("Make repository orphan fir site " + site);
    String sandboxBranchName = repository.getBranch();
    if (StringUtils.isEmpty(sandboxBranchName)) {
        sandboxBranchName = studioConfiguration.getProperty(REPO_SANDBOX_BRANCH);
    }
    String sandboxBranchOrphanName = sandboxBranchName + "_orphan";

    logger.debug("Shallow clone is not implemented in JGit. Instead we are creating new orphan branch after " +
            "cloning and renaming it to sandbox branch to replace fully cloned branch");
    try (Git git = new Git(repository)) {
        logger.debug("Create temporary orphan branch " + sandboxBranchOrphanName);
        git.checkout()
                .setName(sandboxBranchOrphanName)
                .setStartPoint(sandboxBranchName)
                .setOrphan(true)
                .call();

        // Reset everything to simulate first commit as created empty repo
        logger.debug("Soft reset to commit empty repo");
        git.reset().call();

        logger.debug("Commit empty repo, because we need to have HEAD to delete old and rename new branch");
        CommitCommand commitCommand = git.commit()
                .setMessage(getCommitMessage(REPO_CREATE_AS_ORPHAN_COMMIT_MESSAGE));
        String username = securityService.getCurrentUser();
        if (StringUtils.isNotEmpty(username)) {
            commitCommand = commitCommand.setAuthor(getAuthorIdent(username));
        }
        commitCommand.call();

        logger.debug("Delete cloned branch " + sandboxBranchName);
        git.branchDelete().setBranchNames(sandboxBranchName).setForce(true).call();

        logger.debug("Rename temporary orphan branch to sandbox branch");
        git.branchRename().setNewName(sandboxBranchName).setOldName(sandboxBranchOrphanName).call();
    }
}
 
Example #12
Source File: RepositoryManagementServiceInternalImpl.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean commitResolution(String siteId, String commitMessage) throws CryptoException, ServiceLayerException {
    GitRepositoryHelper helper = GitRepositoryHelper.getHelper(studioConfiguration);
    Repository repo = helper.getRepository(siteId, SANDBOX);
    logger.debug("Commit resolution for merge conflict for site " + siteId);
    try (Git git = new Git(repo)) {
        Status status = git.status().call();

        logger.debug("Add all uncommitted changes/files");
        AddCommand addCommand = git.add();
        for (String uncommited : status.getUncommittedChanges()) {
            addCommand.addFilepattern(uncommited);
        }
        addCommand.call();
        logger.debug("Commit changes");
        CommitCommand commitCommand = git.commit();
        String userName = securityService.getCurrentUser();
        User user = userServiceInternal.getUserByIdOrUsername(-1, userName);
        PersonIdent personIdent = helper.getAuthorIdent(user);
        String prologue = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_PROLOGUE);
        String postscript = studioConfiguration.getProperty(REPO_COMMIT_MESSAGE_POSTSCRIPT);

        StringBuilder sbMessage = new StringBuilder();
        if (StringUtils.isNotEmpty(prologue)) {
            sbMessage.append(prologue).append("\n\n");
        }
        sbMessage.append(commitMessage);
        if (StringUtils.isNotEmpty(postscript)) {
            sbMessage.append("\n\n").append(postscript);
        }
        commitCommand.setCommitter(personIdent).setAuthor(personIdent).setMessage(sbMessage.toString()).call();
        return true;
    } catch (GitAPIException | UserNotFoundException | ServiceLayerException e) {
        logger.error("Error while committing conflict resolution for site " + siteId, e);
        throw new ServiceLayerException("Error while committing conflict resolution for site " + siteId, e);
    }
}
 
Example #13
Source File: JGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void commit(String message) throws GitException {
    try (Repository repo = getRepository()) {
        CommitCommand cmd = git(repo).commit().setMessage(message).setAuthor(author);
        if (committer!=null)
            cmd.setCommitter(new PersonIdent(committer,new Date()));
        cmd.call();
    } catch (GitAPIException e) {
        throw new GitException(e);
    }
}
 
Example #14
Source File: ForgeTestSupport.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected Build assertCodeChangeTriggersWorkingBuild(final String projectName, Build firstBuild) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }


    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()).setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;


    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JobWithDetails job = assertJob(projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber()).describedAs("Waiting for latest build for job " + projectName + " to start").isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(forgeClient, projectName);
}
 
Example #15
Source File: CommitTask.java    From ant-git-tasks with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute() throws BuildException {
        try {
                setFailOnError(true);
                CommitCommand cmd = git.commit();

                if (!GitTaskUtils.isNullOrBlankString(message)) {
                        cmd.setMessage(brandedMessage ? GitTaskUtils.BRANDING_MESSAGE + " " + message : message);
                }
                else {
                        cmd.setMessage(GitTaskUtils.BRANDING_MESSAGE);
                }

                String prefix = getDirectory().getCanonicalPath();
                String[] allFiles = getPath().list();

                if (!GitTaskUtils.isNullOrBlankString(only)) {
                        cmd.setOnly(only);
                }
                else if (allFiles.length > 0) {
                        for (String file : allFiles) {
                                String modifiedFile = translateFilePathUsingPrefix(file, prefix);
                                log("Will commit " + modifiedFile);
                                cmd.setOnly(modifiedFile);
                        }
                }
                else {
                        cmd.setAll(true);
                }

                GitSettings gitSettings = lookupSettings();

                if (gitSettings == null) {
                        throw new MissingRequiredGitSettingsException();
                }

                cmd.setAmend(amend).setAuthor(gitSettings.getIdentity()).setCommitter(gitSettings.getIdentity());

                if (reflogComment != null) {
                        cmd.setReflogComment(reflogComment);
                }

                RevCommit revCommit = cmd.call();

                if (revCommitIdProperty != null) {
                        String revisionId = ObjectId.toString(revCommit.getId());
                        getProject().setProperty(revCommitIdProperty, revisionId);
                }

                log(revCommit.getFullMessage());
        } catch (IOException ioe) {
                throw new GitBuildException(MESSAGE_COMMIT_FAILED, ioe);
        } catch (GitAPIException ex) {
                throw new GitBuildException(MESSAGE_COMMIT_FAILED, ex);
        }
}