-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathutil.lua
More file actions
752 lines (644 loc) · 19.9 KB
/
util.lua
File metadata and controls
752 lines (644 loc) · 19.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
local Path = require('plenary.path')
local M = {}
function M.uid()
return tostring(os.time()) .. '-' .. tostring(math.random(1000, 9999))
end
function M.is_buf_a_file(bufnr)
bufnr = bufnr or vim.api.nvim_get_current_buf()
if not vim.api.nvim_buf_is_valid(bufnr) then
return false
end
local buftype = vim.bo[bufnr].buftype
local filepath = vim.api.nvim_buf_get_name(bufnr)
-- Valid files have empty buftype
-- This excludes special buffers like help, terminal, nofile, etc.
return buftype == '' and filepath ~= ''
end
function M.indent_code_block(text)
if not text then
return nil
end
local lines = vim.split(text, '\n', { plain = true })
local first, last = nil, nil
for i, line in ipairs(lines) do
if line:match('[^%s]') then
first = first or i
last = i
end
end
if not first then
return ''
end
local content = {}
for i = first, last do
table.insert(content, lines[i])
end
local min_indent = math.huge
for _, line in ipairs(content) do
if line:match('[^%s]') then
min_indent = math.min(min_indent, line:match('^%s*'):len())
end
end
if min_indent < math.huge and min_indent > 0 then
for i, line in ipairs(content) do
if line:match('[^%s]') then
content[i] = line:sub(min_indent + 1)
end
end
end
return vim.trim(table.concat(content, '\n'))
end
-- Reset all ANSI styling
function M.ansi_reset()
return '\27[0m'
end
---Remove ANSI escape sequences
---@param str string: Input string containing ANSI escape codes
---@return string stripped_str
function M.strip_ansi(str)
return (str:gsub('\27%[[%d;]*m', ''))
end
---Strip ANSI escape sequences from all lines
---@param lines table
---@return table stripped_lines
function M.sanitize_lines(lines)
local stripped_lines = {}
for _, line in pairs(lines) do
table.insert(stripped_lines, M.strip_ansi(line))
end
return stripped_lines
end
--- Normalize a URL by prepending http:// if no protocol is specified
--- @param url string The URL to normalize
--- @return string normalized_url The normalized URL
function M.normalize_url_protocol(url)
if not url:match('^https?://') then
return 'http://' .. url
end
return url
end
--- URL encode a string for use in query parameters
--- @param str string The string to encode
--- @return string encoded_string The URL-encoded string
function M.url_encode(str)
if not str then
return ''
end
str = tostring(str)
str = string.gsub(str, '\n', '\r\n')
str = string.gsub(str, '([^%w%-%.%_%~])', function(c)
return string.format('%%%02X', string.byte(c))
end)
return str
end
--- Apply path mapping transformation if configured
--- @param path string The path to transform
--- @return string transformed_path The transformed path (or original if no mapping)
function M.apply_path_map(path)
if not path then
return path
end
local config = require('opencode.config')
local path_map = config.server.path_map
if type(path_map) == 'function' then
local ok, result = pcall(path_map, path)
if ok and result then
return result
end
return path
elseif type(path_map) == 'string' then
local host_cwd = vim.fn.getcwd()
if vim.startswith(path, host_cwd) then
local relative_path = path:sub(#host_cwd + 1)
if relative_path == '' then
return path_map
end
return path_map .. relative_path
end
end
return path
end
function M.apply_reverse_path_map(path)
if not path then
return path
end
local config = require('opencode.config')
local reverse_path_map = config.server.reverse_path_map
if type(reverse_path_map) == 'function' then
local ok, result = pcall(reverse_path_map, path)
if ok and result then
return result
end
return path
end
return path
end
function M.reverse_transform_paths_recursive(data)
local config = require('opencode.config')
local reverse_path_map = config.server.reverse_path_map
if not reverse_path_map or type(reverse_path_map) ~= 'function' then
return data
end
if type(data) ~= 'table' then
return data
end
local result = {}
for key, value in pairs(data) do
if
type(value) == 'string'
and (key == 'filePath' or key == 'path' or key == 'file' or key == 'directory' or key == 'cwd' or key == 'root')
then
result[key] = M.apply_reverse_path_map(value)
elseif type(value) == 'table' and (key == 'files' or key == 'deleted_files') then
result[key] = vim.tbl_map(M.apply_reverse_path_map, value)
elseif type(value) == 'table' then
result[key] = M.reverse_transform_paths_recursive(value)
else
result[key] = value
end
end
return result
end
--- Transform file paths in API payloads using configured path_map
--- @param data any The data to transform (table, string, or other)
--- @return any transformed_data The data with paths transformed
function M.transform_paths_recursive(data)
local config = require('opencode.config')
local path_map = config.server.path_map
if not path_map or type(path_map) ~= 'function' then
return data
end
if type(data) ~= 'table' then
return data
end
local result = {}
for key, value in pairs(data) do
if type(value) == 'string' and (key == 'filePath' or key == 'path' or key == 'directory') then
result[key] = M.apply_path_map(value)
elseif type(value) == 'table' then
result[key] = M.transform_paths_recursive(value)
else
result[key] = value
end
end
return result
end
--- Format a timestamp as time (e.g., "10:23 AM", "13 Oct 03:32 PM" "13 Oct 2025 03:32 PM")
--- @param timestamp number
--- @return string: Formatted time string
function M.format_time(timestamp)
timestamp = M.normalize_timestamp(timestamp)
if not timestamp then
return ''
end
local same_day = os.date('%Y-%m-%d') == os.date('%Y-%m-%d', timestamp)
local same_year = os.date('%Y') == os.date('%Y', timestamp)
local locale_time = vim.trim(os.date('%X', timestamp) or '')
-- Keep output close to previous formatting by dropping seconds when present.
locale_time = locale_time:gsub('^(%d?%d:%d%d):%d%d(.*)$', '%1%2')
if locale_time == '' then
locale_time = vim.trim(os.date('%H:%M', timestamp) or '')
end
if same_day then
return locale_time
end
if same_year then
return string.format('%s %s', os.date('%d %b', timestamp), locale_time)
end
return string.format('%s %s', os.date('%d %b %Y', timestamp), locale_time)
end
---@param timestamp number
---@return number
function M.normalize_timestamp(timestamp)
if not timestamp then
return nil
end
if timestamp > 1e12 then
return math.floor(timestamp / 1000)
end
return timestamp
end
---@param start_time number
---@param end_time number|nil
---@return string|nil
function M.format_duration_seconds(start_time, end_time)
if not start_time or not end_time then
return nil
end
local elapsed_seconds = math.max(0, M.normalize_timestamp(end_time) - M.normalize_timestamp(start_time))
if elapsed_seconds < 1 then
return nil
end
return string.format('%ds', elapsed_seconds)
end
function M.index_of(tbl, value)
for i, v in ipairs(tbl) do
if v == value then
return i
end
end
return nil
end
function M.find_index_of(tbl, predicate)
for i, v in ipairs(tbl) do
if predicate(v) then
return i
end
end
return nil
end
function M.some(tbl, predicate)
for _, v in ipairs(tbl) do
if predicate(v) then
return true
end
end
return false
end
local _is_git_project = nil
function M.is_git_project()
if _is_git_project ~= nil then
return _is_git_project
end
local cwd = vim.fn.getcwd()
if not cwd then
_is_git_project = false
return _is_git_project
end
local git_dir = Path:new(cwd):joinpath('.git')
_is_git_project = git_dir:exists()
return _is_git_project
end
function M.format_number(n)
if not n or n <= 0 then
return nil
end
if n >= 1e6 then
return string.format('%.1fM', n / 1e6)
elseif n >= 1e3 then
return string.format('%.1fK', n / 1e3)
else
return tostring(n)
end
end
function M.format_percentage(n)
return n and n > 0 and string.format('%.1f%%', n * 100) or nil
end
function M.format_cost(c)
return c and c > 0 and string.format('$%.2f', c) or nil
end
function M.debounce(func, delay)
local timer = nil
return function(...)
if timer then
timer:stop()
end
local args = { ... }
timer = vim.defer_fn(function()
func(unpack(args))
end, delay or 100)
end
end
---@param dir string Directory path to read JSON files from
---@param max_items? number Maximum number of items to read
---@return table[]|nil Array of decoded JSON objects
function M.read_json_dir(dir, max_items)
if not dir or vim.fn.isdirectory(dir) == 0 then
return nil
end
local count = 0
local decoded_items = {}
for file, file_type in vim.fs.dir(dir) do
if file_type == 'file' and file:match('%.json$') then
local file_ok, content = pcall(vim.fn.readfile, dir .. '/' .. file)
if file_ok then
local lines = table.concat(content, '\n')
local ok, data = pcall(vim.json.decode, lines)
if ok and data then
table.insert(decoded_items, data)
end
end
end
count = count + 1
if max_items and count >= max_items then
break
end
end
if #decoded_items == 0 then
return nil
end
return decoded_items
end
--- Safely call a function if it exists.
--- @param fn function|nil
--- @param ... any
function M.safe_call(fn, ...)
local arg = { ... }
return fn and vim.schedule(function()
fn(unpack(arg))
end)
end
--- Call fn(...), notifying the user if it throws. Useful for protecting
--- callbacks where a thrown error would be silently swallowed.
--- @param fn function
--- @param ... any
function M.safe_pcall(fn, ...)
local ok, err = pcall(fn, ...)
if not ok then
vim.schedule(function()
vim.notify('[opencode.nvim] Unexpected error: ' .. vim.inspect(err))
end)
end
end
---@param version string
---@return number|nil, number|nil, number|nil
function M.parse_semver(version)
if not version or version == '' then
return nil
end
local major, minor, patch = version:match('(%d+)%.(%d+)%.?(%d*)')
if not major then
return nil
end
return tonumber(major) or 0, tonumber(minor) or 0, tonumber(patch) or 0
end
---@param version string
---@param required_version string
---@return boolean
function M.is_version_greater_or_equal(version, required_version)
local major, minor, patch = M.parse_semver(version)
local req_major, req_minor, req_patch = M.parse_semver(required_version)
if not major or not req_major then
return false
end
if major ~= req_major then
return major > req_major
end
if minor ~= req_minor then
return minor > req_minor
end
return patch >= req_patch
end
--- Parse arguments in the form of key=value, supporting dot notation for nested tables.
--- Example: "context.selection.enabled=false options
--- @param args_str string
--- @return table
function M.parse_dot_args(args_str)
local result = {}
for arg in string.gmatch(args_str, '[^%s]+') do
local key, value = arg:match('([^=]+)=([^=]+)')
if key and value then
local parts = vim.split(key, '.', { plain = true })
local t = result
for i = 1, #parts - 1 do
t[parts[i]] = t[parts[i]] or {}
t = t[parts[i]]
end
-- Convert string values to appropriate types
local parsed_value = value
if value == 'true' then
parsed_value = true
elseif value == 'false' then
parsed_value = false
elseif tonumber(value) then
parsed_value = tonumber(value)
end
t[parts[#parts]] = parsed_value
end
end
return result
end
--- Check if prompt is allowed via guard callback
--- @param guard_callback? function
--- @param mentioned_files? string[] List of mentioned files in the context
--- @return boolean allowed
--- @return string|nil error_message
function M.check_prompt_allowed(guard_callback, mentioned_files)
if not guard_callback then
return true, nil -- No guard = always allowed
end
if type(guard_callback) ~= 'function' then
return false, 'prompt_guard must be a function'
end
mentioned_files = mentioned_files or {}
local success, result = pcall(guard_callback, mentioned_files)
if not success then
return false, 'prompt_guard error: ' .. tostring(result)
end
if type(result) ~= 'boolean' then
return false, 'prompt_guard must return a boolean'
end
---@cast result boolean
return result, nil
end
local _filetype_overrides = {
javascriptreact = 'jsx',
typescriptreact = 'tsx',
typescript = 'ts',
javascipt = 'js',
sh = 'bash',
yaml = 'yml',
text = 'txt', -- nvim 0.12-nightly returns text as the type which breaks our unit tests
}
local _filetype_cache = {}
--- Get the markdown type to use based on the filename. First gets the neovim type
--- for the file. Then apply any specific overrides. Falls back to using the file
--- extension if nothing else matches
--- @param filename string filename, possibly including path
--- @return string markdown_filetype
function M.get_markdown_filetype(filename)
if not filename or filename == '' then
return ''
end
local cached = _filetype_cache[filename]
if cached ~= nil then
return cached
end
local file_type = vim.filetype.match({ filename = filename }) or ''
local result = _filetype_overrides[file_type] or (file_type ~= '' and file_type) or vim.fn.fnamemodify(filename, ':e')
_filetype_cache[filename] = result
return result
end
function M.strdisplaywidth(str)
local str = str:gsub('%%#.-#', ''):gsub('%%[%*]', '')
return vim.fn.strdisplaywidth(str)
end
--- Parse run command arguments with optional agent, model, variant, and context prefixes.
--- Returns opts table and remaining prompt string.
--- Format: [agent=<name>] [model=<model>] [variant=<variant>] [context=<key=value,...>] <prompt>
--- Also supports quick context syntax like "#buffer #git_diff" in the prompt
--- @param args string[]
--- @return table opts, string prompt
function M.parse_run_args(args)
local opts = {}
local prompt_start_idx = 1
for i, token in ipairs(args) do
local agent = token:match('^agent=(.+)$')
local model = token:match('^model=(.+)$')
local variant = token:match('^variant=(.+)$')
local context = token:match('^context=(.+)$')
if agent then
opts.agent = agent
prompt_start_idx = i + 1
elseif model then
opts.model = model
prompt_start_idx = i + 1
elseif variant then
opts.variant = variant
prompt_start_idx = i + 1
elseif context then
opts.context = M.parse_dot_args(context:gsub(',', ' '))
prompt_start_idx = i + 1
else
break
end
end
local prompt_tokens = vim.list_slice(args, prompt_start_idx)
local prompt = table.concat(prompt_tokens, ' ')
if prompt:find('#') then
local cleaned_prompt, quick_context = M.parse_quick_context_args(prompt)
prompt = cleaned_prompt
opts.context = vim.tbl_deep_extend('force', opts.context or {}, quick_context) --[[@as OpencodeContextConfig]]
end
return opts, prompt
end
---pcall but returns a full stacktrace on error
function M.pcall_trace(fn, ...)
return xpcall(fn, function(err)
return debug.traceback(err, 2)
end, ...)
end
function M.is_path_in_cwd(path)
local cwd = vim.fn.simplify(vim.fn.getcwd())
local cwd_prefix = cwd == '/' and cwd or (cwd .. '/')
local logical_path
if path:sub(1, 1) == '/' then
logical_path = vim.fn.simplify(path)
else
logical_path = vim.fn.simplify(cwd .. '/' .. path)
end
return logical_path == cwd or logical_path:sub(1, #cwd_prefix) == cwd_prefix
end
--- Check if a given path is in the system temporary directory.
--- Optionally match the filename against a pattern.
--- @param path string File path to check
--- @param pattern string|nil Optional Lua pattern to match the filename
--- @return boolean is_temp
function M.is_temp_path(path, pattern)
local temp_dir = vim.fn.tempname()
temp_dir = vim.fn.fnamemodify(temp_dir, ':h')
local abs_path = vim.fn.fnamemodify(path, ':p')
if abs_path:sub(1, #temp_dir) ~= temp_dir then
return false
end
if pattern then
local filename = vim.fn.fnamemodify(path, ':t')
return filename:match(pattern) ~= nil
end
return true
end
--- Parse quick context arguments and extract prompt.
--- Transforms quick context items like "generate a conventional commit #git_diff #buffer"
--- into a partial ContextConfig object with only enabled fields and returns the remaining text as prompt.
--- @param prompt string Context arguments string (e.g., "generate a conventional commit #buffer #git_diff")
--- @return string prompt, OpencodeContextConfig config
function M.parse_quick_context_args(prompt)
---@type OpencodeContextConfig
local config = { enabled = true }
if not prompt or prompt == '' then
return '', config
end
local function extract(items)
local found = false
for _, item in ipairs(items) do
local pattern = '#' .. item
local start_pos = prompt:lower():find(pattern:lower(), 1, true)
if start_pos then
found = true
local end_pos = start_pos + #pattern - 1
prompt = prompt:sub(1, start_pos - 1) .. prompt:sub(end_pos + 1)
end
end
return found
end
local cursor_enabled = extract({ 'cursor_data', 'cursor' })
if cursor_enabled then
config.cursor_data = { enabled = true, context_lines = 5 }
end
local info_enabled = extract({ 'info' })
local warning_enabled = extract({ 'warnings', 'warning', 'warn' })
local error_enabled = extract({ 'errors' })
if info_enabled or warning_enabled or error_enabled then
config.diagnostics = { enabled = true, only_closest = true }
if info_enabled then
config.diagnostics.info = true
end
if warning_enabled then
config.diagnostics.warning = true
end
if error_enabled then
config.diagnostics.error = true
end
end
local current_file_enabled = extract({ 'current_file', 'file' })
if current_file_enabled then
config.current_file = { enabled = true }
end
local selection_enabled = extract({ 'selection' })
if selection_enabled then
config.selection = { enabled = true }
end
local agents_enabled = extract({ 'agents' })
if agents_enabled then
config.agents = { enabled = true }
end
local buffer_enabled = extract({ 'buffer' })
if buffer_enabled then
config.buffer = { enabled = true }
end
local git_diff_enabled = extract({ 'git_diff', 'diff' })
if git_diff_enabled then
config.git_diff = { enabled = true }
end
return vim.trim(prompt:gsub('%s+', ' ')), config
end
function M.get_visual_range()
if not vim.fn.mode():match('[vV\022]') then
return nil
end
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes('<Esc>', true, false, true), 'nx', true)
local bufnr = vim.api.nvim_get_current_buf()
local start_pos = vim.fn.getpos("'<")
local end_pos = vim.fn.getpos("'>")
local start_line = start_pos[2]
local start_col = start_pos[3]
local end_line = end_pos[2]
local end_col = end_pos[3]
return {
bufnr = bufnr,
start_line = start_line,
start_col = start_col,
end_line = end_line,
end_col = end_col,
}
end
--- Sort items by priority level (low, medium, high) and then alphabetically by a key.
--- @param items table[] Array of items to sort
--- @param key_fn fun(item: table): string Function to extract the key from each item
--- @param priority_map? table<string, number> Optional custom priority map (defaults to {low=1, medium=2, high=3})
--- @return table[] sorted_items The sorted array (sorts in-place and returns the same array)
function M.sort_by_priority(items, key_fn, priority_map)
local default_priority = 99
table.sort(items, function(a, b)
local a_key = key_fn(a)
local b_key = key_fn(b)
local a_priority = priority_map[a_key] or default_priority
local b_priority = priority_map[b_key] or default_priority
if a_priority ~= b_priority then
return a_priority < b_priority
end
return a_key < b_key
end)
return items
end
return M