(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
set -l path (realpath (pwd))
set -l prefix ""
# Extract commandline prefix up to cursor safely
set -l buffer (commandline --current-buffer)
set -l cursor_pos (commandline -C)
set -l prefix (string sub -l $cursor_pos -- "$buffer")
@ -16,26 +13,69 @@ function __based
set prefix (string replace -a "'" "''" -- $prefix)
set -l cmd_expr "%$prefix%"
# If the user has disabled fuzzy matching
if set -q BASED_NO_FUZZY
set cmd_expr "$prefix%"
end
# Build combined result set in SQL
if test -n "$prefix"
sqlite3 $db "
SELECT cmd FROM log
WHERE path = '$path'
AND cmd LIKE '$cmd_expr'
ORDER BY counter DESC, ts DESC;" | string collect
set results (sqlite3 -batch $db "
SELECT DISTINCT cmd FROM (
-- Prioritize commands in the current path, matching the prefix
SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 0 as priority
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
sqlite3 $db "
SELECT cmd
FROM (
SELECT cmd, MAX(ts) as max_ts
set results (sqlite3 -batch $db "
SELECT DISTINCT cmd FROM (
-- Get the most recent command across all paths
SELECT cmd, max_ts, counter, priority FROM (
SELECT cmd, MAX(ts) as max_ts, MAX(counter) as counter, 0 as priority
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
printf "%s\n" $results
end