1 module neton.store.Util;
2 import std.stdio;
3 import std.array;
4 import std.string;
5 import std.algorithm.searching;
6 import std.json;
7 
8 const string CONFIG_PREFIX = "/config/";
9 const string SERVICE_PREFIX = "/service/";
10 const string LEASE_PREFIX = "/lease/";
11 const string LEASE_GEN_ID_PREFIX = "/lease/ID";
12 
13 // if the key is "/foo/bar", it will produces result with path "/",
14 // "/foo" and "/foo/bar"
15 
16 bool isRemained(string key)
17 {
18     if (startsWith(key, SERVICE_PREFIX[0 .. $ - 1]) 
19         || startsWith(key, CONFIG_PREFIX[0 .. $ - 1])
20         || startsWith(key, LEASE_PREFIX[0 .. $ - 1]))
21         return true;
22 
23     return false;
24 }
25 
26 string getConfigKey(string name)
27 {
28     return CONFIG_PREFIX ~ removeDelimiter(name);
29 }
30 
31 string getRegistryKey(string name)
32 {
33     return SERVICE_PREFIX ~ removeDelimiter(name);
34 }
35 
36 string getSafeKey(string key)
37 {
38     string result;
39     key = strip(key);
40     if (endsWith(key, "/"))
41         key = key[0 .. $ - 1];
42     if (key.length == 0)
43     {
44         result = "/";
45     }
46     else
47         result = key;
48     if (!startsWith(result, "/"))
49         result = "/" ~ result;
50     return result;
51 }
52 
53 string removeDelimiter(string key)
54 {
55     key = strip(key);
56     if (endsWith(key, "/"))
57         key = key[0 .. $ - 1];
58     if (startsWith(key, "/"))
59         key = key[1 .. $];
60     return key;
61 }
62 
63 string[] getAllParent(string key)
64 {
65     string[] result;
66     key = strip(key);
67     if (endsWith(key, "/"))
68         key = key[0 .. $ - 1];
69     if (key.length == 0)
70     {
71         result ~= "/";
72         return result;
73     }
74     auto segments = split(key, "/");
75     for (int i = 0; i < segments.length; i++)
76     {
77         string path;
78         for (int j = 0; j <= i; j++)
79         {
80             path ~= "/";
81             path ~= segments[j];
82         }
83         if (path.length > 1)
84             result ~= path[1 .. $];
85         else
86             result ~= path;
87     }
88     return result;
89 }
90 
91 string getParent(string key)
92 {
93     string res;
94     auto allP = getAllParent(key);
95     if (allP.length > 1)
96         res = allP[$ - 1 - 1];
97     else
98     {
99         res = allP[0];
100     }
101     if (res == key)
102         return string.init;
103     else
104         return res;
105 }
106 
107 JSONValue tryGetJsonFormat(string json)
108 {
109     JSONValue value;
110     try
111     {
112         value = parseJSON(json);
113     }
114     catch (std.json.JSONException e)
115     {
116         return JSONValue(json);
117     }
118     return value;
119 }