-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpmc.lua
More file actions
1524 lines (1360 loc) · 45.9 KB
/
pmc.lua
File metadata and controls
1524 lines (1360 loc) · 45.9 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
--@description: pmc - pack-my-code, a minimalist code context packaging tool
--@author: WaterRun
--@file: pmc.lua
--@date: 2026-03-08
--@updated: 2026-03-23
-- =============================================================================
-- Type annotations
-- =============================================================================
---@class PmcOptions
---@field target_dir string
---@field exclude_patterns string[]
---@field include_patterns string[]
---@field ignore_gitignore boolean
---@field with_tree boolean
---@field with_stats boolean
---@field wrap_mode "md"|"nil"|"block"
---@field path_mode "relative"|"name"|"absolute"
---@field yaml_mode boolean
---@field output_file string|nil
---@field clipboard boolean
---@field show_version boolean
---@field show_help boolean
---@field user_set_t boolean
---@field user_set_s boolean
---@field user_set_w boolean
---@field user_set_p boolean
---@class FileItem
---@field abs_path string
---@field rel_target string
---@field display_path string
---@field content string
---@field line_count integer
---@field ext_key string
---@field lang string
---@class TreeNode
---@field name string
---@field kind "dir"|"file"
---@field order integer
---@field rel_path string|nil
---@field children table<string,TreeNode>|nil
---@field files table<string,TreeNode>|nil
-- =============================================================================
-- Constants
-- =============================================================================
local VERSION = "2"
local MAX_FILE_SIZE = 1024 * 1024 -- 1 MB
local DIR_SEP = package.config:sub(1, 1)
local IS_WINDOWS = (DIR_SEP == "\\")
local WRITE_CHUNK_SIZE = 4096
-- =============================================================================
-- Lookup tables
-- =============================================================================
--@description: known no-extension filenames for stats grouping
local KNOWN_NO_EXT = {
["makefile"] = true,
["gnumakefile"] = true,
["dockerfile"] = true,
["containerfile"] = true,
["vagrantfile"] = true,
["jenkinsfile"] = true,
["readme"] = true,
["license"] = true,
["copying"] = true,
["changelog"] = true,
["authors"] = true,
["contributors"] = true,
["gemfile"] = true,
["rakefile"] = true,
["guardfile"] = true,
["procfile"] = true,
["brewfile"] = true,
["cmakelists.txt"] = true,
}
--@description: binary file extensions - skip without reading content
local BINARY_EXTENSIONS = {}
do
local exts = {
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp",
".tiff", ".tga", ".psd", ".ai", ".eps", ".svg",
".mp3", ".mp4", ".wav", ".avi", ".mov", ".mkv", ".flv",
".ogg", ".flac", ".aac", ".wma", ".wmv", ".m4a", ".m4v",
".zip", ".tar", ".gz", ".bz2", ".xz", ".7z", ".rar", ".zst",
".exe", ".dll", ".so", ".dylib", ".o", ".obj", ".a", ".lib",
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
".wasm", ".class", ".pyc", ".pyo", ".elc",
".ttf", ".otf", ".woff", ".woff2", ".eot",
".sqlite", ".db", ".mdb", ".ldb",
".jar", ".war", ".ear", ".apk", ".ipa", ".deb", ".rpm",
".iso", ".dmg", ".img", ".bin", ".dat",
".min.js", ".min.css",
}
for _, ext in ipairs(exts) do
BINARY_EXTENSIONS[ext] = true
end
end
--@description: language detection by file extension
local LANG_BY_EXT = {
[".lua"] = "lua",
[".py"] = "python",
[".pyw"] = "python",
[".pyi"] = "python",
[".js"] = "javascript",
[".mjs"] = "javascript",
[".cjs"] = "javascript",
[".ts"] = "typescript",
[".mts"] = "typescript",
[".cts"] = "typescript",
[".jsx"] = "jsx",
[".tsx"] = "tsx",
[".sh"] = "bash",
[".bash"] = "bash",
[".zsh"] = "zsh",
[".fish"] = "fish",
[".rb"] = "ruby",
[".erb"] = "erb",
[".go"] = "go",
[".rs"] = "rust",
[".c"] = "c",
[".h"] = "c",
[".cpp"] = "cpp",
[".cc"] = "cpp",
[".cxx"] = "cpp",
[".hpp"] = "cpp",
[".hxx"] = "cpp",
[".hh"] = "cpp",
[".java"] = "java",
[".cs"] = "csharp",
[".fs"] = "fsharp",
[".fsx"] = "fsharp",
[".php"] = "php",
[".html"] = "html",
[".htm"] = "html",
[".xhtml"] = "html",
[".css"] = "css",
[".scss"] = "scss",
[".less"] = "less",
[".sass"] = "sass",
[".json"] = "json",
[".jsonc"] = "jsonc",
[".json5"] = "json5",
[".xml"] = "xml",
[".xsl"] = "xml",
[".xsd"] = "xml",
[".yaml"] = "yaml",
[".yml"] = "yaml",
[".toml"] = "toml",
[".ini"] = "ini",
[".cfg"] = "ini",
[".conf"] = "ini",
[".sql"] = "sql",
[".md"] = "markdown",
[".markdown"] = "markdown",
[".rst"] = "rst",
[".tex"] = "latex",
[".sty"] = "latex",
[".cls"] = "latex",
[".vue"] = "vue",
[".svelte"] = "svelte",
[".swift"] = "swift",
[".kt"] = "kotlin",
[".kts"] = "kotlin",
[".scala"] = "scala",
[".sc"] = "scala",
[".clj"] = "clojure",
[".cljs"] = "clojure",
[".cljc"] = "clojure",
[".r"] = "r",
[".dart"] = "dart",
[".ex"] = "elixir",
[".exs"] = "elixir",
[".erl"] = "erlang",
[".hrl"] = "erlang",
[".hs"] = "haskell",
[".lhs"] = "haskell",
[".pl"] = "perl",
[".pm"] = "perl",
[".ps1"] = "powershell",
[".psm1"] = "powershell",
[".psd1"] = "powershell",
[".bat"] = "batch",
[".cmd"] = "batch",
[".cmake"] = "cmake",
[".tf"] = "terraform",
[".hcl"] = "hcl",
[".proto"] = "protobuf",
[".graphql"] = "graphql",
[".gql"] = "graphql",
[".txt"] = "text",
[".log"] = "text",
[".env"] = "dotenv",
[".zig"] = "zig",
[".nim"] = "nim",
[".v"] = "v",
[".groovy"] = "groovy",
[".gradle"] = "groovy",
[".m"] = "objectivec",
[".mm"] = "objectivec",
[".d"] = "d",
[".jl"] = "julia",
[".ml"] = "ocaml",
[".mli"] = "ocaml",
[".lisp"] = "lisp",
[".cl"] = "lisp",
[".el"] = "elisp",
[".scm"] = "scheme",
[".rkt"] = "racket",
[".asm"] = "asm",
[".s"] = "asm",
[".glsl"] = "glsl",
[".hlsl"] = "hlsl",
[".wgsl"] = "wgsl",
[".dockerfile"] = "dockerfile",
}
--@description: language detection by special filename
local LANG_BY_NAME = {
["makefile"] = "makefile",
["gnumakefile"] = "makefile",
["dockerfile"] = "dockerfile",
["containerfile"] = "dockerfile",
["vagrantfile"] = "ruby",
["gemfile"] = "ruby",
["rakefile"] = "ruby",
["guardfile"] = "ruby",
["jenkinsfile"] = "groovy",
["cmakelists.txt"] = "cmake",
[".gitignore"] = "gitignore",
[".gitattributes"] = "gitignore",
[".gitmodules"] = "gitignore",
[".dockerignore"] = "gitignore",
[".hgignore"] = "gitignore",
[".editorconfig"] = "ini",
[".env"] = "dotenv",
[".env.local"] = "dotenv",
[".env.development"] = "dotenv",
[".env.production"] = "dotenv",
[".babelrc"] = "json",
[".eslintrc"] = "json",
[".prettierrc"] = "json",
["package.json"] = "json",
["tsconfig.json"] = "json",
["cargo.toml"] = "toml",
["pyproject.toml"] = "toml",
["go.mod"] = "gomod",
["go.sum"] = "gosum",
}
--@description: default exclude patterns applied in -r (raw scan) mode
local DEFAULT_RAW_EXCLUDES = {
".git/", ".svn/", ".hg/",
"node_modules/", "__pycache__/", ".tox/", ".mypy_cache/",
".vscode/", ".idea/", ".vs/",
"*.lock",
}
--@description: lua pattern magic characters
local LUA_MAGIC_CHARS = {
["^"] = true,
["$"] = true,
["("] = true,
[")"] = true,
["%"] = true,
["."] = true,
["["] = true,
["]"] = true,
["+"] = true,
["-"] = true,
["*"] = true,
["?"] = true,
}
-- =============================================================================
-- Utility functions
-- =============================================================================
--@description: fail with standardized error format and exit
local function fail(message)
io.stderr:write(string.format("err:( %s )\n", message))
io.stderr:flush()
os.exit(1)
end
--@description: print warning to stderr
local function warn(message)
io.stderr:write(string.format("warn: %s\n", message))
io.stderr:flush()
end
--@description: trim leading and trailing whitespace
local function trim(s)
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
--@description: normalize path separators to forward slash, collapse duplicates
local function normalizePath(p)
local s = p:gsub("\\", "/")
s = s:gsub("/+", "/")
if #s > 1 then
s = s:gsub("/$", "")
end
return s
end
--@description: normalize pattern separators; keep trailing slash semantics
local function normalizePattern(p)
local s = p:gsub("\\", "/")
s = s:gsub("/+", "/")
return s
end
--@description: check whether string starts with prefix
local function startsWith(s, prefix)
return s:sub(1, #prefix) == prefix
end
--@description: check whether string ends with suffix
local function endsWith(s, suffix)
if suffix == "" then return true end
return s:sub(- #suffix) == suffix
end
--@description: split string by literal delimiter
local function splitByChar(s, delim)
local out = {}
local start_i = 1
while true do
local i, j = s:find(delim, start_i, true)
if not i then
table.insert(out, s:sub(start_i))
break
end
table.insert(out, s:sub(start_i, i - 1))
start_i = j + 1
end
return out
end
--@description: extract basename from normalized path
local function baseName(p)
local s = normalizePath(p)
local i = s:match("^.*()/")
if i then return s:sub(i + 1) end
return s
end
--@description: extract file extension including the dot, or nil
local function fileExtension(name)
return name:match("^.+(%.[^%.]+)$")
end
--@description: check if filename has a real extension (not just a leading dot)
local function hasExtension(name)
local i = name:match("^.*()%.")
if not i then return false end
if i == 1 then return false end
return i < #name
end
-- =============================================================================
-- Safe output writing (chunked to prevent Windows console truncation)
-- =============================================================================
--@description: write string in safe-sized chunks
local function safeWrite(handle, s)
if s == "" then return end
if #s <= WRITE_CHUNK_SIZE then
handle:write(s)
return
end
local pos = 1
while pos <= #s do
local end_pos = pos + WRITE_CHUNK_SIZE - 1
if end_pos > #s then end_pos = #s end
handle:write(s:sub(pos, end_pos))
pos = end_pos + 1
end
end
-- =============================================================================
-- Shell and command utilities
-- =============================================================================
--@description: shell-quote a string for the current platform
local function shellQuote(s)
if IS_WINDOWS then
return "\"" .. s:gsub("\"", "\"\"") .. "\""
end
return "'" .. s:gsub("'", "'\"'\"'") .. "'"
end
--@description: run shell command, capture stdout
local function runCommand(cmd)
local pipe, err = io.popen(cmd, "r")
if not pipe then
return false, "", err or "popen failed"
end
local data = pipe:read("*a") or ""
local ok, why, code = pipe:close()
if ok == nil then
return false, data, code or why or "command failed"
end
return true, data, 0
end
-- =============================================================================
-- Clipboard utilities
-- =============================================================================
--@description: detect clipboard command for the current platform
local function getClipboardCommand()
if IS_WINDOWS then
return "clip"
end
-- Linux: try common clipboard tools in order
local tools = {
{ cmd = "xclip -selection clipboard", bin = "xclip" },
{ cmd = "xsel --clipboard --input", bin = "xsel" },
{ cmd = "wl-copy", bin = "wl-copy" },
}
for _, t in ipairs(tools) do
local ok = runCommand("which " .. t.bin .. " >/dev/null 2>&1")
if ok then
return t.cmd
end
end
return nil
end
--@description: write text to system clipboard
local function writeToClipboard(text)
local cmd = getClipboardCommand()
if not cmd then
fail("no clipboard tool found (need clip on Windows, or xclip / xsel / wl-copy on Linux)")
end
local pipe = io.popen(cmd, "w")
if not pipe then
fail("cannot open clipboard command: " .. cmd)
end
pipe:write(text)
local close_ok = pipe:close()
if not close_ok then
fail("clipboard write failed")
end
end
-- =============================================================================
-- Path utilities
-- =============================================================================
--@description: resolve absolute path via shell
local function getAbsolutePath(p)
if IS_WINDOWS then
local cmd = "cd /d " .. shellQuote(p) .. " 2>nul && cd"
local ok, out = runCommand(cmd)
if not ok then fail("cannot resolve absolute path: " .. p) end
local line = trim(out:gsub("\r", ""))
if line == "" then fail("cannot resolve absolute path: " .. p) end
return normalizePath(line)
end
local cmd = "cd " .. shellQuote(p) .. " 2>/dev/null && pwd"
local ok, out = runCommand(cmd)
if not ok then fail("cannot resolve absolute path: " .. p) end
local line = trim(out)
if line == "" then fail("cannot resolve absolute path: " .. p) end
return normalizePath(line)
end
--@description: get current working directory
local function getCwd()
if IS_WINDOWS then
local ok, out = runCommand("cd")
if not ok then fail("cannot get current directory") end
return normalizePath(trim(out:gsub("\r", "")))
end
local ok, out = runCommand("pwd")
if not ok then fail("cannot get current directory") end
return normalizePath(trim(out))
end
--@description: split path into segments
local function splitPathSegments(p)
local segs = {}
for seg in normalizePath(p):gmatch("[^/]+") do
table.insert(segs, seg)
end
return segs
end
--@description: compute relative path from base to target
local function relativePath(base_abs, target_abs)
local base = splitPathSegments(base_abs)
local targ = splitPathSegments(target_abs)
local i = 1
while i <= #base and i <= #targ and base[i] == targ[i] do
i = i + 1
end
local out = {}
for _ = i, #base do table.insert(out, "..") end
for j = i, #targ do table.insert(out, targ[j]) end
if #out == 0 then return "." end
return table.concat(out, "/")
end
--@description: make path relative to target directory
local function toTargetRelative(target_abs, file_abs)
local t = normalizePath(target_abs)
local f = normalizePath(file_abs)
if f == t then return "." end
if startsWith(f, t .. "/") then return f:sub(#t + 2) end
return relativePath(t, f)
end
--@description: format display path according to path mode
local function formatDisplayPath(path_mode, cwd_abs, file_abs)
if path_mode == "absolute" then return normalizePath(file_abs) end
if path_mode == "name" then return baseName(file_abs) end
return relativePath(cwd_abs, normalizePath(file_abs))
end
-- =============================================================================
-- Language detection
-- =============================================================================
--@description: detect programming language from file path
local function detectLang(rel_path)
local name = baseName(rel_path)
local lower_name = name:lower()
-- special filenames first
local special = LANG_BY_NAME[lower_name]
if special then return special end
-- check for .min.js / .min.css compound extensions
if endsWith(lower_name, ".min.js") then return "javascript" end
if endsWith(lower_name, ".min.css") then return "css" end
-- standard extension lookup
local ext = fileExtension(name)
if ext then
local lang = LANG_BY_EXT[ext:lower()]
if lang then return lang end
-- case-sensitive fallback (e.g. .R)
lang = LANG_BY_EXT[ext]
if lang then return lang end
end
return ""
end
-- =============================================================================
-- File inspection
-- =============================================================================
--@description: check if file has a known binary extension
local function isBinaryExtension(rel_path)
local name = baseName(rel_path):lower()
-- check compound extensions first
if endsWith(name, ".min.js") or endsWith(name, ".min.css") then
return true
end
local ext = fileExtension(name)
if not ext then return false end
return BINARY_EXTENSIONS[ext] == true
end
--@description: get file size in bytes, or nil on error
local function getFileSize(abs_path)
local f = io.open(abs_path, "rb")
if not f then return nil end
local size = f:seek("end")
f:close()
return size
end
--@description: read entire file as binary-safe string
local function readFile(abs_path)
local f, err = io.open(abs_path, "rb")
if not f then return nil, err end
local data = f:read("*a")
f:close()
return data or "", nil
end
--@description: heuristic text detection by null-byte sniffing in the first 8KB
local function isTextContent(data)
local check_len = math.min(#data, 8192)
local chunk = data:sub(1, check_len)
return not chunk:find("\0", 1, true)
end
--@description: normalize all line endings to LF
local function normalizeLineEndings(data)
return data:gsub("\r\n", "\n"):gsub("\r", "\n")
end
--@description: count lines in LF-normalized content
local function countLines(content)
if content == "" then return 0 end
local n = 0
for _ in content:gmatch("[^\n]*\n") do
n = n + 1
end
if content:sub(-1) ~= "\n" then
n = n + 1
end
return n
end
--@description: extension key for statistics grouping
local function detectExtKey(rel_path)
local bn = baseName(rel_path)
local lower_bn = bn:lower()
if not hasExtension(bn) then
if KNOWN_NO_EXT[lower_bn] then return "[no_ext:known]" end
return "[no_ext:unknown]"
end
local ext = bn:match("^.+(%.[^%.]+)$")
if not ext then return "[no_ext:unknown]" end
return ext:lower()
end
-- =============================================================================
-- Pattern matching
-- =============================================================================
--@description: escape one lua pattern magic character
local function escapeLuaMagic(ch)
if LUA_MAGIC_CHARS[ch] then return "%" .. ch end
return ch
end
--@description: convert a glob pattern to a lua pattern string
-- Supports: * (any non-slash chars), ** (any chars including slash), ? (single non-slash char)
local function globToLuaPattern(s)
local out = { "^" }
local i = 1
while i <= #s do
local ch = s:sub(i, i)
if ch == "*" then
if s:sub(i + 1, i + 1) == "*" then
-- ** matches everything including /
table.insert(out, ".*")
i = i + 2
-- consume one optional / after **
if i <= #s and s:sub(i, i) == "/" then
-- ** already covers /, so we make the slash optional
table.insert(out, "/?")
i = i + 1
end
else
-- single * matches everything except /
table.insert(out, "[^/]*")
i = i + 1
end
elseif ch == "?" then
table.insert(out, "[^/]")
i = i + 1
else
table.insert(out, escapeLuaMagic(ch))
i = i + 1
end
end
table.insert(out, "$")
return table.concat(out)
end
--@description: check if pattern contains wildcard characters
local function hasWildcard(p)
return p:find("*", 1, true) ~= nil or p:find("?", 1, true) ~= nil
end
--@description: check if a directory segment appears in any parent directory of the path
local function hasPathSegment(rel_path, seg)
local parts = splitByChar(rel_path, "/")
for i = 1, (#parts - 1) do
if parts[i] == seg then return true end
end
return false
end
--@description: match a single include/exclude pattern against a target-relative path
local function matchOnePattern(rel_path, pattern)
local rp = normalizePath(rel_path)
local pt = normalizePattern(pattern)
local is_dir_pattern = endsWith(pt, "/")
local bname = baseName(rp)
-- directory patterns (trailing /)
if is_dir_pattern then
local d = pt:sub(1, -2)
if d == "" then return false end
if d:find("/", 1, true) then
return startsWith(rp, d .. "/")
end
if startsWith(rp, d .. "/") then return true end
return hasPathSegment(rp, d)
end
-- patterns containing / -> match against full relative path
if pt:find("/", 1, true) then
if hasWildcard(pt) then
return rp:match(globToLuaPattern(pt)) ~= nil
end
return rp == pt
end
-- no-slash patterns with wildcards -> match basename, fallback full path
if hasWildcard(pt) then
local lp = globToLuaPattern(pt)
if bname:match(lp) then return true end
return rp:match(lp) ~= nil
end
-- extension shorthand like ".lua"
if startsWith(pt, ".") then
return endsWith(bname:lower(), pt:lower())
end
-- literal name match
return bname == pt or rp == pt
end
--@description: check if any pattern in list matches the path
local function matchPatterns(rel_path, patterns)
for _, p in ipairs(patterns) do
if matchOnePattern(rel_path, p) then return true end
end
return false
end
-- =============================================================================
-- Pattern parsing
-- =============================================================================
--@description: parse comma-separated pattern string into a list
local function parsePatternList(raw)
local patterns = {}
if not raw or raw == "" then return patterns end
local parts = splitByChar(raw, ",")
for _, part in ipairs(parts) do
local p = trim(part)
if p ~= "" then
p = normalizePattern(p)
table.insert(patterns, p)
end
end
return patterns
end
-- =============================================================================
-- Git integration
-- =============================================================================
--@description: check if git is available
local function hasGit()
local ok = runCommand("git --version")
return ok
end
--@description: split null-byte separated string (replaces %z pattern for Lua 5.2+ compat)
local function splitNullSeparated(s)
local items = {}
local start = 1
for i = 1, #s do
if s:byte(i) == 0 then
local item = s:sub(start, i - 1)
if item ~= "" then
table.insert(items, item)
end
start = i + 1
end
end
if start <= #s then
local item = s:sub(start)
if item ~= "" then
table.insert(items, item)
end
end
return items
end
--@description: list tracked + untracked files via git, respecting .gitignore
local function listFilesWithGit(target_abs)
if not hasGit() then
fail("git is required for default mode; use -r to scan directly")
end
local ok_repo, repo_out = runCommand(
"git -C " .. shellQuote(target_abs) .. " rev-parse --show-toplevel"
)
if not ok_repo then
fail("target is not inside a git work tree; use -r to scan directly")
end
local root_abs = normalizePath(trim(repo_out:gsub("\r", "")))
if root_abs == "" then
fail("failed to get git repository root")
end
local target_norm = normalizePath(target_abs)
local rel_target = ""
if target_norm ~= root_abs then
if not startsWith(target_norm, root_abs .. "/") then
fail("target path is outside repository root")
end
rel_target = target_norm:sub(#root_abs + 2)
end
-- On Windows: use newline-separated output to avoid io.popen text-mode 0x1A
-- (NTFS does not allow \n in filenames, so newline split is safe)
-- On Unix: use null-separated output (filenames can contain \n)
local raw_items
if IS_WINDOWS then
local ok_list, list_out = runCommand(
"git -C " .. shellQuote(root_abs) ..
" ls-files --cached --others --exclude-standard --full-name"
)
if not ok_list then
fail("failed to list files through git")
end
raw_items = {}
list_out = list_out:gsub("\r", "")
for line in list_out:gmatch("([^\n]+)") do
table.insert(raw_items, line)
end
else
local ok_list, list_out = runCommand(
"git -C " .. shellQuote(root_abs) ..
" ls-files -z --cached --others --exclude-standard --full-name"
)
if not ok_list then
fail("failed to list files through git")
end
raw_items = splitNullSeparated(list_out)
end
local files = {}
for _, item in ipairs(raw_items) do
local rel_repo = normalizePath(item)
if rel_repo ~= "" then
local dominated = false
if rel_target == "" then
dominated = true
elseif rel_repo == rel_target or startsWith(rel_repo, rel_target .. "/") then
dominated = true
end
if dominated then
table.insert(files, normalizePath(root_abs .. "/" .. rel_repo))
end
end
end
return files
end
-- =============================================================================
-- Direct file scanning (-r mode)
-- =============================================================================
--@description: list files by recursive directory scan
local function listFilesDirect(target_abs)
local cmd
if IS_WINDOWS then
cmd = "dir /a-d /s /b " .. shellQuote(target_abs) .. " 2>nul"
else
cmd = "find " .. shellQuote(target_abs) .. " -type f -print 2>/dev/null"
end
local ok, out = runCommand(cmd)
if not ok then
return {}
end
local files = {}
out = out:gsub("\r", "")
for line in out:gmatch("([^\n]+)") do
local p = trim(line)
if p ~= "" then
table.insert(files, normalizePath(p))
end
end
return files
end
-- =============================================================================
-- File item building (filtering, reading, normalizing)
-- =============================================================================
--@description: process a single file path into a FileItem, or nil if skipped
local function processOneFile(abs_path, target_abs, effective_excludes, include_patterns,
path_mode, cwd_abs)
local rel_target = toTargetRelative(target_abs, abs_path)
if rel_target == "." then return nil end
-- skip known binary extensions without reading
if isBinaryExtension(rel_target) then return nil end
-- include filter
if #include_patterns > 0 then
if not matchPatterns(rel_target, include_patterns) then return nil end
end
-- exclude filter
if #effective_excludes > 0 then
if matchPatterns(rel_target, effective_excludes) then return nil end
end
-- file size guard
local size = getFileSize(abs_path)
if not size then
warn("cannot access file: " .. abs_path)
return nil
end
if size > MAX_FILE_SIZE then
warn("skipped (exceeds 1 MB): " .. rel_target)
return nil
end
if size == 0 then
-- include empty files as-is
return {
abs_path = normalizePath(abs_path),
rel_target = normalizePath(rel_target),
display_path = formatDisplayPath(path_mode, cwd_abs, abs_path),
content = "",
line_count = 0,
ext_key = detectExtKey(rel_target),
lang = detectLang(rel_target),
}
end
-- read content
local data, read_err = readFile(abs_path)
if not data then
warn("cannot read file: " .. abs_path .. " (" .. tostring(read_err) .. ")")
return nil
end
-- text/binary check
if not isTextContent(data) then return nil end
-- normalize line endings to LF
data = normalizeLineEndings(data)
return {
abs_path = normalizePath(abs_path),
rel_target = normalizePath(rel_target),
display_path = formatDisplayPath(path_mode, cwd_abs, abs_path),
content = data,
line_count = countLines(data),
ext_key = detectExtKey(rel_target),
lang = detectLang(rel_target),
}
end
--@description: build filtered, sorted list of FileItems from raw file paths
local function buildFileItems(abs_files, target_abs, opt, cwd_abs)
-- merge default raw-scan excludes when in -r mode
local effective_excludes = {}
if opt.ignore_gitignore then
for _, p in ipairs(DEFAULT_RAW_EXCLUDES) do
table.insert(effective_excludes, p)
end
end
for _, p in ipairs(opt.exclude_patterns) do
table.insert(effective_excludes, p)
end
table.sort(abs_files, function(a, b)
return normalizePath(a) < normalizePath(b)
end)
local items = {}
for _, abs_path in ipairs(abs_files) do
local item = processOneFile(
abs_path, target_abs, effective_excludes, opt.include_patterns,
opt.path_mode, cwd_abs
)
if item then
table.insert(items, item)
end
end
table.sort(items, function(a, b)
return a.rel_target < b.rel_target
end)
return items
end