001package org.hl7.fhir.utilities.i18n;
002
003import java.io.File;
004import java.io.FileNotFoundException;
005import java.io.IOException;
006import java.nio.file.Files;
007import java.util.ArrayList;
008import java.util.Collections;
009import java.util.Comparator;
010import java.util.HashMap;
011import java.util.HashSet;
012import java.util.List;
013import java.util.Map;
014import java.util.Set;
015
016import org.hl7.fhir.utilities.StringPair;
017import org.hl7.fhir.utilities.FileUtilities;
018import org.hl7.fhir.utilities.Utilities;
019import org.hl7.fhir.utilities.filesystem.DirectoryVisitor;
020import org.hl7.fhir.utilities.filesystem.DirectoryVisitor.IDirectoryVisitorImplementation;
021import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
022
023/**
024 * This class checks that all the i18n constants and declarations are consistent,
025 * and then generates / updates the .po source files, and then updates the .properties files
026 * 
027 * It needs to be run whenever
028 *   (a) New constants are added to the java code
029 *   (b) An implementer contributes translations in a .po source file
030 *   
031 * It takes 3 parameters:
032 *   * path to the local copy of the core repo
033 *   * path to the local copy of the ig-publisher repo
034 *   * path to the local copy of the fhirserver repo
035 */
036public class POGenerator {
037
038  public class PropertyValue extends StringPair {
039    private boolean used;
040    
041    public PropertyValue(String name, String value) {
042      super(name, value);
043      // TODO Auto-generated constructor stub
044    }
045
046    public String getBaseName() {
047      String res = getName();
048      if (res.endsWith("_one")) {
049        res = res.substring(0, res.length()-4);
050      } else if (res.endsWith("_other")) {
051        res = res.substring(0, res.length()-6);
052      }
053      return res;
054    }
055
056  }
057
058  public class ConstantDefinition {
059    private String name;
060    private String sname;
061    private boolean defined;
062    private boolean used;
063  }
064
065  public class POObjectSorter implements Comparator<POObject> {
066
067    @Override
068    public int compare(POObject o1, POObject o2) {
069      return o1.id.compareTo(o2.id);
070    }
071  }
072
073  private class POObject {
074    private boolean orphan = true;
075    private boolean duplicate;
076    private String id;
077    private String msgid;
078    private String oldMsgId;
079    private String msgidPlural;
080    private String comment;
081    private List<String> msgstr  = new ArrayList<String>();
082  }
083  
084
085  public static void main(String[] args) throws IOException {
086    new POGenerator().execute(args[0], args[1], args[2]);
087  }
088
089  private List<String> prefixes = new ArrayList<>();
090  private int noTrans = 0;
091
092  private void execute(String core, String igpub, String pascal) throws IOException {
093    String source = Utilities.path(core, "/org.hl7.fhir.utilities/src/main/resources");
094    if (checkState(source, core, igpub, pascal)) {
095      generate(source, "rendering-phrases.properties",  "rendering-phrases-en.po",       null, 2);
096      generate(source, "rendering-phrases.properties",  "rendering-phrases-de.po",    "rendering-phrases_de.properties", 2);
097      generate(source, "rendering-phrases.properties",  "rendering-phrases-es.po",    "rendering-phrases_es.properties", 3);
098      generate(source, "rendering-phrases.properties",  "rendering-phrases-ja.po",    "rendering-phrases_ja.properties", 2);
099      generate(source, "rendering-phrases.properties",  "rendering-phrases-fr.po",    "rendering-phrases_fr.properties", 2);
100      generate(source, "rendering-phrases.properties",  "rendering-phrases-nl.po",    "rendering-phrases_nl.properties", 2);
101      generate(source, "rendering-phrases.properties",  "rendering-phrases-pt_BR.po", "rendering-phrases_pt_BR.properties", 2);
102
103      generate(source, "Messages.properties", "validator-messages-en.po",    null, 2);
104      generate(source, "Messages.properties", "validator-messages-de.po",    "Messages_de.properties", 2);
105      generate(source, "Messages.properties", "validator-messages-es.po",    "Messages_es.properties", 3);
106      generate(source, "Messages.properties", "validator-messages-ja.po",    "Messages_ja.properties", 2);
107      generate(source, "Messages.properties", "validator-messages-fr.po",    "Messages_fr.properties", 2);
108      generate(source, "Messages.properties", "validator-messages-nl.po",    "Messages_nl.properties", 2);
109      generate(source, "Messages.properties", "validator-messages-pt_BR.po", "Messages_pt_BR.properties", 2);
110
111      System.out.println("Finished");
112    } 
113  }
114
115  private boolean checkState(String source, String core, String igpub, String pascal) throws IOException {
116    System.out.println("Checking...");
117    List<PropertyValue> props = loadProperties(Utilities.path(source, "rendering-phrases.properties"), true);
118    List<ConstantDefinition> consts = loadConstants(Utilities.path(core, "/org.hl7.fhir.utilities/src/main/java/org/hl7/fhir/utilities/i18n/RenderingI18nContext.java"));
119    boolean ok = true;
120    for (ConstantDefinition cd : consts) {
121      boolean found = false;
122      for (PropertyValue p : props) {
123        String pn = p.getBaseName();        
124        if (pn.equals(cd.sname) || p.getName().equals(cd.sname)) {
125          found = true;
126          p.used = true;
127        }
128      }
129      cd.defined = found;
130    }
131    scanJavaSource(core, consts, "RenderingI18nContext", "RenderingContext");
132    scanJavaSource(igpub, consts, "RenderingI18nContext", "RenderingContext");
133    scanPascalSource(pascal, props);
134    
135    Set<String> pns = new HashSet<>();
136    for (PropertyValue p : props) {
137      if (!p.used) {
138        ok = false;
139        System.out.println("Error: PV "+p.getName()+ " provided but not used");   
140      }
141      if (!pns.contains(p.getName())) {
142        pns.add(p.getName());
143      } else {
144        System.out.println("Error: PV "+p.getName()+ " duplicated");
145      }
146      if (p.getValue().contains("\\n")) {
147        System.out.println("Error: PV "+p.getName()+ " has a \\n");
148      }
149    }
150    
151    for (ConstantDefinition cd : consts) {
152      if (!cd.defined && !cd.used) {
153        System.out.println("Error: "+cd.name+ " not defined or used");        
154        ok = false;
155      } else if (!cd.defined) {
156        ok = false;
157        System.out.println("Error: msg for "+cd.name+ " not found at "+cd.sname);
158      } else if (!cd.used) {
159        System.out.println("Warning: const "+cd.name+ " not used");
160        // ok = false;
161      }
162    }
163
164    props = loadProperties(Utilities.path(source, "Messages.properties"), true);
165    consts = loadConstants(Utilities.path(core, "/org.hl7.fhir.utilities/src/main/java/org/hl7/fhir/utilities/i18n/I18nConstants.java"));
166    for (ConstantDefinition cd : consts) {
167      boolean found = false;
168      for (PropertyValue p : props) {
169        String pn = p.getBaseName();
170        if (pn.equals(cd.sname) || p.getName().equals(cd.sname)) {
171          found = true;
172          p.used = true;
173        }
174      }
175      cd.defined = found;
176    }
177
178    scanJavaSource(core, consts, "I18nConstants");
179    scanJavaSource(igpub, consts, "I18nConstants");
180    scanPascalSource(pascal, props);
181
182    pns = new HashSet<>();
183    for (PropertyValue p : props) {
184      if (!p.used) {
185        ok = false;
186        System.out.println("Error: PV "+p.getName()+ " provided but not used");   
187      }
188      if (!pns.contains(p.getName())) {
189        pns.add(p.getName());
190      } else {
191        System.out.println("Error: PV "+p.getName()+ " duplicated");
192      }      
193      if (p.getValue().contains("\\n")) {
194        System.out.println("Error: PV "+p.getName()+ " has a \\n");
195      }
196
197    }
198    
199    for (ConstantDefinition cd : consts) {
200      if (!cd.defined && !cd.used) {
201        System.out.println("Error: "+cd.name+ " not defined or used");        
202        ok = false;
203      } else if (!cd.defined) {
204        ok = false;
205        System.out.println("Error: msg for "+cd.name+ " not found @ "+cd.sname);
206      } else if (!cd.used) {
207        System.out.println("Warning: const "+cd.name+ " not used");
208        // ok = false;
209      }
210    }
211    if (ok) {
212      System.out.println("No Errors Found");
213    } else {
214      System.out.println("Errors Found, so not continuing");  
215    }
216
217    return ok;
218  }
219
220  private class JavaScanner implements IDirectoryVisitorImplementation {
221    List<ConstantDefinition> consts;
222    List<String> names;
223    
224    @Override
225    public boolean enterDirectory(File f) throws IOException {
226      return !Utilities.existsInList(f.getName(), "model", "formats");
227    }
228
229    @Override
230    public boolean visitFile(File file) throws IOException {
231      String source = FileUtilities.fileToString(file);
232      for (ConstantDefinition cd : consts) {
233        if (!cd.used) {
234          boolean found = false;
235          for (String n : names) {
236            if (source.contains(n+"."+cd.name+",")) {
237              found = true;
238            } 
239            if (source.contains(n+"."+cd.name+")")) {
240              found = true;
241            } 
242            if (source.contains(n+"."+cd.name+" :")) {
243              found = true;
244            } 
245            if (source.contains(n+"."+cd.name+";")) {
246              found = true;
247            } 
248          } 
249          if (found) {
250            cd.used = true;
251          }
252        }  
253      }
254      return true;
255    }
256  }
257  
258  private void scanJavaSource(String path, List<ConstantDefinition> consts, String... names) throws FileNotFoundException, IOException {
259    JavaScanner scanner = new JavaScanner();
260    scanner.consts = consts;
261    scanner.names = new ArrayList<String>();
262    for (String s : names) {
263      scanner.names.add(s);
264    }
265    DirectoryVisitor.visitDirectory(scanner, path, "java");
266  }
267
268  private class PascalScanner implements IDirectoryVisitorImplementation {
269    private List<PropertyValue> defs;
270    
271    @Override
272    public boolean enterDirectory(File directory) throws IOException {
273      return true;
274    }
275
276    @Override
277    public boolean visitFile(File file) throws IOException {
278      String source = FileUtilities.fileToString(file);
279      for (PropertyValue pv : defs) {
280        if (!pv.used) {
281          boolean found = false;
282          String pn = pv.getBaseName();
283          if (source.contains("'"+pn+"'")) {
284            found = true;
285          } 
286          if (found) {
287            pv.used = true;
288          }
289        }
290      }
291      return true;
292    }
293  }
294  
295  private void scanPascalSource(String path, List<PropertyValue> defs) throws FileNotFoundException, IOException {
296    PascalScanner scanner = new PascalScanner();
297    scanner.defs = defs;
298    DirectoryVisitor.visitDirectory(scanner, path, "pas");
299  }
300
301  
302  private List<ConstantDefinition> loadConstants(String path) throws FileNotFoundException, IOException {
303    List<ConstantDefinition> res = new ArrayList<POGenerator.ConstantDefinition>();
304    for (String line : FileUtilities.fileToLines(path)) {
305      if (line.contains("public static final String") && !line.trim().startsWith("//")) {
306        int i = line.indexOf("public static final String") + "public static final String".length();
307        String[] p = line.substring(i).split("\\=");
308        if (p.length == 2) {
309          String n = p[0].trim();
310          String v = p[1].trim().replace("\"", "").replace(";", "");
311          ConstantDefinition cd = new ConstantDefinition();
312          cd.name = n;
313          cd.sname = v;
314          res.add(cd);
315        }
316      }
317    }
318    return res;
319  }
320
321  private void generate(String source, String src, String dest, String tgt, int count) throws IOException {
322    // load the destination file 
323    // load the source file 
324    // update the destination object set for changes from the source file
325    // save the destination file 
326    String fn = Utilities.path(source, "source", dest);
327    List<POObject> objects;
328    if (ManagedFileAccess.file(fn).exists()) {
329      objects = loadPOFile(fn);
330    } else {
331      objects = new ArrayList<POGenerator.POObject>();
332    }
333    List<PropertyValue> props = loadProperties(Utilities.path(source, src), false);
334    for (PropertyValue e : props) {
335      String name = e.getName();
336      int mode = 0;
337      if (name.endsWith("_one")) {
338        mode = 1;
339        name = name.substring(0, name.length() - 4);
340      } else if (name.endsWith("_other")) {
341        mode = 2;
342        name = name.substring(0, name.length() - 6);
343      } 
344
345      POObject o = findObject(objects, name);
346      if (o == null) {
347        if (mode > 1) {
348          throw new Error("Not right");
349        }
350        o = new POObject();
351        o.id = name;
352        o.comment = name;
353        objects.add(o);
354        o.msgid = e.getValue();
355        o.orphan = false;
356      } else {
357        update(o, mode, e.getValue());
358      }
359    }
360    objects.removeIf(o -> o.orphan);
361    Collections.sort(objects, new POObjectSorter());
362    Map<String, Integer> sources = new HashMap<>();
363    Set<String> dups = new HashSet<>();
364    for (POObject o : objects) {
365      if (sources.containsKey(o.msgid)) {
366        Integer c = sources.get(o.msgid)+1;
367        sources.put(o.msgid, c);
368        dups.add(o.msgid);
369//        System.out.println("Duplicate in "+dest.substring(dest.lastIndexOf("/")+1)+": "+o.msgid+" on ("+CommaSeparatedStringBuilder.join(",", listIds(objects, o.msgid))+")");
370      } else {
371        sources.put(o.msgid, 1);
372      }
373    }
374    for (POObject o : objects) {
375      Integer c = sources.get(o.msgid);
376      if (c > 1) {
377        o.duplicate = true;
378      }
379    }
380    savePOFile(Utilities.path(source, "source", dest), objects, count, false);
381    if (tgt == null) {
382      savePOFile(Utilities.path(source, "source", "transifex", dest), objects, count, true);
383    } else {
384      savePOFile(Utilities.path(source, "source", "transifex", "translations", dest), objects, count, true);
385    }
386    if (tgt != null) {
387      savePropFile(Utilities.path(source, tgt), objects);
388    }
389  }
390
391  private Set<String> listIds(List<POObject> objects, String msgid) {
392    Set<String> res = new HashSet<>();
393    for (POObject o : objects) {
394      if (o.msgid.equals(msgid)) {
395        res.add(o.id);
396      }
397    }
398    return res;
399  }
400
401  private void savePOFile(String dest, List<POObject> objects, int count, boolean tfxMode) throws IOException {
402    prefixes.clear();
403    
404    StringBuilder b = new StringBuilder();
405    for (String p : prefixes) {
406      b.append(p);
407      b.append("\r\n");
408    }
409    b.append("\r\n");
410    for (POObject o : objects) {
411      // for POEdit
412      if (o.oldMsgId != null) {
413        b.append("# "+o.comment+" (!!when last translated was: "+o.oldMsgId+")\r\n");        
414      } else {
415        b.append("# "+o.comment+"\r\n");
416      }
417      b.append("#: "+o.id+"\r\n");
418      if (o.duplicate) {
419        b.append("msgctxt \""+o.id+"\"\r\n");        
420      } 
421      String m = tfxMode && Utilities.noString(o.msgid) ? "-- no content: do not translate #"+(++noTrans )+" --" : o.msgid; 
422      b.append("msgid \""+wrapQuotes(m)+"\"\r\n");
423      if (o.msgidPlural != null) {
424        b.append("msgid_plural \""+wrapQuotes(o.msgidPlural)+"\"\r\n"); 
425        while (o.msgstr.size() < count) {
426          o.msgstr.add("");
427        }
428        for (int i = 0; i < o.msgstr.size(); i++) {
429          String s = o.msgstr.get(i);
430//          if (tfxMode && Utilities.noString(s)) {
431//            s = Utilities.noString(i == 0 ? o.msgid : o.msgidPlural) ? "-- no content: do not translate --" : "";
432//          }
433          b.append("msgstr["+i+"] \""+wrapQuotes(s)+"\"\r\n");
434        }
435      } else {
436        if (o.msgstr.size() == 0) {
437          b.append("msgstr \"\"\r\n");                  
438        } else {
439          b.append("msgstr \""+wrapQuotes(o.msgstr.get(0))+"\"\r\n");                            
440        }
441      } 
442      b.append("\r\n");
443    }
444    FileUtilities.stringToFile(b.toString(), dest);
445  }
446
447  private String wrapQuotes(String s) {
448    return s.replace("\"", "\\\"");
449  }
450
451  private void update(POObject o, int mode, String value) {
452    o.orphan = false;
453    if (o.comment == null) {
454      o.comment = o.id;
455    }
456    if (mode == 0) {
457      if (!value.equals(o.msgid)) {
458        // the english string has changed, and the other language string is now out of date
459        if (o.oldMsgId != null && !o.msgstr.isEmpty()) {
460          o.oldMsgId = o.msgid;
461        }
462        o.msgid = value;
463        for (int i = 0; i < o.msgstr.size(); i++) {
464          if (!Utilities.noString(o.msgstr.get(i))) {
465            o.msgstr.set(i, "!!"+o.msgstr.get(i));
466          }
467        }
468      } else {
469        o.oldMsgId = null;
470      }
471    } else if (mode == 1) {
472      if (!value.equals(o.msgid)) {
473        // the english string has changed, and the other language string is now out of date 
474        if (o.oldMsgId != null && !o.msgstr.isEmpty()) {
475          o.oldMsgId = o.msgid;
476        }
477        o.msgid = value;
478        if (o.msgstr.size() > 0 && !Utilities.noString(o.msgstr.get(0))) {
479          o.msgstr.set(0, "!!"+o.msgstr.get(0));
480        }
481      } else {
482        o.oldMsgId = null;
483      }
484    } else if (mode == 2) {
485      if (!value.equals(o.msgidPlural)) {
486        // the english string has changed, and the other language string is now out of date 
487//        if (o.oldMsgId != null) {
488//          o.oldMsgId = o.msgid;
489//        }
490        o.msgidPlural = value;
491        if (o.msgstr.size() > 1 && !Utilities.noString(o.msgstr.get(1))) {
492          o.msgstr.set(1, "!!"+o.msgstr.get(1));
493        }
494      } else {
495        o.oldMsgId = null;
496      }
497    }
498  }
499
500  private POObject findObject(List<POObject> objects, String name) {
501    for (POObject t : objects) {
502      if (t.id != null && t.id.equals(name)) {
503        return t;
504      }
505    }
506    return null;
507  }
508
509  private List<POObject> loadPOFile(String dest) throws FileNotFoundException, IOException {
510    List<POObject> list = new ArrayList<POGenerator.POObject>();
511    POObject obj = null;
512    for (String line : FileUtilities.fileToLines(dest)) {
513      if (Utilities.noString(line)) {
514        // else 
515      } else if (line.startsWith("#:")) {
516        if (obj == null || obj.id != null) {
517          obj = new POObject();
518          list.add(obj);
519        }
520        obj.id = line.substring(2).trim();  
521      } else if (line.startsWith("# ")) {
522        if (obj == null || obj.comment != null) {
523          obj = new POObject();
524          list.add(obj);
525        }
526        obj.comment = line.substring(1).trim();
527        if (obj.comment.contains("!!when")) {
528          obj.oldMsgId = obj.comment.substring(obj.comment.indexOf("!!when"));
529          obj.comment = obj.comment.substring(0, obj.comment.indexOf("!!when")-1);
530          obj.oldMsgId = obj.oldMsgId.substring(obj.oldMsgId.indexOf(": ")+2).trim();
531          obj.oldMsgId = obj.oldMsgId.substring(0, obj.oldMsgId.length()-1);
532        }
533      } else if (obj == null) {
534        prefixes.add(line);  
535      } else if (line.startsWith("#|")) {
536        // retired use of #| because it caused problems with the tools
537        obj.oldMsgId = line.substring(2).trim();
538        if (obj.oldMsgId.startsWith("msgid ")) {
539          obj.oldMsgId = trimQuotes(obj.oldMsgId.substring(6));
540        }
541      } else if (line.startsWith("msgid ")) {
542        obj.msgid = trimQuotes(line.substring(5).trim());
543        if (obj.msgid.endsWith("("+obj.id+")")) {
544          obj.msgid = obj.msgid.substring(0, obj.msgid.length() - (obj.id.length()+3));
545        }
546      } else if (line.startsWith("msgid_plural ")) {
547        obj.msgidPlural = trimQuotes(line.substring(12).trim());
548      } else if (line.startsWith("msgstr ")) {
549        obj.msgstr.add(trimQuotes(line.substring(6).trim()));
550      } else if (line.startsWith("msgctxt ")) {
551        // ignore this
552      } else if (line.startsWith("msgstr[")) {
553        String s = line.substring(7);
554        int i = s.indexOf("]");
555        int c = Integer.valueOf(s.substring(0, i));
556        s = trimQuotes(s.substring(i+1).trim());
557        while (s.startsWith("!!")) {
558          s = s.substring(2);
559        }
560        if (c != obj.msgstr.size()) {
561          System.out.println("index issue");   
562        } else { // if (!Utilities.noString(s)) {
563          obj.msgstr.add(s);          
564        }
565      } else {
566        System.out.println("unknown line: "+line);          
567      }
568    }
569    return list;
570  }
571
572  private String trimQuotes(String s) {
573    s = s.trim();
574    if (s.startsWith("\"")) {
575      s = s.substring(1);
576    }
577    if (s.endsWith("\"")) {
578      s = s.substring(0, s.length()-1);
579    }
580    return s.trim().replace("\\\"", "\"");
581  }
582
583  private List<PropertyValue> loadProperties(String source, boolean checking) throws IOException {
584    List<PropertyValue> res = new ArrayList<>();
585    File src = ManagedFileAccess.file(source);
586    List<String> lines = Files.readAllLines(src.toPath());
587    for (String line : lines) {
588      if (!line.startsWith("#") && line.contains("=")) {
589        String n = line.substring(0, line.indexOf("=")).trim();
590        String v = line.substring(line.indexOf("=")+1).trim();
591        if (checking || !(v.length() == 3 && v.startsWith("{") && v.endsWith("}"))) {
592          res.add(new PropertyValue(n, v));
593        }
594      } 
595    }
596    return res;
597  }
598
599  private void savePropFile(String tgt, List<POObject> objects) throws IOException {
600    String nameLine = FileUtilities.fileToLines(tgt).get(0);
601    String[] parts = nameLine.substring(1).trim().split("\\=");
602    String[] names = parts[1].split("\\,");
603    
604    StringBuilder b = new StringBuilder();
605    b.append(nameLine+"\r\n");
606    for (POObject o : objects) {
607      if (o.msgidPlural == null) {
608        String v= o.msgstr.size() > 0 ? o.msgstr.get(0) : "";
609        if (!Utilities.noString(v)) {
610          b.append(o.id+" = "+v+"\r\n");
611        }
612      } else {
613        for (int i = 0; i < names.length; i++) {
614          String v = (o.msgstr.size() > i ? o.msgstr.get(i) : "");
615          if (!Utilities.noString(v)) {
616            b.append(o.id+"_"+names[i].trim()+" = "+v+"\r\n");
617          }
618        }
619      }
620    }
621    
622    FileUtilities.stringToFile(b.toString(), tgt);
623  }
624
625  
626}