(feat): better history handling using priorities for commands

This commit is contained in:
Eduard Tolosa 2025-06-03 17:05:04 -05:00
parent 94ef5f3234
commit 7b9142e3ba

View file

@ -5,9 +5,6 @@ function __based
end end
set -l path (realpath (pwd)) set -l path (realpath (pwd))
set -l prefix ""
# Extract commandline prefix up to cursor safely
set -l buffer (commandline --current-buffer) set -l buffer (commandline --current-buffer)
set -l cursor_pos (commandline -C) set -l cursor_pos (commandline -C)
set -l prefix (string sub -l $cursor_pos -- "$buffer") set -l prefix (string sub -l $cursor_pos -- "$buffer")
@ -16,26 +13,69 @@ function __based
set prefix (string replace -a "'" "''" -- $prefix) set prefix (string replace -a "'" "''" -- $prefix)
set -l cmd_expr "%$prefix%" set -l cmd_expr "%$prefix%"
# If the user has disabled fuzzy matching
if set -q BASED_NO_FUZZY if set -q BASED_NO_FUZZY
set cmd_expr "$prefix%" set cmd_expr "$prefix%"
end end
# Build combined result set in SQL
if test -n "$prefix" if test -n "$prefix"
sqlite3 $db " set results (sqlite3 -batch $db "
SELECT cmd FROM log SELECT DISTINCT cmd FROM (
WHERE path = '$path' -- Prioritize commands in the current path, matching the prefix
AND cmd LIKE '$cmd_expr' SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 0 as priority
ORDER BY counter DESC, ts DESC;" | string collect FROM log
WHERE path = '$path' AND cmd LIKE '$cmd_expr'
GROUP BY cmd
UNION
-- Append the commands from the imported fish history that match the prefix
SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 1 as priority
FROM log
WHERE path = 'fish_history' AND cmd LIKE '$cmd_expr'
AND cmd NOT IN (
SELECT cmd
FROM log
WHERE path = '$path' AND cmd LIKE '$cmd_expr'
)
GROUP BY cmd
)
ORDER BY priority ASC, counter DESC, max_ts DESC;")
else else
sqlite3 $db " set results (sqlite3 -batch $db "
SELECT cmd SELECT DISTINCT cmd FROM (
FROM ( -- Get the most recent command across all paths
SELECT cmd, MAX(ts) as max_ts SELECT cmd, max_ts, counter, priority FROM (
SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 0 as priority
FROM log FROM log
GROUP BY cmd GROUP BY cmd
ORDER BY max_ts DESC
LIMIT 1
) )
ORDER BY max_ts DESC;" | string collect
UNION
-- Commands in the current context
SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 1 as priority
FROM log
WHERE path = '$path'
GROUP BY cmd
UNION
-- Commands in the imported fish history
SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 2 as priority
FROM log
WHERE path = 'fish_history'
AND cmd NOT IN (
SELECT cmd
FROM log
WHERE path = '$path'
)
GROUP BY cmd
)
ORDER BY priority ASC, counter DESC, max_ts DESC;")
end end
printf "%s\n" $results
end end