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 {
        try {
            File result = File.createTempFile("empty","docx");
            WordprocessingMLPackage empty = WordprocessingMLPackage.createPackage();
            empty.save(result);
            return result;
        } catch (Docx4JException | IOException e) {
            throw new DocAsCodeException("Unable to create empty .docx file.",e);
        }
    }

    @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()));
        }
    }
}