DocxDifferencer.java

package org.docascode.api.diff;

import com.profesorfalken.jpowershell.PowerShell;
import org.docascode.api.core.errors.DocAsCodeException;
import org.docascode.api.event.Event;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import java.io.*;

public class DocxDifferencer extends AbstractDifferencer{
    private File createEmpty() throws DocAsCodeException {
        File result = new File(".empty.docx");
        try {
            WordprocessingMLPackage empty = WordprocessingMLPackage.createPackage();
            empty.save(result);
        } catch (Docx4JException e) {
            throw new DocAsCodeException("Unable to create empty .docx file.",e);
        }
        return result;
    }

    @Override
    public void diff() throws DocAsCodeException {
        try (PowerShell powerShell = PowerShell.openSession()) {
            String script = "powershell/diff-docx.ps1";
            if (baseFile == null) {
                baseFile = createEmpty();
            }
            if (revisedFile == null) {
                revisedFile = createEmpty();
            }
            Event e = new Event(this);
            e.setMessage(String.format(
                    "Getting diff of '%s' against '%s'...",
                    baseFile,
                    revisedFile));
            fireEvent(e);
            //Read the resource
            BufferedReader srcReader = new BufferedReader(
                    new InputStreamReader(getClass().getClassLoader().getResourceAsStream(script)));
            powerShell.executeScript(srcReader,
                    String.format("-BaseFilePath %s -RevisedFilePath %s -Revision %s -TargetFilePath %s",
                            baseFile.getAbsolutePath(),
                            revisedFile.getAbsolutePath(),
                            revision,
                            targetFile.getAbsolutePath()));
        }
    }
}