1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.data.i18n.loader;
7 
8 import diamond.core.apptype;
9 
10 static if (isWeb)
11 {
12   /**
13   * Loads a language file for i18n use.
14   * The format of the file must be like shown in the example:
15   * Examples:
16   * --------------------
17   * MESSAGE_KEY=SINGLE-LINE MESSAGE
18   *
19   * ...
20   *
21   * MESSAGE_KEY:
22   * MULTI-LINE
23   * MESSAGE
24   * ;
25   * --------------------
26   * Params:
27   *   languageName = The name of the language.
28   *   languageFile = The file for the localization content.
29   */
30   void loadLanguageFile(string languageName, string languageFile)
31   {
32     import std.file : exists, readText;
33     import std.array : replace, split;
34     import std..string : strip, stripLeft, stripRight, indexOf;
35     import std.algorithm : map;
36 
37     import diamond.errors.checks;
38     import diamond.data.i18n.messages;
39 
40     enforce(exists(languageFile), "Cannot find language file.");
41 
42     auto lines = readText(languageFile).replace("\r", "").split("\n");
43 
44     bool multiLine;
45     string key = "";
46     string message = "";
47 
48     foreach (line; lines.map!(l => l.stripRight()))
49     {
50       if (multiLine)
51       {
52         if (line == ";" && message[$-1] != 0x5c/*0x5c = '\'*/)
53         {
54           multiLine = false;
55           addMessage(languageName, key, message);
56           continue;
57         }
58         else
59         {
60           message ~= (line.stripLeft().length ? line : "") ~ "\r\n";
61           continue;
62         }
63       }
64 
65       if (!line.strip().length)
66       {
67         continue;
68       }
69 
70       auto keyEndIndex = line.indexOf('=');
71 
72       if (keyEndIndex == -1 && line[$-1] == ':')
73       {
74         multiLine = true;
75         key = line[0 .. $-1];
76         message = "";
77         continue;
78       }
79 
80       enforce(keyEndIndex > 0, "Found no message key");
81       enforce(keyEndIndex < line.length, "Found no message value.");
82 
83       key = line[0 .. keyEndIndex].stripLeft();
84       message = line[keyEndIndex + 1 .. $].strip();
85 
86       addMessage(languageName, key, message);
87     }
88   }
89 }