-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.lua
More file actions
1783 lines (1673 loc) · 54.3 KB
/
Copy pathrun.lua
File metadata and controls
1783 lines (1673 loc) · 54.3 KB
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
plugin = {}
local PLUGIN_ID = "stack"
local PLUGIN_NAME = "stack"
local PLUGIN_VERSION = "0.1.0"
local STACK_BINARY = "stack"
local CURL_BINARY = "curl"
local JSON_NULL = {}
local SEARCH_TTL = 120
local PACKAGE_TTL = 300
local DEFAULT_SEARCH_LIMIT = 10
local expand_runtime_placeholders
local function trim(value)
return (tostring(value or ""):gsub("^%s+", ""):gsub("%s+$", ""))
end
local function lower(value)
return string.lower(tostring(value or ""))
end
local function split_lines(value)
local text = tostring(value or ""):gsub("\r\n", "\n")
local lines = {}
if text == "" then
return lines
end
for line in (text .. "\n"):gmatch("(.-)\n") do
lines[#lines + 1] = line
end
return lines
end
local function first_nonempty(...)
for index = 1, select("#", ...) do
local value = select(index, ...)
if value ~= nil and value ~= JSON_NULL then
if type(value) == "string" then
local text = trim(value)
if text ~= "" then
return text
end
else
return value
end
end
end
return nil
end
local function shell_quote(value)
return "'" .. tostring(value or ""):gsub("'", "'\\''") .. "'"
end
local function command_quote(value)
local text = tostring(value or "")
if text:match("^[%w%+%-%._/%:@=,%[%]]+$") ~= nil then
return text
end
return shell_quote(text)
end
local function join_path(...)
local parts = {}
for index = 1, select("#", ...) do
local part = trim(select(index, ...))
if part ~= "" then
if #parts == 0 then
parts[#parts + 1] = part:gsub("[/\\]+$", "")
else
parts[#parts + 1] = part:gsub("^[/\\]+", ""):gsub("[/\\]+$", "")
end
end
end
if #parts == 0 then
return "."
end
return table.concat(parts, "/")
end
local function parent_dir(path)
return tostring(path or ""):match("^(.*)[/\\][^/\\]+$")
end
local function read_field(value, key)
if value == nil then
return nil
end
local ok, result = pcall(function()
return value[key]
end)
if ok then
return result
end
return nil
end
local function object_flags(object)
local value = read_field(object, "flags")
if type(value) ~= "table" and type(value) ~= "userdata" then
return {}
end
local flags = {}
local ok = pcall(function()
for _, item in ipairs(value) do
local cleaned = trim(item)
if cleaned ~= "" then
flags[#flags + 1] = cleaned
end
end
end)
if not ok then
return {}
end
return flags
end
local function append_unique(list, value, seen)
local text = trim(value)
if text == "" then
return
end
if seen[text] then
return
end
seen[text] = true
list[#list + 1] = text
end
local function collect_raw_flags(context, packages)
local flags = {}
local seen = {}
local function collect_from(object)
for _, flag in ipairs(object_flags(object)) do
append_unique(flags, flag, seen)
end
end
collect_from(context)
collect_from(read_field(context, "request"))
for _, package in ipairs(packages or {}) do
collect_from(package)
end
return flags
end
local function has_flag(flags, key)
local wanted = lower(trim(key))
for _, flag in ipairs(flags or {}) do
if lower(trim(flag)) == wanted then
return true
end
end
return false
end
local function flag_value(flags, key)
local prefix = lower(trim(key)) .. "="
for _, flag in ipairs(flags or {}) do
local cleaned = trim(flag)
if lower(cleaned):sub(1, #prefix) == prefix then
return trim(cleaned:sub(#prefix + 1))
end
end
return nil
end
local function emit_event(context, name, payload)
if context == nil or context.events == nil then
return
end
local fn = context.events[name]
if type(fn) == "function" then
fn(payload)
end
end
local function begin_step(context, label)
if context == nil or context.tx == nil then
return
end
local fn = context.tx.begin_step
if type(fn) == "function" then
fn(label)
end
end
local function tx_success(context)
if context == nil or context.tx == nil then
return
end
local fn = context.tx.success
if type(fn) == "function" then
fn()
end
end
local function tx_failed(context, message)
if context == nil or context.tx == nil then
return
end
local fn = context.tx.failed
if type(fn) == "function" then
fn(message)
end
end
local function log_warn(context, message)
if context == nil or context.log == nil then
return
end
local fn = context.log.warn
if type(fn) == "function" then
fn(message)
end
end
local function normalize_run_result(first, second, third, fourth, fifth)
if type(first) == "table" then
if first.stdout == nil then
first.stdout = first.stdoutText or ""
end
if first.stderr == nil then
first.stderr = first.stderrText or ""
end
if first.exitCode == nil then
first.exitCode = first.exit_code or first.code or first.status
end
if first.success == nil and first.ok ~= nil then
first.success = first.ok
end
if first.success == nil and first.exitCode ~= nil then
first.success = first.exitCode == 0
end
return first
end
local result = {}
local function merge_exec_like(value)
for _, key in ipairs({ "success", "ok", "stdout", "stderr", "exitCode", "exit_code", "code", "status", "stdoutText", "stderrText" }) do
local ok, item = pcall(function()
return value[key]
end)
if ok and item ~= nil and result[key] == nil then
result[key] = item
end
end
end
local function apply_scalar(value)
local value_type = type(value)
if value_type == "table" then
for key, item in pairs(value or {}) do
result[key] = item
end
elseif value_type == "userdata" then
merge_exec_like(value)
elseif value_type == "boolean" then
if result.success == nil then
result.success = value
end
elseif value_type == "number" then
if result.exitCode == nil then
result.exitCode = value
end
elseif value_type == "string" then
if result.stdout == nil then
result.stdout = value
elseif result.stderr == nil then
result.stderr = value
end
end
end
apply_scalar(first)
apply_scalar(second)
apply_scalar(third)
apply_scalar(fourth)
apply_scalar(fifth)
if result.stdout == nil then
result.stdout = result.stdoutText or ""
end
if result.stderr == nil then
result.stderr = result.stderrText or ""
end
if result.exitCode == nil then
result.exitCode = result.exit_code or result.code or result.status
end
if result.success == nil and result.ok ~= nil then
result.success = result.ok
end
if result.success == nil and result.exitCode ~= nil then
result.success = result.exitCode == 0
end
return result
end
local function exec_run(context, command)
local first, second, third, fourth, fifth
if context ~= nil and context.exec ~= nil and type(context.exec.run) == "function" then
first, second, third, fourth, fifth = context.exec.run(command)
else
first, second, third, fourth, fifth = reqpack.exec.run(command)
end
return normalize_run_result(first, second, third, fourth, fifth)
end
local function is_command_success(result)
if type(result) ~= "table" then
return false
end
if result.success == true or result.ok == true then
return true
end
return (result.exitCode or result.exit_code or result.code or result.status) == 0
end
local function command_exists(context, binary)
return is_command_success(exec_run(context, "command -v " .. shell_quote(binary) .. " >/dev/null 2>&1"))
end
local function command_ok(ok, _, code)
if ok == true then
return true
end
if type(ok) == "number" then
return ok == 0
end
return code == 0
end
local function ensure_directory(path)
local dir = trim(path)
if dir == "" or dir == "." then
return true
end
if os == nil or type(os.execute) ~= "function" then
return false
end
local ok, kind, code = os.execute("mkdir -p " .. shell_quote(dir))
return command_ok(ok, kind, code)
end
local function read_file(path)
path = expand_runtime_placeholders(path)
local handle = io.open(path, "r")
if handle == nil then
if reqpack ~= nil and reqpack.exec ~= nil and type(reqpack.exec.run) == "function" then
local result = normalize_run_result(reqpack.exec.run("cat " .. shell_quote(path)))
if is_command_success(result) then
return result.stdout or ""
end
end
return nil
end
local content = handle:read("*a")
handle:close()
return content
end
local function write_file(path, content)
path = expand_runtime_placeholders(path)
local dir = parent_dir(path)
if dir ~= nil and dir ~= "" and not ensure_directory(dir) then
return false
end
local handle = io.open(path, "w")
if handle == nil then
return false
end
handle:write(content)
handle:close()
return true
end
local function remove_file(path)
if os ~= nil and type(os.remove) == "function" then
os.remove(expand_runtime_placeholders(path))
end
end
local function home_dir()
if os ~= nil and type(os.getenv) == "function" then
return first_nonempty(os.getenv("HOME"), os.getenv("USERPROFILE"), "/home/test", ".")
end
return "/home/test"
end
local function fixture_root()
if os ~= nil and type(os.getenv) == "function" then
return trim(os.getenv("REQPACK_TEST_FIXTURE_ROOT") or "")
end
return ""
end
function expand_runtime_placeholders(value)
local text = tostring(value or "")
local root = fixture_root()
if root ~= "" then
text = text:gsub("%$%{fixtureRoot%}", root)
end
return text
end
local function expand_fixture_path(path)
local text = trim(expand_runtime_placeholders(path))
if text == "" then
return text
end
if text:match("^[/~]") ~= nil or text:match("^[A-Za-z]:[/\\]") ~= nil then
return text
end
local root = fixture_root()
if root ~= "" and (text == "." or text:sub(1, 2) == "./" or text:sub(1, 3) == "../") then
if text == "." then
return root
end
if text:sub(1, 2) == "./" then
return join_path(root, text:sub(3))
end
return join_path(root, text)
end
return text
end
local function epoch_now()
if os ~= nil and type(os.time) == "function" then
return os.time()
end
return 0
end
local function codepoint_to_utf8(codepoint)
if codepoint <= 0x7F then
return string.char(codepoint)
end
if codepoint <= 0x7FF then
return string.char(0xC0 + math.floor(codepoint / 0x40), 0x80 + (codepoint % 0x40))
end
if codepoint <= 0xFFFF then
return string.char(
0xE0 + math.floor(codepoint / 0x1000),
0x80 + (math.floor(codepoint / 0x40) % 0x40),
0x80 + (codepoint % 0x40)
)
end
return string.char(
0xF0 + math.floor(codepoint / 0x40000),
0x80 + (math.floor(codepoint / 0x1000) % 0x40),
0x80 + (math.floor(codepoint / 0x40) % 0x40),
0x80 + (codepoint % 0x40)
)
end
local function decode_json_internal(raw)
local text = tostring(raw or "")
local length = #text
local index = 1
local function decode_error(message)
error(message .. " at byte " .. tostring(index), 0)
end
local function peek()
return text:sub(index, index)
end
local function skip_whitespace()
while index <= length do
local byte = text:byte(index)
if byte == 32 or byte == 9 or byte == 10 or byte == 13 then
index = index + 1
else
break
end
end
end
local parse_value
local function parse_string()
index = index + 1
local parts = {}
local segment_start = index
while index <= length do
local current = text:sub(index, index)
if current == '"' then
parts[#parts + 1] = text:sub(segment_start, index - 1)
index = index + 1
return table.concat(parts)
end
if current == "\\" then
parts[#parts + 1] = text:sub(segment_start, index - 1)
index = index + 1
if index > length then
decode_error("unterminated escape sequence")
end
local escape = text:sub(index, index)
if escape == '"' or escape == "\\" or escape == "/" then
parts[#parts + 1] = escape
index = index + 1
elseif escape == "b" then
parts[#parts + 1] = "\b"
index = index + 1
elseif escape == "f" then
parts[#parts + 1] = "\f"
index = index + 1
elseif escape == "n" then
parts[#parts + 1] = "\n"
index = index + 1
elseif escape == "r" then
parts[#parts + 1] = "\r"
index = index + 1
elseif escape == "t" then
parts[#parts + 1] = "\t"
index = index + 1
elseif escape == "u" then
local hex = text:sub(index + 1, index + 4)
if #hex ~= 4 or hex:match("^[0-9a-fA-F]+$") == nil then
decode_error("invalid unicode escape")
end
parts[#parts + 1] = codepoint_to_utf8(tonumber(hex, 16))
index = index + 5
else
decode_error("unsupported escape sequence")
end
segment_start = index
else
local byte = text:byte(index)
if byte ~= nil and byte < 32 then
decode_error("control character in string")
end
index = index + 1
end
end
decode_error("unterminated string")
end
local function parse_number()
local start = index
local current = peek()
if current == "-" then
index = index + 1
end
current = peek()
if current == "0" then
index = index + 1
elseif current:match("%d") then
repeat
index = index + 1
current = peek()
until current == "" or not current:match("%d")
else
decode_error("invalid number")
end
current = peek()
if current == "." then
index = index + 1
if not peek():match("%d") then
decode_error("invalid number fraction")
end
repeat
index = index + 1
current = peek()
until current == "" or not current:match("%d")
end
current = peek()
if current == "e" or current == "E" then
index = index + 1
current = peek()
if current == "+" or current == "-" then
index = index + 1
end
if not peek():match("%d") then
decode_error("invalid number exponent")
end
repeat
index = index + 1
current = peek()
until current == "" or not current:match("%d")
end
return tonumber(text:sub(start, index - 1))
end
local function parse_array()
index = index + 1
skip_whitespace()
local result = {}
if peek() == "]" then
index = index + 1
return result
end
while true do
result[#result + 1] = parse_value()
skip_whitespace()
local current = peek()
if current == "," then
index = index + 1
skip_whitespace()
elseif current == "]" then
index = index + 1
return result
else
decode_error("expected ',' or ']' ")
end
end
end
local function parse_object()
index = index + 1
skip_whitespace()
local result = {}
if peek() == "}" then
index = index + 1
return result
end
while true do
if peek() ~= '"' then
decode_error("expected string key")
end
local key = parse_string()
skip_whitespace()
if peek() ~= ":" then
decode_error("expected ':'")
end
index = index + 1
skip_whitespace()
local value = parse_value()
if value == nil then
result[key] = JSON_NULL
else
result[key] = value
end
skip_whitespace()
local current = peek()
if current == "," then
index = index + 1
skip_whitespace()
elseif current == "}" then
index = index + 1
return result
else
decode_error("expected ',' or '}'")
end
end
end
function parse_value()
skip_whitespace()
local current = peek()
if current == '"' then
return parse_string()
elseif current == "{" then
return parse_object()
elseif current == "[" then
return parse_array()
elseif current == "-" or current:match("%d") then
return parse_number()
elseif text:sub(index, index + 3) == "true" then
index = index + 4
return true
elseif text:sub(index, index + 4) == "false" then
index = index + 5
return false
elseif text:sub(index, index + 3) == "null" then
index = index + 4
return nil
end
decode_error("unexpected token")
end
local decoded = parse_value()
skip_whitespace()
if index <= length then
decode_error("trailing characters")
end
return decoded
end
local function decode_json(raw)
local ok, result = pcall(decode_json_internal, raw)
if ok then
return result, nil
end
return nil, tostring(result)
end
local function package_name(package)
return trim(read_field(package, "name") or read_field(package, "packageName") or read_field(package, "packageId") or "")
end
local function package_version(package)
return trim(read_field(package, "version") or "")
end
local function cache_root(context, packages)
local raw_flags = collect_raw_flags(context, packages)
local explicit = flag_value(raw_flags, "cache-root")
if explicit ~= nil and explicit ~= "" then
return expand_fixture_path(explicit)
end
return join_path(home_dir(), ".cache", "reqpack", PLUGIN_ID)
end
local function shared_paths(context, packages)
local root = cache_root(context, packages)
return {
root = root,
stack_root = join_path(root, "stack-root"),
bin = join_path(root, "bin"),
state_file = join_path(root, "state", "installed.tsv"),
search_dir = join_path(root, "query", "search"),
versions_dir = join_path(root, "query", "versions"),
cabal_dir = join_path(root, "query", "cabal"),
}
end
local function env_prefix(paths)
return table.concat({
"STACK_ROOT=" .. shell_quote(paths.stack_root),
"NO_COLOR='1'",
"LC_ALL='C'",
"LANG='C'",
"LANGUAGE='C'",
}, " ")
end
local function build_stack_command(context, packages, args, options)
local paths = shared_paths(context, packages)
local parts = { env_prefix(paths), STACK_BINARY, "--color", "never" }
for _, arg in ipairs(args or {}) do
parts[#parts + 1] = command_quote(arg)
end
local command = table.concat(parts, " ")
local dir = trim(options and options.dir or "")
if dir ~= "" then
command = "cd " .. shell_quote(dir) .. " && " .. command
end
return command, paths
end
local function cache_key(value)
local normalized = lower(trim(value))
if normalized == "" then
normalized = "unknown"
end
return (normalized:gsub("[^%w%.%-_]+", "_"))
end
local function read_timestamp(path)
local raw = trim(read_file(path) or "")
local value = tonumber(raw)
if value == nil then
return 0
end
return value
end
local function is_cache_fresh(ts_path, ttl)
local timestamp = read_timestamp(ts_path)
if timestamp <= 0 then
return false
end
return (epoch_now() - timestamp) < ttl
end
local function persist_cache(body_path, ts_path, body)
write_file(body_path, body)
write_file(ts_path, tostring(epoch_now()))
end
local function fetch_url(context, url, accept)
local args = { "-fsSL" }
if trim(accept or "") ~= "" then
args[#args + 1] = "-H"
args[#args + 1] = "Accept: " .. accept
end
local parts = { CURL_BINARY }
for _, arg in ipairs(args) do
parts[#parts + 1] = command_quote(arg)
end
parts[#parts + 1] = shell_quote(url)
local result = exec_run(context, table.concat(parts, " "))
if not is_command_success(result) then
return nil, first_nonempty(result and result.stderr, result and result.stdout, "request failed")
end
return result.stdout or "", nil
end
local function cached_fetch(context, body_path, ts_path, url, ttl, accept)
local cached = read_file(body_path)
if cached ~= nil and is_cache_fresh(ts_path, ttl) then
return cached, nil
end
local body, err = fetch_url(context, url, accept)
if body ~= nil then
persist_cache(body_path, ts_path, body)
return body, nil
end
if cached ~= nil then
return cached, nil
end
return nil, err
end
local function version_tokens(value)
local tokens = {}
local text = tostring(value or "")
for token in text:gmatch("[A-Za-z0-9]+") do
if token:match("^%d+$") then
tokens[#tokens + 1] = { numeric = true, value = tonumber(token) }
else
tokens[#tokens + 1] = { numeric = false, value = lower(token) }
end
end
return tokens
end
local function compare_versions(left, right)
local a = version_tokens(left)
local b = version_tokens(right)
local max_len = math.max(#a, #b)
for index = 1, max_len do
local x = a[index]
local y = b[index]
if x == nil and y == nil then
return 0
elseif x == nil then
if y.numeric and y.value == 0 then
else
return -1
end
elseif y == nil then
if x.numeric and x.value == 0 then
else
return 1
end
elseif x.numeric and y.numeric then
if x.value < y.value then
return -1
elseif x.value > y.value then
return 1
end
elseif x.numeric ~= y.numeric then
return x.numeric and 1 or -1
else
if x.value < y.value then
return -1
elseif x.value > y.value then
return 1
end
end
end
return 0
end
local function sanitize_state_field(value)
return trim(tostring(value or ""):gsub("[\r\n\t]", " "))
end
local function split_tabs(line)
local fields = {}
for field in (tostring(line or "") .. "\t"):gmatch("(.-)\t") do
fields[#fields + 1] = field
end
return fields
end
local function parse_csv_list(value)
local items = {}
local seen = {}
for item in tostring(value or ""):gmatch("([^,]+)") do
append_unique(items, trim(item), seen)
end
return items
end
local function join_csv_list(items)
local values = {}
local seen = {}
for _, item in ipairs(items or {}) do
append_unique(values, item, seen)
end
table.sort(values)
return table.concat(values, ",")
end
local function load_state(paths)
local items = {}
local raw = read_file(paths.state_file)
if raw == nil then
return items
end
for _, line in ipairs(split_lines(raw)) do
local text = trim(line)
if text ~= "" then
local fields = split_tabs(text)
items[#items + 1] = {
name = trim(fields[1]),
version = trim(fields[2]),
sourceKind = trim(fields[3]),
sourceRef = trim(fields[4]),
binaries = parse_csv_list(fields[5]),
summary = trim(fields[6]),
license = trim(fields[7]),
homepage = trim(fields[8]),
}
end
end
return items
end
local function save_state(paths, items)
local lines = {}
table.sort(items, function(left, right)
return trim(left.name) < trim(right.name)
end)
for _, item in ipairs(items or {}) do
lines[#lines + 1] = table.concat({
sanitize_state_field(item.name),
sanitize_state_field(item.version),
sanitize_state_field(item.sourceKind),
sanitize_state_field(item.sourceRef),
sanitize_state_field(join_csv_list(item.binaries)),
sanitize_state_field(item.summary),
sanitize_state_field(item.license),
sanitize_state_field(item.homepage),
}, "\t")
end
return write_file(paths.state_file, (#lines > 0 and table.concat(lines, "\n") .. "\n") or "")
end
local function find_state_index(items, name)
local wanted = lower(trim(name))
for index, item in ipairs(items or {}) do
if lower(trim(item.name)) == wanted then
return index
end
end
return nil
end
local function binary_owned_elsewhere(items, current_name, binary)
local wanted_name = lower(trim(current_name))
local wanted_binary = trim(binary)
for _, item in ipairs(items or {}) do
if lower(trim(item.name)) ~= wanted_name then
for _, owned in ipairs(item.binaries or {}) do
if trim(owned) == wanted_binary then
return true
end
end
end
end
return false
end
local function cleanup_unowned_binaries(paths, items, current_name, binaries)
for _, binary in ipairs(binaries or {}) do
if not binary_owned_elsewhere(items, current_name, binary) then
remove_file(join_path(paths.bin, binary))
end
end
end
local function ensure_command(context, binary)
if not command_exists(context, binary) then
return false, binary .. " binary not available"
end
return true, nil
end
local function package_versions_paths(paths, name)
local base = join_path(paths.versions_dir, cache_key(name) .. ".json")
return base, base .. ".ts"
end
local function package_cabal_paths(paths, name, version)
local base = join_path(paths.cabal_dir, cache_key(name .. "-" .. version) .. ".cabal")
return base, base .. ".ts"
end
local function search_paths(paths, prompt)
local base = join_path(paths.search_dir, cache_key(prompt) .. ".json")
return base, base .. ".ts"
end
local function latest_version_from_map(map, allow_deprecated)
local latest = nil
for version, status in pairs(map or {}) do
local current_status = trim(status)
if allow_deprecated or current_status ~= "deprecated" then
if latest == nil or compare_versions(version, latest) > 0 then
latest = version
end
end
end
if latest ~= nil then
return latest
end
for version in pairs(map or {}) do
if latest == nil or compare_versions(version, latest) > 0 then
latest = version
end