LanguageFileCompare.java 5.61 KB
Newer Older
王品堯's avatar
王品堯 committed
1 2 3
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
4 5
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
王品堯's avatar
王品堯 committed
6

王品堯's avatar
王品堯 committed
7 8 9 10
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
王品堯's avatar
王品堯 committed
11
import java.io.FileInputStream;
王品堯's avatar
王品堯 committed
12
import java.io.FileReader;
王品堯's avatar
王品堯 committed
13
import java.io.IOException;
王品堯's avatar
王品堯 committed
14 15 16 17 18 19 20
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

王品堯's avatar
王品堯 committed
21 22
public class LanguageFileCompare {
  private static Logger log = LoggerFactory.getLogger(LanguageFileCompare.class);
王品堯's avatar
王品堯 committed
23 24

  public static void main(String[] args) {
王品堯's avatar
王品堯 committed
25 26 27 28
    if (args.length > 0) {
      Path originPath = Paths.get(args[0]);
      JsonNode twJson = getJsonNode(originPath);
      if (twJson != null) {
王品堯's avatar
王品堯 committed
29 30
        Set<String> originSet = new HashSet<>();
        addKeys("", twJson, originSet, new ArrayList<>());
王品堯's avatar
王品堯 committed
31

王品堯's avatar
王品堯 committed
32 33 34
        IntStream.range(1, args.length)
            .forEach(i -> findMissingKeys(Paths.get(args[i]), originSet));
      }
王品堯's avatar
王品堯 committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
    }
    checkProperties();
  }

  private static JsonNode getJsonNode(Path path) {
    String ext = path.getFileName().toString();
    try {
      ObjectMapper objectMapper = new ObjectMapper();
      if (ext.endsWith(".json")) {
        /* CHM、HRB */
        return objectMapper.readTree(new String(Files.readAllBytes(path)));
      } else if (ext.endsWith(".js")) {
        /* CHMB use js file to translate */
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine engine = scriptEngineManager.getEngineByName("Nashorn");
        engine.eval(new FileReader(path.toFile()));
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        return objectMapper.valueToTree(bindings.get("local"));
      }
王品堯's avatar
王品堯 committed
54
    } catch (Exception e) {
王品堯's avatar
王品堯 committed
55
      log.error("{} is not exists or file not correct.", path.getFileName(), e);
王品堯's avatar
王品堯 committed
56 57
      System.exit(1);
    }
王品堯's avatar
王品堯 committed
58
    return null;
王品堯's avatar
王品堯 committed
59 60
  }

王品堯's avatar
王品堯 committed
61 62
  private static void addKeys(
      String currentPath, JsonNode jsonNode, Set<String> set, List<Integer> suffix) {
王品堯's avatar
王品堯 committed
63 64 65 66 67 68 69 70 71 72 73
    if (jsonNode.isObject()) {
      ObjectNode objectNode = (ObjectNode) jsonNode;
      Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
      String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "-";

      while (iter.hasNext()) {
        Map.Entry<String, JsonNode> entry = iter.next();
        addKeys(pathPrefix + entry.getKey(), entry.getValue(), set, suffix);
      }

    } else if (jsonNode.isValueNode()) {
74
      StringBuilder sb = new StringBuilder(currentPath);
王品堯's avatar
王品堯 committed
75
      if (currentPath.contains("-")) {
76 77
        for (Integer suffix1 : suffix) {
          sb.append("-").append(suffix1);
王品堯's avatar
王品堯 committed
78 79
        }
      }
80
      set.add(sb.toString());
王品堯's avatar
王品堯 committed
81 82 83
    }
  }

84
  private static void findMissingKeys(Path targetPath, Set<String> originSet) {
王品堯's avatar
王品堯 committed
85 86
    if (!targetPath.toFile().exists()) return;

王品堯's avatar
王品堯 committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    Set<String> targetSet = new HashSet<>();
    JsonNode json = getJsonNode(targetPath);
    if (json == null) return;

    addKeys("", json, targetSet, new ArrayList<>());

    Set<String> missingKey =
        originSet
            .parallelStream()
            .filter(key -> !targetSet.contains(key))
            .collect(Collectors.toSet());
    if (!missingKey.isEmpty()) {
      log.error(
          "Missing Key on {} \nMissing Keys: {}",
          targetPath.getFileName(),
          missingKey.stream().sorted().collect(Collectors.toList()));
王品堯's avatar
王品堯 committed
103 104 105
      System.exit(1);
    }
  }
王品堯's avatar
王品堯 committed
106 107 108 109 110 111 112

  private static void checkProperties() {
    String path = "./src/main/resources/i18n/";
    String extension = ".properties";

    Map<String, List<String>> map =
        Arrays.stream(
王品堯's avatar
王品堯 committed
113 114 115
                Optional.ofNullable(
                        Paths.get(path).toFile().list((dir, name) -> name.endsWith(extension)))
                    .orElse(new String[0]))
王品堯's avatar
王品堯 committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
            .map(s -> s.split(extension)[0])
            .collect(
                Collectors.groupingBy(
                    filename -> filename.split("_")[0],
                    Collectors.mapping(l -> path + l + extension, Collectors.toList())));

    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
      List<String> twList =
          entry
              .getValue()
              .stream()
              .filter(fileName -> fileName.contains("zh_TW"))
              .collect(Collectors.toList());
      List<String> otherList =
          entry
              .getValue()
              .stream()
              .filter(fileName -> !fileName.contains("zh_TW"))
              .collect(Collectors.toList());
      if (twList.isEmpty() || otherList.isEmpty()) continue;

      try {
        Set<String> originKeySet = getKeys(twList.get(0));
        for (String target : otherList) {
          Set<String> targetKeySet = getKeys(target);
          Set<String> missingSet =
              originKeySet
                  .parallelStream()
                  .filter(k -> !targetKeySet.contains(k))
                  .collect(Collectors.toSet());
          if (!missingSet.isEmpty()) {
            log.error(
                "Missing Key on {} \nMissing Keys: {}",
                Paths.get(target).getFileName(),
                missingSet);
            System.exit(1);
          }
        }
      } catch (Exception e) {
        log.error("check i18n properties error.", e);
        System.exit(1);
      }
    }
  }

  private static Set<String> getKeys(String fileName) throws IOException {
    Properties properties = new Properties();
    properties.load(new FileInputStream(fileName));
    return new HashSet(Collections.list(properties.propertyNames()));
  }
王品堯's avatar
王品堯 committed
166
}