All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.legendofdragoon.scripting.Patcher Maven / Gradle / Ivy

There is a newer version: 0.5.6
Show newest version
package org.legendofdragoon.scripting;

import com.github.difflib.DiffUtils;
import com.github.difflib.UnifiedDiffUtils;
import com.github.difflib.patch.Patch;
import com.github.difflib.patch.PatchFailedException;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public final class Patcher {
  private Patcher() { }

  public static String generatePatch(final Path originalFile, final Path modifiedFile) throws IOException {
    final List originalLines = Files.readAllLines(originalFile);
    final List modifiedLines = Files.readAllLines(modifiedFile);
    return generatePatch(originalLines, modifiedLines);
  }

  public static String generatePatch(final List originalLines, final List modifiedLines) {
    final Patch patch = DiffUtils.diff(originalLines, modifiedLines);
    final List diff = UnifiedDiffUtils.generateUnifiedDiff("original", "modified", originalLines, patch, 3);
    final StringBuilder output = new StringBuilder();

    for(final String line : diff) {
      output.append(line).append('\n');
    }

    return output.toString();
  }

  public static String applyPatch(final Path originalFile, final Path patchFile) throws IOException, PatchFailedException {
    final List originalLines = Files.readAllLines(originalFile);
    final List patchLines = Files.readAllLines(patchFile);
    return applyPatch(originalLines, patchLines);
  }

  public static String applyPatch(final List originalLines, final List patchLines) throws PatchFailedException {
    final Patch patch = UnifiedDiffUtils.parseUnifiedDiff(patchLines);
    final List patched = DiffUtils.patch(originalLines, patch);
    final StringBuilder output = new StringBuilder();

    for(final String line : patched) {
      output.append(line).append('\n');
    }

    return output.toString();
  }

  public static String undoPatch(final Path patchedFile, final Path patchFile) throws IOException {
    final List patchedLines = Files.readAllLines(patchedFile);
    final List patchLines = Files.readAllLines(patchFile);
    return undoPatch(patchedLines, patchLines);
  }

  public static String undoPatch(final List patchedLines, final List patchLines) {
    final Patch patch = UnifiedDiffUtils.parseUnifiedDiff(patchLines);
    final List unpatched = DiffUtils.unpatch(patchedLines, patch);
    final StringBuilder output = new StringBuilder();

    for(final String line : unpatched) {
      output.append(line).append('\n');
    }

    return output.toString();
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy