PreCommitCtrl.java

package org.docascode.hooks;

import org.docascode.utils.Utils;
import org.docx4j.TextUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.diff.DiffEntry;

import java.io.*;
import java.util.List;

public class PreCommitCtrl {
    public void run() throws Exception {
        try {
            Git git = Git.open(Utils.getRepository().getTopLevel());
            List<DiffEntry> diffList = git.diff().setCached(true).call();
            for (DiffEntry entry : diffList){
                Utils.info(entry.getNewPath());
                WordprocessingMLPackage pkg = WordprocessingMLPackage.load(new File(Utils.getRepository().getTopLevel().getAbsolutePath()+"/"+entry.getNewPath()));

                MainDocumentPart documentPart = pkg.getMainDocumentPart();

                org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document)documentPart.getJaxbElement();

                OutputStream os = new FileOutputStream(Utils.getRepository().getTopLevel().getAbsolutePath()+"/.docascode/markdown/test.md");
                Writer out = new OutputStreamWriter(os);

                TextUtils.extractText(wmlDocumentEl, out);
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (GitAPIException e) {
            e.printStackTrace();
        }
    }
}