1 /**
2  * Copyright 2018
3  * MIT License
4  * Common operations
5  */
6 module phabricator.common;
7 import phabricator.api;
8 import std.file: exists, readText;
9 import std..string: endsWith, indexOf, split, startsWith;
10 
11 // Result key
12 public enum ResultKey = "result";
13 
14 // Content key
15 public enum ContentKey = "content";
16 
17 // Data key
18 public enum DataKey = "data";
19 
20 // cursor key
21 public enum CursorKey = "cursor";
22 
23 // after key
24 public enum AfterKey = "after";
25 
26 // Custom fields
27 private enum CustomField = "custom.custom:";
28 
29 // Index field
30 public enum IndexField = CustomField ~ "index";
31 
32 // fields key
33 public enum FieldsKey = "fields";
34 
35 // status key
36 public enum StatusKey = "status";
37 
38 // PHID object identifiers
39 public enum PHID = "phid";
40 
41 // Attachments key
42 public enum AttachKey = "attachments";
43 
44 // Raw key
45 public enum RawKey = "raw";
46 
47 /**
48  * Settings to construct apis from
49  */
50 public struct Settings
51 {
52     // host/url to connect to
53     string url;
54 
55     // conduit token
56     string token;
57 }
58 
59 /**
60  * Create a new api from settings
61  */
62 public static T construct(T : PhabricatorAPI)(Settings settings)
63     if (is(typeof(new T()) == T))
64 {
65     auto api = new T();
66     api.url = settings.url;
67     api.token = settings.token;
68     return api;
69 }
70 
71 /**
72  * Load environment variables
73  */
74 public static string[string] loadEnvironmentFile(string envFile, string filter)
75 {
76     string[string] vars;
77     vars["env"] = envFile;
78     loadEnvironmentFile(vars, envFile, filter);
79     return vars;
80 }
81 
82 /**
83  * Load into an existing associative array
84  */
85 public static void loadEnvironmentFile(string[string] vars, string envFile, string filter)
86 {
87     if (vars == null)
88     {
89         throw new Exception("map is null, aborting");
90     }
91 
92     if (exists(envFile))
93     {
94         auto text = readText(envFile);
95         foreach (string line; text.split("\n"))
96         {
97             loadSetting(vars, line, filter);
98         }
99     }
100 }
101 
102 /**
103  * Load settings
104  */
105 public static void loadSetting(string[string] vars, string line, string varFilter)
106 {
107     auto filter = varFilter;
108     if (filter == null)
109     {
110         filter = "";
111     }
112 
113     if (line.startsWith(filter))
114     {
115         auto segment = line[filter.length..line.length];
116         auto idx = segment.indexOf("=");
117         if (idx > 0)
118         {
119             auto key = segment[0..idx];
120             auto val = segment[idx + 1..segment.length];
121             if (val.startsWith("\"") && val.endsWith("\""))
122             {
123                 val = val[1..val.length - 1];
124             }
125             vars[key] = val;
126         }
127     }
128 }