-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiles.lua
396 lines (324 loc) · 9 KB
/
files.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
local M = {}
---@param source? string caller debug.getinfo(1).source
---@return string dir path to dir of calling script
---@nodiscard
local function get_script_dir(source)
source = source or debug.getinfo(1).source
local script = source:gsub("^@", ""):gsub("[\\/]", "/")
if script:match("^[a-zA-Z]:[\\/]") then
return "" .. script:gsub("[\\/]+[^\\/]*$", "")
end
local pwd_cmd = package.config:sub(1, 1) == "/" and "pwd" or "echo %cd%"
local pipe = io.popen(pwd_cmd)
local cwd = pipe and pipe:read("*l"):gsub("[\\/]+$", ""):gsub("[\\/]", "/")
if pipe then
pipe:close()
end
local dir = cwd or "."
if script:match("[\\/][^\\/]+$") then
dir = dir .. "/" .. script:gsub("[\\/]+[^\\/]*$", "")
end
return dir
end
local old_package_path = package.path
package.path = get_script_dir() .. "/?.lua"
local json = require("json")
package.path = old_package_path
local vimfn = (vim or {}).fn or {}
local is_windows = (function()
local is_ok, has_win = pcall(vimfn.has, "win32")
if is_ok then
return has_win > 0
end
return package.config:sub(1, 1) == "\\"
end)()
local function dirname(filename)
local d = filename:match("^(.*[\\/]).+$")
if d ~= nil then
d = d:match("^(.+)[\\/]+$") or d
end
return d
end
local function fix_numeric_keys(o)
if type(o) ~= "table" then
return o
end
local remapped = {}
for key, value in pairs(o) do
if type(key) == "string" then
key = tonumber(key) or key
end
if type(value) == "table" then
value = fix_numeric_keys(value)
end
remapped[key] = value
end
return remapped
end
local function _str_strip(s)
return s:gsub("^%s+", ""):gsub("%s+$", "")
end
local function _str_escape(s)
return s:gsub('"', '"')
end
local function _is_file(filename)
local f = io.open(filename, "r")
return f ~= nil and io.close(f)
end
local function _is_filename_sane(filename)
local s = filename:gsub("^%s*[a-zA-Z]:[\\/]?", "")
return not (s:match("[^a-zA-Z0-9/\\%.%-_'()%[%] ]") and true)
end
local function _exec(cmd, strip)
strip = strip ~= false
local status_ok, pipe = pcall(io.popen, cmd)
if not status_ok or not pipe then
return nil
end
pipe:flush()
local result = pipe:read("*a")
pipe:close()
if strip and result then
strip = _str_strip(result)
end
return result
end
local function _path(syspath)
syspath = syspath or os.getenv("PATH")
local dirs = {}
while syspath and #syspath > 0 do
local pat = "^%s*(.-)%s*[;:][;:%s]*" -- unix path
if syspath:match("^%s*[a-zA-Z]:[\\/]") then
pat = "^%s*([a-zA-Z]:[\\/].-)%s*[;:][;:%s]*" -- win path
end
local _, stop, dir = syspath:find(pat)
if stop then
syspath = syspath:sub(stop + 1)
else
dir = _str_strip(syspath):gsub("[;:%s]+$", "")
syspath = nil
end
if dir and #dir > 0 then
table.insert(dirs, dir)
end
end
return dirs
end
local function _in_path(exe, syspath)
local sep = is_windows and "\\" or "/"
if type(syspath) ~= "table" then
syspath = _path(syspath)
end
for _, dir in ipairs(syspath) do
local filename = dir .. sep .. exe
if _is_file(filename) then
return filename
elseif is_windows and _is_file(filename .. ".exe") then
return filename .. ".exe"
end
end
return nil
end
---@diagnostic disable-next-line: redefined-local
function M.makedirs(dirname)
local is_ok, _ = pcall(vimfn.mkdir, dirname, "p")
if is_ok then
return true
end
if dirname:match("^[a-zA-Z0-9_-\\/ %.']+$") then
dirname = dirname:gsub("[\\/]", "/") -- prevent char escapes
if is_windows then
os.execute('cmd.exe /E:ON /F:OFF /V:OFF /Q "' .. dirname .. '"')
else
os.execute('mkdir -p "' .. dirname .. '"')
end
return true
end
return false
end
---@param filename string path to file
---@return any? data file contents
---@nodiscard
function M.read_file(filename)
local file = io.open(filename, "r")
if not file then
return nil
end
local data = file:read("*a")
file:close()
return data
end
---@param filename string path to file
---@param data? any data to write
---@return boolean status true if write ok
function M.write_file(filename, data)
if data == nil then
data = ""
end
local parent_dir = dirname(filename)
if parent_dir then
M.makedirs(parent_dir)
end
local file = io.open(filename, "w")
if not file then
return false
end
file:write(data)
file:close()
file = nil
return true
end
---@param filename string path to json file
---@return any? data parsed file contents
---@nodiscard
function M.read_json(filename)
if vimfn.filereadable(filename) <= 0 then
return nil
end
local data = M.read_file(filename)
if not data then
return nil
end
local status_ok, json_obj = pcall(json.decode, data)
if not status_ok or not json_obj then
status_ok, json_obj = pcall(vimfn.json_decode, data)
end
if not status_ok or not json_obj then
return nil
end
return fix_numeric_keys(json_obj)
end
---@param filename string path to json file
---@param data? any data to encode as json and write
function M.write_json(filename, data)
assert(type(filename) == "string", "filepath must be of type string")
local status_ok, json_str = pcall(json.encode, data)
if not status_ok or not json_str then
status_ok, json_str = pcall(vimfn.json_encode, data)
end
if not status_ok or not json_str then
return
end
M.write_file(filename, json_str)
end
---@param filename string path to file
---@return number? epoch_secs secs since unix epoch. may be a float
function M.created(filename)
if not _is_filename_sane(filename) then
return nil
end
local epoch_secs = nil
-- allow windows in case gnu port is installed
if (not epoch_secs or epoch_secs <= 0) and _in_path("stat") then
local output = _exec('stat --format %W "' .. _str_escape(filename) .. '"')
epoch_secs = tonumber(output)
end
if
(not epoch_secs or epoch_secs <= 0)
and is_windows
and _in_path("powershell")
then
local output = _exec(
"powershell -NoProfile -NoLogo -Command "
.. '"(Get-Item \\"'
.. filename:gsub('"', '\\"')
.. '\\").CreationTime | Get-Date -UFormat %s"'
)
epoch_secs = tonumber(output)
end
if
(not epoch_secs or epoch_secs <= 0)
and not is_windows
and _in_path("find")
then
local output = _exec('find "' .. _str_escape(filename) .. '" -printf "%Bs"')
epoch_secs = tonumber(output)
end
return epoch_secs and epoch_secs > 0 and epoch_secs or nil
end
---@param filename string path to file
---@return number? epoch_secs secs since unix epoch. may be a float
function M.modified(filename)
if not _is_filename_sane(filename) then
return nil
end
local epoch_secs = nil
-- allow windows in case gnu port is installed
if (not epoch_secs or epoch_secs <= 0) and _in_path("stat") then
local output = _exec('stat --format %Y "' .. _str_escape(filename) .. '"')
epoch_secs = tonumber(output)
end
if
(not epoch_secs or epoch_secs <= 0)
and is_windows
and _in_path("powershell")
then
local output = _exec(
"powershell -NoProfile -NoLogo -Command "
.. '"(Get-Item \\"'
.. filename:gsub('"', '\\"')
.. '\\").LastWriteTime | Get-Date -UFormat %s"'
)
epoch_secs = tonumber(output)
end
if
(not epoch_secs or epoch_secs <= 0)
and not is_windows
and _in_path("date")
then
local output = _exec('date --utc +%s -r "' .. _str_escape(filename) .. '"')
epoch_secs = tonumber(output)
end
if
(not epoch_secs or epoch_secs <= 0)
and not is_windows
and _in_path("find")
then
local output = _exec('find "' .. _str_escape(filename) .. '" -printf "%Ts"')
epoch_secs = tonumber(output)
end
if not epoch_secs or epoch_secs <= 0 then
return nil
end
return epoch_secs
end
---@param filename string path to file
---@return number? inode inode num if detected
function M.inode(filename)
if not _is_filename_sane(filename) then
return nil
end
local inode = nil
if (not inode or inode <= 0) and _in_path("stat") then
-- allow windows in case gow or equivalent is installed
local output = _exec('stat --format %i "' .. _str_escape(filename) .. '"')
inode = tonumber(output)
end
if (not inode or inode <= 0) and not is_windows and _in_path("find") then
local output = _exec('find "' .. _str_escape(filename) .. '" -printf "%i"')
inode = tonumber(output)
end
if not inode or inode <= 0 then
return nil
end
return inode
end
---@param filename string path to file
---@return number? file_id FileID if detected
function M.file_id(filename)
if not _is_filename_sane(filename) then
return nil
end
local file_id = nil
if (not file_id or file_id < 0) and is_windows and _in_path("fsutil") then
local output =
_exec('fsutil file queryFileID "' .. _str_escape(filename) .. '"')
output = output and output:match("%s+(0x[a-fA-F0-9]+)%s*$") or nil
file_id = tonumber(output)
end
if not file_id or file_id < 0 then
return nil
end
return file_id
end
return M