Adopt odlparent-10.0.0/yangtools-8.0.0-SNAPSHOT
[mdsal.git] / binding / mdsal-binding-test-utils / src / main / java / org / opendaylight / mdsal / binding / testutils / DiffUtil.java
1 /*
2  * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.testutils;
9
10 import com.github.difflib.DiffUtils;
11 import com.github.difflib.UnifiedDiffUtils;
12 import com.github.difflib.patch.Patch;
13 import com.google.common.base.Joiner;
14 import com.google.common.base.Splitter;
15 import java.util.List;
16
17 /**
18  * Utility to create diff of text.
19  *
20  * @author Michael Vorburger
21  */
22 // package-local: no need to expose this, consider it an implementation detail; public API is the AssertDataObjects
23 final class DiffUtil {
24     // Configuration which we could tune as we use this more
25     private static final int MAX_DIFFS = 1;
26     // number of lines of context output around each difference
27     private static final int CONTEXT_LINES = 3;
28
29     private static final Splitter SPLITTER = Splitter.on(System.getProperty("line.separator"));
30     private static final Joiner JOINER = Joiner.on(System.getProperty("line.separator"));
31
32     private DiffUtil() {
33
34     }
35
36     static String diff(final String expectedText, final String actualText) {
37         List<String> originalLines = SPLITTER.splitToList(expectedText);
38         List<String> revisedLines = SPLITTER.splitToList(actualText);
39         Patch<String> patch = DiffUtils.diff(originalLines, revisedLines);
40         List<String> diff =
41             UnifiedDiffUtils.generateUnifiedDiff("expected", "actual", originalLines, patch, CONTEXT_LINES);
42
43         String header = "";
44         int deltas = patch.getDeltas().size();
45         if (deltas > MAX_DIFFS) {
46             header = String.format("(Too many differences (%d); only showing first %d)%n", deltas, MAX_DIFFS);
47             diff = diff.subList(0, MAX_DIFFS);
48         }
49         return header + JOINER.join(diff);
50     }
51 }