forked from larkery/zsh-histdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlite-history.zsh
366 lines (337 loc) · 11.3 KB
/
sqlite-history.zsh
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
which sqlite3 >/dev/null 2>&1 || return;
typeset -g HISTDB_QUERY=""
typeset -g HISTDB_FILE="${HOME}/.histdb/zsh-history.db"
typeset -g HISTDB_SESSION=""
typeset -g HISTDB_HOST=""
typeset -g HISTDB_INSTALLED_IN="${(%):-%N}"
typeset -g HISTDB_AWAITING_EXIT=0
sql_escape () {
sed -e "s/'/''/g" <<< "$@"
}
_histdb_query () {
sqlite3 "${HISTDB_FILE}" "$@"
[[ "$?" -ne 0 ]] && echo "error in $@"
}
_histdb_init () {
if ! [[ -e "${HISTDB_FILE}" ]]; then
local hist_dir="$(dirname ${HISTDB_FILE})"
if ! [[ -d "$hist_dir" ]]; then
mkdir -p -- "$hist_dir"
fi
_histdb_query <<-EOF
create table commands (argv text, unique(argv) on conflict ignore);
create table places (host text, dir text, unique(host, dir) on conflict ignore);
create table history (session int,
command_id int references commands (rowid),
place_id int references places (rowid),
exit_status int,
start_time int,
duration int);
EOF
fi
if [[ -z "${HISTDB_SESSION}" ]]; then
HISTDB_HOST="'$(sql_escape ${HOST})'"
HISTDB_SESSION=$(_histdb_query "select 1+max(session) from history inner join places on places.rowid=history.place_id where places.host = ${HISTDB_HOST}")
HISTDB_SESSION="${HISTDB_SESSION:-0}"
readonly HISTDB_SESSION
fi
}
declare -a _BORING_COMMANDS
_BORING_COMMANDS=("^ls$" "^cd$" "^ " "^histdb" "^top$" "^htop$")
histdb-update-outcome () {
local retval=$?
local finished=$(date +%s)
if [[ $HISTDB_AWAITING_EXIT == 1 ]]; then
_histdb_init
_histdb_query "update history set exit_status = ${retval}, duration = ${finished} - start_time
where rowid = (select max(rowid) from history) and session = ${HISTDB_SESSION}"
HISTDB_AWAITING_EXIT=0
fi
}
zshaddhistory () {
local cmd="${1[0, -2]}"
for boring ($_BORING_COMMANDS); do
if [[ "$cmd" =~ $boring ]]; then
return 0
fi
done
local cmd="'$(sql_escape $cmd)'"
local pwd="'$(sql_escape ${PWD})'"
local started=$(date +%s)
_histdb_init
if [[ "$cmd" != "''" ]]; then
_histdb_query \
"insert into commands (argv) values (${cmd});
insert into places (host, dir) values (${HISTDB_HOST}, ${pwd});
insert into history
(session, command_id, place_id, start_time)
select
${HISTDB_SESSION},
commands.rowid,
places.rowid,
${started}
from
commands, places
where
commands.argv = ${cmd} and
places.host = ${HISTDB_HOST} and
places.dir = ${pwd}
;"
HISTDB_AWAITING_EXIT=1
fi
return 0
}
histdb-top () {
_histdb_init
local sep=$'\x1f'
local field
local join
local table
1=${1:-cmd}
case "$1" in
dir)
field=places.dir
join='places.rowid = history.place_id'
table=places
;;
cmd)
field=commands.argv
join='commands.rowid = history.command_id'
table=commands
;;;
esac
_histdb_query -separator "$sep" \
-header \
"select count(*) as count, places.host, replace($field, '
', '
$sep$sep') as ${1:-cmd} from history left join commands on history.command_id=commands.rowid left join places on history.place_id=places.rowid group by places.host, $field order by count(*)" |
column -t -s "$sep"
}
histdb-sync () {
_histdb_init
local hist_dir="$(dirname ${HISTDB_FILE})"
if [[ -d "$hist_dir" ]]; then
pushd "$hist_dir"
if [[ $(git rev-parse --is-inside-work-tree) != "true" ]] || [[ "$(git rev-parse --show-toplevel)" != "$(pwd)" ]]; then
git init
git config merge.histdb.driver "$(dirname ${HISTDB_INSTALLED_IN})/histdb-merge %O %A %B"
echo "$(basename ${HISTDB_FILE}) merge=histdb" | tee -a .gitattributes &>-
git add .gitattributes
git add "$(basename ${HISTDB_FILE})"
fi
git commit -am "history" && git pull --no-edit && git push
popd
fi
}
histdb () {
_histdb_init
local -a opts
local -a hosts
local -a indirs
local -a atdirs
local -a sessions
zparseopts -E -D -a opts \
-host+::=hosts \
-in+::=indirs \
-at+::=atdirs \
-forget \
-detail \
-sep:- \
-exact \
d h -help \
s+::=sessions \
-from:- -until:- -limit:-
local usage="usage:$0 terms [--host] [--in] [--at] [-s n]+* [--from] [--until] [--limit] [--forget] [--sep x] [--detail]
--host print the host column and show all hosts (otherwise current host)
--host x find entries from host x
--in find only entries run in the current dir or below
--in x find only entries in directory x or below
--at like --in, but excluding subdirectories
-s n only show session n
-d debug output query that will be run
--detail show details
--forget forget everything which matches in the history
--exact don't match substrings
--sep x print with separator x, and don't tabulate
--from x only show commands after date x (sqlite date parser)
--until x only show commands before date x (sqlite date parser)
--limit n only show n rows. defaults to $LINES or 25"
local selcols="session as ses, dir"
local cols="session, replace(places.dir, '$HOME', '~') as dir"
local where="not (commands.argv like 'histdb%')"
if [[ -p /dev/stdout ]]; then
local limit=""
else
local limit="${$((LINES - 4)):-25}"
fi
local forget="0"
local exact=0
if (( ${#hosts} )); then
local hostwhere=""
local host=""
for host ($hosts); do
host="${${host#--host}#=}"
hostwhere="${hostwhere}${host:+${hostwhere:+ or }places.host='$(sql_escape ${host})'}"
done
where="${where}${hostwhere:+ and (${hostwhere})}"
cols="${cols}, places.host as host"
selcols="${selcols}, host"
else
where="${where} and places.host=${HISTDB_HOST}"
fi
if (( ${#indirs} + ${#atdirs} )); then
local dirwhere=""
local dir=""
for dir ($indirs); do
dir="${${${dir#--in}#=}:-$PWD}"
dirwhere="${dirwhere}${dirwhere:+ or }places.dir like '$(sql_escape $dir)%'"
done
for dir ($atdirs); do
dir="${${${dir#--at}#=}:-$PWD}"
dirwhere="${dirwhere}${dirwhere:+ or }places.dir = '$(sql_escape $dir)'"
done
where="${where}${dirwhere:+ and (${dirwhere})}"
fi
if (( ${#sessions} )); then
local sin=""
local ses=""
for ses ($sessions); do
ses="${${${ses#-s}#=}:-${HISTDB_SESSION}}"
sin="${sin}${sin:+, }$ses"
done
where="${where}${sin:+ and session in ($sin)}"
fi
local sep=$'\x1f'
local debug=0
local opt=""
for opt ($opts); do
case $opt in
--sep*)
sep=${opt#--sep}
;;
--from*)
local from=${opt#--from}
case $from in
-*)
from="datetime('now', '$from')"
;;
today)
from="datetime('now', 'start of day')"
;;
yesterday)
from="datetime('now', 'start of day', '-1 day')"
;;
esac
where="${where} and datetime(start_time, 'unixepoch') >= $from"
;;
--until*)
local until=${opt#--until}
case $until in
-*)
until="datetime('now', '$until')"
;;
today)
until="datetime('now', 'start of day')"
;;
yesterday)
until="datetime('now', 'start of day', '-1 day')"
;;
esac
where="${where} and datetime(start_time, 'unixepoch') <= $until"
;;
-d)
debug=1
;;
--detail)
cols="${cols}, exit_status, duration "
selcols="${selcols}, exit_status as [?],duration as secs "
;;
-h|--help)
echo "$usage"
return 0
;;
--forget)
forget=1
;;
--exact)
exact=1
;;
--limit*)
limit=${opt#--limit}
;;
esac
done
if [[ -n "$*" ]]; then
if [[ $exact -eq 0 ]]; then
where="${where} and commands.argv like '%$(sql_escape $@)%'"
else
where="${where} and commands.argv like '$(sql_escape $@)'"
fi
fi
if [[ $forget -gt 0 ]]; then
limit=""
fi
local seps=$(echo "$cols" | tr -c -d ',' | tr ',' $sep)
cols="${cols}, replace(commands.argv, '
', '
$seps') as argv, max(start_time) as max_start"
local mst="datetime(max_start, 'unixepoch')"
local dst="datetime('now', 'start of day')"
local timecol="strftime(case when $mst > $dst then '%H:%M' else '%d/%m' end, max_start, 'unixepoch', 'localtime') as time"
selcols="${timecol}, ${selcols}, argv as cmd"
local query="select ${selcols} from (select ${cols}
from
history
left join commands on history.command_id = commands.rowid
left join places on history.place_id = places.rowid
where ${where}
group by history.command_id, history.place_id
order by max_start desc
${limit:+limit $limit}) order by max_start asc"
## min max date?
local count_query="select count(*) from (select ${cols}
from
history
left join commands on history.command_id = commands.rowid
left join places on history.place_id = places.rowid
where ${where}
group by history.command_id, history.place_id
order by max_start desc) order by max_start asc"
if [[ $debug = 1 ]]; then
echo "$query"
else
local count=$(_histdb_query "$count_query")
if [[ -p /dev/stdout ]]; then
buffer() {
## this runs out of memory for big files I think perl -e 'local $/; my $stdin = <STDIN>; print $stdin;'
temp=$(mktemp)
cat > "$temp"
cat -- "$temp"
rm -f -- "$temp"
}
else
buffer() {
cat
}
fi
if [[ $sep == $'\x1f' ]]; then
_histdb_query -header -separator $sep "$query" | iconv -f utf-8 -t utf-8 -c | column -t -s $sep | buffer
else
_histdb_query -header -separator $sep "$query" | buffer
fi
[[ -n $limit ]] && [[ $limit -lt $count ]] && echo "(showing $limit of $count results)"
fi
if [[ $forget -gt 0 ]]; then
read -q "REPLY?Forget all these results? [y/n] "
if [[ $REPLY =~ "[yY]" ]]; then
_histdb_query "delete from history where
history.rowid in (
select history.rowid from
history
left join commands on history.command_id = commands.rowid
left join places on history.place_id = places.rowid
where ${where})"
_histdb_query "delete from commands where commands.rowid not in (select distinct history.command_id from history)"
fi
fi
}