@thigasdevelopment/luam 0.12.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lua/env.lua ADDED
@@ -0,0 +1,91 @@
1
+ local ENVIRONMENT_FILE = '__LUAM_ENV_FILE__'; -- Replaced at build time with the file the manifest selects. (.env, .env.development, ...)
2
+
3
+ ---@param str string
4
+ ---@return string
5
+ local function trim (str)
6
+ return str:match ('^%s*(.-)%s*$');
7
+ end
8
+
9
+ ---@param path string
10
+ ---@return string
11
+ local function load (path)
12
+ local pathType = type (path);
13
+ if (pathType ~= 'string') then
14
+ error ('bad argument #1 to \'load\' (\'string\' expected got \'' .. pathType .. '\').', 2);
15
+ end
16
+
17
+ if (not fileExists (path)) then return end
18
+
19
+ local file = fileOpen (path, true);
20
+ if (not file) then
21
+ error ('Failed to open environment file.', 2);
22
+ end
23
+
24
+ local content = fileRead (file, fileGetSize (file));
25
+ fileClose (file);
26
+
27
+ return content;
28
+ end
29
+
30
+ ---@param value string
31
+ ---@return boolean | number | string
32
+ local function normalize (value)
33
+ local number = tonumber (value);
34
+ if (number) then
35
+ value = number;
36
+ elseif (value:lower () == 'true') then
37
+ value = true;
38
+ elseif (value:lower () == 'false') then
39
+ value = false;
40
+ end
41
+ return value;
42
+ end
43
+
44
+ ---@param content string
45
+ ---@return table<string, any>
46
+ local function parse (content)
47
+ local result = { };
48
+
49
+ local lines = content:gmatch ('[^\r\n]+');
50
+ for line in lines do
51
+ line = trim (line);
52
+ if (line ~= '') and (not line:find ('^#')) then
53
+ local key, value = line:match ('^([%w_]+)%s*=%s*(.*)$');
54
+ if (key and value) then
55
+ if (value:sub (1, 1) == '"' and value:sub (-1) == '"') or (value:sub (1, 1) == "'" and value:sub (-1) == "'") then
56
+ value = value:sub (2, -2);
57
+ end
58
+
59
+ local value = normalize (value);
60
+ result[key] = value;
61
+ end
62
+ end
63
+ end
64
+
65
+ return result;
66
+ end
67
+
68
+ local content = load (ENVIRONMENT_FILE);
69
+ if (not content) then return end
70
+ content = parse (content);
71
+
72
+ env = setmetatable ({ }, {
73
+ ---@param _ string | number
74
+ ---@param key string
75
+ ---@return boolean | number | string
76
+ __index = function (_, key)
77
+ local value = content[key];
78
+ if (value == nil) then
79
+ error ('"' .. tostring(key) .. '" is not declared in "' .. ENVIRONMENT_FILE .. '".', 2);
80
+ end
81
+ return value;
82
+ end,
83
+
84
+ ---@param _ string | number
85
+ ---@param key string
86
+ __newindex = function (_, key)
87
+ error ('The environment is read-only and "' .. tostring(key) .. '" cannot be assigned.', 2);
88
+ end,
89
+
90
+ __metatable = false,
91
+ });