PostCommitCommand.java

package org.docascode.api;

import org.docascode.api.core.errors.DocAsCodeException;
import org.docascode.api.core.DocAsCodeRepository;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;

import java.io.IOException;

public class PostCommitCommand extends DocAsCodeCommand<RevCommit> {
    PostCommitCommand(DocAsCodeRepository repo) {
        super(repo);
    }

    @Override
    public RevCommit call() throws DocAsCodeException {
        RevCommit result;
        RevCommit previousCommit;
        ObjectId headId;
        try (RevWalk rw = new RevWalk(getRepository().git())){
            headId = getRepository().git().resolve(Constants.HEAD + "^{commit}");
            previousCommit = rw.parseCommit(headId);
        } catch (IOException e) {
            throw new DocAsCodeException("Unable to process post-commit.", e);
        }
        if (this.getRepository().git().isLocked()) {
            try (Git git = Git.open(getRepository().getWorkTree()) ){
                getRepository().git().unlock();
                git.add().addFilepattern(".docascode/markdown").call();

                result = git.commit()
                        .setAmend(true)
                        .setNoVerify(true)
                        .setMessage(previousCommit.getFullMessage())
                        .call();
                return result;
            } catch (GitAPIException | IOException e) {
                throw new DocAsCodeException("Unable to process post-commit.", e);
            } finally {
                this.getRepository().git().unlock();
            }
        } else {
            return previousCommit;
        }
    }
}