-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhistdb.bash
1607 lines (1421 loc) · 48.7 KB
/
histdb.bash
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
# blesh/contrib/histdb (C) 2023, Koichi Murase <[email protected]>
ble/util/assign _ble_histdb_sqlite3 'builtin type -P sqlite3 2>/dev/null'
if [[ ! -x $_ble_histdb_sqlite3 ]]; then
ble/util/print 'contrib/histdb: "sqlite3" is required for this module.' >&2
return 1
fi
ble-import util.bgproc
_ble_histdb_version=3
#------------------------------------------------------------------------------
# histdb_remarks
bleopt/declare -v histdb_remarks 'git: \q{contrib/histdb-remarks-git}'
_ble_histdb_remarks_data=()
function ble/prompt/unit:_ble_histdb_remarks/update {
ble/prompt/unit/add-hash '$bleopt_histdb_remarks'
ble/prompt/unit:{section}/update _ble_histdb_remarks "$bleopt_histdb_remarks" no-trace
}
## @fn ble/histdb/.get-remarks
## @var[out] remarks
function ble/histdb/.get-remarks {
remarks=
if [[ $bleopt_histdb_remarks ]]; then
local ret
ble/prompt/unit#update _ble_histdb_remarks "$bleopt_histdb_remarks"
ble/prompt/unit:{section}/get _ble_histdb_remarks
remarks=$ret
fi
}
function ble/prompt/backslash:contrib/histdb-remarks-git {
ble-import prompt-git
function ble/prompt/backslash:contrib/histdb-remarks-git {
local "${_ble_contrib_prompt_git_vars[@]/%/=}" # WA #D1570 checked
ble/contrib/prompt-git/initialize || return 0
ble/contrib/prompt-git/update-head-information
local state; ble/contrib/prompt-git/get-state
local dirty_mark; ble/contrib/prompt-git/get-dirty-mark
local path=${git_base%.git}
path=${path%/}
path=${path##*?/}
[[ $PWD == "$git_base"/?* ]] &&
path="$path/${PWD#$git_base/}"
ble/prompt/print "git: ${branch:-(detached)} ${hash:-(orphan)}$dirty_mark${state:+ $state} @ ${path:-/}"
} && "$FUNCNAME"
}
#------------------------------------------------------------------------------
# background sqlite3 process
bleopt/declare -v histdb_ignore ''
bleopt/declare -v histdb_file ''
function ble/histdb/.get-filename {
local basename=${bleopt_histdb_file%.sqlite3}
local hostname=${HOSTNAME:-$_ble_base_env_HOSTNAME}
hostname=${hostname//'/'/'%'} # filename cannot contian /
ret=${basename:-$_ble_base_state/history}${hostname:+@$hostname}.sqlite3
}
## @var _ble_histdb_file
_ble_histdb_file=
## @arr _ble_histdb_bgproc=(fd_response fd_request - bgpid)
##
_ble_histdb_bgproc=()
_ble_histdb_bgproc_fname=()
_ble_histdb_timeout=5000
_ble_histdb_keepalive=1800 # sec
function ble/histdb/escape-for-sqlite-glob {
ret=$1
if [[ $ret == *["[*?"]* ]]; then
local a b
for a in '[' '*' '?'; do
b=[$a] ret=${ret//"$a"/"$b"}
done
fi
}
function ble/histdb/sqlite3.flush {
if [[ ${_ble_histdb_bgproc[0]} && _ble_bash -ge 40000 ]]; then
local line IFS=
ble/bash/read-timeout 0.001 -r -d '' line <&"${_ble_histdb_bgproc[0]}"
fi
}
function ble/histdb/sqlite3.request {
ble/histdb/sqlite3.open
if [[ ${_ble_histdb_bgproc[1]} ]]; then
ble/histdb/sqlite3.flush
ble/util/print "$1" >&"${_ble_histdb_bgproc[1]}"
else
[[ $1 == .exit ]] && return 0
"$_ble_histdb_sqlite3" -quote "$_ble_histdb_file" ".timeout $_ble_histdb_timeout" "$1"
fi
}
function ble/histdb/read-single-value {
local line nl=$'\n' q=\' qq=\'\' Q="'\''"
local IFS=
if ble/bash/read line && [[ $line == \'* ]]; then
local out=$line ext=0
while ((ext==0)) && ! ble/string#match "$out" '^'"$q"'([^'\'']|'"$qq"')*'"$q"'$'; do
ble/bash/read line; ext=$?
out=$out$nl$line
done
line=$out
fi
line=${line#$q}
line=${line%$q}
line=${line//$qq/$q}
line=$q${line//$q/$Q}$q
ble/util/print "ret=$line"
}
function ble/histdb/sqlite3.request-single-value {
local query=$1 opts=$2
ble/histdb/sqlite3.open
if [[ ${_ble_histdb_bgproc[1]} && _ble_bash -ge 40000 ]]; then
ble/histdb/sqlite3.flush
ble/util/print "$query" >&"${_ble_histdb_bgproc[1]}"
local sync_command='ble/histdb/read-single-value <&"${_ble_histdb_bgproc[0]}"'
local sync_condition='((sync_elapsed<200)) || ! ble/complete/check-cancel'
local sync_opts=progressive-weight
[[ :$opts: == *:auto:* && $bleopt_complete_timeout_auto ]] &&
sync_opts=$sync_opts:timeout=$((bleopt_complete_timeout_auto))
ble/util/assign ret 'ble/util/conditional-sync "$sync_command" "$sync_condition" "" "$sync_opts"' &>/dev/null; local ext=$?
builtin eval -- "$ret"
((ext==142)) && ext=148
return "$ext"
else
local out q=\' qq=\'\'
ble/util/assign out '"$_ble_histdb_sqlite3" -quote "$_ble_histdb_file" ".timeout $_ble_histdb_timeout" "$query"'
out=${out#$q}
out=${out%$q}
ret=${out//$qq/$q}
fi
}
function ble/histdb/sqlite3.proc {
exec "$_ble_histdb_sqlite3" -quote -cmd "-- [ble: $BLE_SESSION_ID]" "$_ble_histdb_file"
}
_ble_histdb_keepalive_enabled=
ble/is-function ble/util/idle.push &&
_ble_histdb_keepalive_enabled=1
## @fn ble/histdb/sqlite3.open
## @var[ref] _ble_histdb_file
## @arr[out] _ble_histdb_bgproc
## @arr[out] _ble_histdb_bgproc_fname
function ble/histdb/sqlite3.open {
if [[ $_ble_histdb_file ]]; then
# background process に依らないモードの時は OK
ble/util/bgproc#opened _ble_histdb || return 0
ble/util/bgproc#alive _ble_histdb; local state=$?
if ((state==0)); then
ble/util/bgproc#keepalive _ble_histdb
return 0
else
if ((state==3)); then
# background process が死んでいる時は再度開き直す。
ble/util/print 'histdb: background sqlite3 is inactive.' >&2
fi
ble/util/bgproc#start _ble_histdb
return "$?"
fi
fi
local ret; ble/histdb/.get-filename
_ble_histdb_file=$ret
local session_id=$_ble_base_session
local start_time=${session_id%%/*}
IFS=, builtin eval 'local groups="${GROUPS[*]}"'
local user=${USER:-$_ble_base_env_USER}
local hostname=${HOSTNAME:-$_ble_base_env_HOSTNAME}
local screen_info= ssh_info=
[[ $STY ]] && screen_info="$STY $WINDOW"
[[ $SSH_TTY ]] && ssh_info="$SSH_TTY $SSH_CONNECTION"
local bgproc_opts=owner-close-on-unload:kill-timeout=60000
[[ $_ble_histdb_keepalive_enabled ]] &&
bgproc_opts=$bgproc_opts:timeout=$((_ble_histdb_keepalive*1000))
if ble/util/bgproc#open _ble_histdb ble/histdb/sqlite3.proc "$bgproc_opts"; (($?!=0&&$?!=3)); then
# Note: システムが元々サポートしていない場合 ($? == 3) はエラーメッセージは
# 出さない。
local msg='[ble histdb: background sqlite3 failed to start]'
ble/util/print "${_ble_term_setaf[9]}$msg$_ble_term_sgr0" >&2
fi
local ret q=\' qq=\'\'
ble/histdb/sqlite3.request-single-value "
BEGIN IMMEDIATE TRANSACTION;
CREATE TABLE IF NOT EXISTS misc(key TEXT PRIMARY KEY, value INTEGER);
INSERT OR IGNORE INTO misc values('version', $_ble_histdb_version);
CREATE TABLE IF NOT EXISTS sessions(
session_id TEXT PRIMARY KEY, pid INTEGER, ppid INTEGER,
hostname TEXT, user TEXT, uid INTEGER, euid INTEGER, groups TEXT,
start_time INTEGER, start_wd TEXT,
bash_path TEXT, bash_version TEXT, shlvl INTEGER,
blesh_path TEXT, blesh_version TEXT,
term TEXT, lang TEXT, display TEXT, screen_info TEXT, ssh_info TEXT,
tty TEXT, last_time INTEGER, last_wd TEXT);
CREATE TABLE IF NOT EXISTS command_history(
session_id TEXT, command_id INTEGER,
lineno INTEGER, history_index INTEGER,
command TEXT, cwd TEXT, inode INTEGER, issue_time INTEGER,
status INTEGER,
pipestatus TEXT,
lastarg TEXT,
bgpid INTEGER,
exec_time INTEGER,
exec_time_beg INTEGER,
exec_time_end INTEGER,
exec_time_real INTEGER,
exec_time_usr INTEGER,
exec_time_sys INTEGER,
exec_time_cpu INTEGER,
exec_time_usr_self INTEGER,
exec_time_sys_self INTEGER,
exec_time_usr_chld INTEGER,
exec_time_sys_chld INTEGER,
remarks TEXT,
PRIMARY KEY (session_id, command_id));
CREATE TABLE IF NOT EXISTS words(
word TEXT PRIMARY KEY, count INTEGER, ctime INTEGER, mtime INTEGER);
INSERT OR IGNORE INTO
sessions(
session_id, pid, ppid,
hostname, user, uid, euid, groups,
start_time, start_wd,
bash_path, bash_version, shlvl,
blesh_path, blesh_version,
term, lang, display, screen_info, ssh_info,
tty)
VALUES(
'${session_id//$q/$qq}', '${$//$q/$qq}', '${PPID//$q/$qq}',
'${hostname//$q/$q}', '${user//$q/$qq}', '${UID//$q/$qq}', '${EUID/$q/$qq}', '${groups//$q/$qq}',
'${start_time//$q/$qq}', '${PWD//$q/$qq}',
'${BASH//$q/$qq}', '${BASH_VERSION//$q/$qq}', '${SHLVL//$q/$qq}',
'${_ble_base_blesh//$q/$qq}', '${BLE_VERSION//$q/$qq}',
'${TERM//$q/$qq}', '${LANG//$q/$qq}', '${DISPLAY//$q/$qq}', '${screen_info//$q/$qq}', '${ssh_info//$q/$qq}',
'${_ble_prompt_const_l//$q/$qq}');
COMMIT;
SELECT VALUE FROM misc WHERE key = 'version';"
local version=$ret
if [[ $version ]] && ((version<_ble_histdb_version)); then
local query=
((version<2)) &&
query=$query$_ble_term_nl"ALTER TABLE command_history ADD COLUMN inode INTEGER;"
((version<3)) &&
query=$query$_ble_term_nl"ALTER TABLE command_history ADD COLUMN remarks TEXT;"
query=$query$_ble_term_nl"UPDATE misc SET value = $_ble_histdb_version WHERE key = 'version';"
ble/histdb/sqlite3.request "$query"
fi
}
function ble/util/bgproc/onstart:_ble_histdb {
ble/util/bgproc#post _ble_histdb ".timeout $_ble_histdb_timeout"
}
function ble/util/bgproc/onstop:_ble_histdb {
ble/util/bgproc#post _ble_histdb '.exit'
}
function ble/histdb/sqlite3.close {
[[ $_ble_histdb_file ]] || return 0
local session_id=$_ble_base_session ret
ble/util/time; local time=$ret
ble/histdb/sqlite3.request "
UPDATE sessions SET
last_time = '${time//$q/$qq}',
last_wd = '${PWD//$q/$qq}'
WHERE session_id = '${session_id//$q/$qq}';"
ble/util/bgproc#close _ble_histdb
_ble_histdb_file=
}
_ble_histdb_exec_ignore=()
_ble_histdb_exec_cwd=
_ble_histdb_exec_cwd_inode=
function ble/histdb/update-cwd-inode {
[[ $PWD == "$_ble_histdb_exec_cwd" ]] && return 0
_ble_histdb_exec_cwd=$PWD
_ble_histdb_exec_cwd_inode=
if local ret; ble/file#inode "$PWD" && ble/string#match "$ret" '^[0-9]+$'; then
_ble_histdb_exec_cwd_inode=$ret
fi
}
function ble/histdb/collect-words.proc {
[[ $wtype && ! ${wtype//[0-9]} ]] &&
ble/array#push collect_words "${_ble_edit_str:wbeg:wlen}"
}
function ble/histdb/collect-words {
ble-edit/content/update-syntax
local -a collect_words=()
ble/syntax/tree-enumerate-in-range 0 "${#_ble_edit_str}" ble/histdb/collect-words.proc
ble/array#reverse collect_words
ret=()
local word
"${_ble_util_set_declare[@]//NAME/mark}" # WA #D1570 checked
for word in "${collect_words[@]}"; do
# Note (#D1958): Even if the same words appeared in a single command, we
# only count 1 for one command. This is because the "words" table is
# used for the word completion, where the count is used as an importance
# measure. We count the number of commands where the word appears
# because the same word can easily appear in a single command multiple
# times.
ble/set#contains mark "$word" && return 0
ble/set#add mark "$word"
ble/array#push ret "$word"
done
}
## @fn ble/histdb/exec_register.hook command
## @var[in] command_id
## @var[in] lineno
## これらの変数は exec_register の側で用意される。
function ble/histdb/exec_register.hook {
local command=$1
if [[ $bleopt_histdb_ignore ]]; then
local patterns pattern
ble/string#split patterns : "$bleopt_histdb_ignore"
for pattern in "${patterns[@]}"; do
if [[ $command == $pattern ]]; then
_ble_histdb_exec_ignore[command_id]=1
return 0
fi
done
fi
builtin unset -v '_ble_histdb_exec_ignore[command_id]'
local q=\' qq=\'\'
local session_id=$_ble_base_session ret
ble/util/time; local issue_time=$ret
# @var history_index ... history index: The current command might not be
# registered to the command history, but we always pick up the index of the
# last entry because there is no way to check it reliably. We could compare
# the top element with BASH_COMMAND, but the history entry might be
# transformed by HISTCONTROL=strip, etc.
local history_index; ble/history/get-count -v history_index
((history_index++))
# Expand "bleopt histdb_remarks"
local remarks
ble/histdb/.get-remarks
local ret word extra_query=
ble/histdb/collect-words
for word in "${ret[@]}"; do
extra_query=$extra_query"INSERT OR REPLACE INTO words(word, count, ctime, mtime)
VALUES('${word//$q/$qq}',
coalesce((SELECT count FROM words WHERE word = '${word//$q/$qq}'), 0) + 1,
coalesce((SELECT ctime FROM words WHERE word = '${word//$q/$qq}'), $issue_time),
$issue_time);"
done
ble/histdb/update-cwd-inode
local inode=$_ble_histdb_exec_cwd_inode
ble/histdb/sqlite3.request "
BEGIN IMMEDIATE TRANSACTION;
UPDATE sessions SET
last_time = '${issue_time//$q/$qq}',
last_wd = '${PWD//$q/$qq}'
WHERE session_id = '${session_id//$q/$qq}';
-- Update duplicate command_id
UPDATE command_history SET
command_id = min(0, (SELECT command_id FROM command_history WHERE session_id = '${session_id//$q/$qq}')) - 1
WHERE session_id = '${session_id//$q/$qq}' AND command_id = $command_id;
-- Add command_history entry
INSERT INTO command_history(
session_id, command_id,
lineno, history_index,
command, cwd, inode, issue_time, remarks)
VALUES(
'${session_id//$q/$qq}', '${command_id//$q/$qq}',
'${lineno//$q/$qq}', '${history_index//$q/$qq}',
'${command//$q/$qq}', '${PWD//$q/$qq}', ${inode:-None}, '${issue_time//$q/$qq}', '${remarks//$q/$qq}');
$extra_query
COMMIT;"
}
function ble/histdb/postexec.hook {
local session_id=$_ble_base_session
local command_id=$_ble_edit_exec_command_id
if [[ ${_ble_histdb_exec_ignore[command_id]+set} ]]; then
builtin unset -v '_ble_histdb_exec_ignore[command_id]'
return 0
fi
local ret
ble/util/time; local last_time=$ret
IFS=, builtin eval 'local pipestatus="${_ble_edit_exec_PIPESTATUS[*]}"'
local lastarg=$_ble_edit_exec_lastarg
((${#lastarg}>=1000)) && lastarg=${lastarg::997}...
local real=$_ble_exec_time_tot
local usr=$_ble_exec_time_usr
local sys=$_ble_exec_time_sys
local cpu=$((real>0?(usr+sys)/real:0))
local usr_chld=$((usr-_ble_exec_time_usr_self))
local sys_chld=$((sys-_ble_exec_time_sys_self))
local q=\' qq=\'\'
ble/histdb/sqlite3.request "
UPDATE sessions SET
last_time = '${last_time//$q/$qq}',
last_wd = '${PWD//$q/$qq}'
WHERE session_id = '${session_id//$q/$qq}';
UPDATE command_history SET
status = '${_ble_edit_exec_lastexit//$q/$qq}',
pipestatus = '${pipestatus//$q/$qq}',
lastarg = '${lastarg//$q/$qq}',
bgpid = '${!//$q/$qq}',
exec_time = '${_ble_exec_time_ata//$q/$qq}',
exec_time_beg = '${_ble_exec_time_beg//$q/$qq}',
exec_time_end = '${_ble_exec_time_end//$q/$qq}',
exec_time_real = '${real//$q/$qq}',
exec_time_usr = '${usr//$q/$qq}',
exec_time_sys = '${sys//$q/$qq}',
exec_time_cpu = '${cpu//$q/$qq}',
exec_time_usr_self = '${_ble_exec_time_usr_self//$q/$qq}',
exec_time_sys_self = '${_ble_exec_time_sys_self//$q/$qq}',
exec_time_usr_chld = '${usr_chld//$q/$qq}',
exec_time_sys_chld = '${sys_chld//$q/$qq}'
WHERE session_id = '${session_id//$q/$qq}' AND command_id = $command_id;"
}
function ble/histdb/backup {
local file=$1
ble/bin#freeze-utility-path -n gzip || return 1
local backup=${file%.sqlite3}.backup.sqlite3 q=\' qq=\'\'
if [[ -s $backup.gz ]]; then
# If there is already an up-to-date backup file, we skip the backup.
local ret now
ble/util/time; now=$ret
ble/file#mtime "$backup.gz" || return 1
((now>ret+24*3600)) || return 1
fi
"$_ble_histdb_sqlite3" "$file" \
".timeout $_ble_histdb_timeout" \
"PRAGMA quick_check;" \
".backup '${backup//$q/$qq}'" \
"ATTACH DATABASE '${backup//$q/$qq}' AS backup;
PRAGMA backup.quick_check;" >/dev/null &&
ble/bin/gzip -c "$backup" >| "$backup.gz.part" &&
[[ -s $backup.gz.part ]] &&
ble/bin/mv -f "$backup.gz.part" "$backup.gz" &&
ble/bin/rm -f "$backup"
}
function ble/histdb/unload.hook {
if [[ $_ble_histdb_file ]]; then
local file=$_ble_histdb_file
ble/histdb/sqlite3.close
ble/histdb/backup "$file"
fi
}
# 設定が変化して記録先の history.sqlite3 のパスが変わったら現在のファイルは閉じ
# る。必要になった時に初めて新しいファイルを開く。
function ble/histdb/exec_end.hook {
local ret; ble/histdb/.get-filename
[[ $ret == "$_ble_histdb_file" ]] ||
((${#_ble_edit_exec_lines[@]})) ||
ble/histdb/sqlite3.close
}
blehook exec_register!=ble/histdb/exec_register.hook
blehook POSTEXEC!=ble/histdb/postexec.hook
blehook exec_end!=ble/histdb/exec_end.hook
blehook unload!=ble/histdb/unload.hook
#------------------------------------------------------------------------------
# auto-complete
function ble/complete/auto-complete/source:histdb-history {
[[ $_ble_history_prefix ]] && return 1
local limit=$((bleopt_line_limit_length)) limit_condition=
if ((limit)); then
((limit-=${#_ble_edit_str},limit>0)) || return 1
limit_condition=" AND length(command) <= $limit"
fi
local ret
ble/histdb/escape-for-sqlite-glob "$_ble_edit_str"; local pat=$ret?*
ble/histdb/update-cwd-inode
local inode=$_ble_histdb_exec_cwd_inode
local q=\' qq=\'\'
ble/histdb/sqlite3.request-single-value "
SELECT coalesce(
(SELECT command FROM (SELECT command, max(issue_time) FROM command_history WHERE command GLOB '${pat//$q/$qq}' AND cwd = '${PWD//$q/$qq}$limit_condition')),
${inode:+(SELECT command FROM (SELECT command, max(issue_time) FROM command_history WHERE command GLOB '${pat//$q/$qq}' AND inode = $inode$limit_condition)),}
'');"
[[ $ret == "$_ble_edit_str"?* ]] || return 1
ble/complete/auto-complete/enter h 0 "${ret:${#_ble_edit_str}}" '' "$ret"
}
function ble/complete/auto-complete/source:histdb-word {
[[ $_ble_history_prefix ]] && return 1
local iN=${#_ble_edit_str}
((_ble_edit_ind>0)) || return 1
local limit=$((bleopt_line_limit_length)) limit_condition=
if ((limit)); then
((limit-=iN,limit>0)) || return 1
limit_condition=" AND length(word) <= $limit"
fi
local -a wbegins=()
if ((_ble_edit_ind<iN)); then
# 行中にいる時は現在位置で完結している単語だけを対象にする。
if [[ ${_ble_syntax_tree[_ble_edit_ind-1]} ]]; then
local tree
ble/string#split-words tree "${_ble_syntax_tree[_ble_edit_ind-1]}"
local wtype=${tree[0]} wlen=${tree[1]}
[[ $wtype && ! ${wtype//[0-9]} && wlen -ge 0 ]] &&
ble/array#push wbegins "$((_ble_edit_ind-wlen))"
elif local ret; ble/syntax/completion-context/.search-last-istat "$((_ble_edit_ind-1))"; then
local istat=$ret stat wlen
ble/string#split-words stat "${_ble_syntax_stat[istat]}"
if (((wlen=stat[1])>=0)); then
ble/array#push wbegins "$((istat-wlen))"
elif [[ ${_ble_syntax_bash_command_EndWtype[stat[0]]:-} ]]; then
# 単語の始まりの時 (_ble_syntax_bash_command_EndWtype で判定できるのかは実は非自明)
ble/array#push wbegins "$istat"
fi
fi
else
# 閉じていない入れ子に対する列挙
local -a stat nest tree
ble/string#split-words stat "${_ble_syntax_stat[iN]}"
local wlen tclen
if (((wlen=stat[1])>=0)); then
ble/array#push wbegins "$((iN-wlen))"
elif (((tclen=stat[4])>=0)); then
local wend=$((iN-tclen))
ble/string#split-words tree "${_ble_syntax_tree[wend-1]}"
local wtype=${tree[0]} wlen=${tree[1]}
[[ $wtype && ! ${wtype//[0-9]} && wlen -ge 0 ]] &&
ble/array#push wbegins "$((wend-wlen))"
fi
local inest=$iN nlen=${stat[3]}
while ((nlen>0)); do
((inest-=nlen))
ble/string#split-words nest "${_ble_syntax_nest[inest]}"
(((wlen=nest[1])>=0)) &&
ble/array#push wbegins "$((inest-wlen))"
nlen=${nest[3]}
done
fi
((${#wbegins[@]})) || return 1
local -a sqls=()
local i q=\' qq=\'\'
for i in "${wbegins[@]}"; do
local word=${_ble_edit_str:i:_ble_edit_ind-i}
[[ $word ]] || continue
local ret; ble/histdb/escape-for-sqlite-glob "$word"
local pat=$ret?*
ble/array#push sqls "SELECT '$i:' || word FROM (SELECT word, max(mtime) FROM words WHERE word GLOB '${pat//$q/$qq}'$limit_condition)"
done
((${#sqls[@]})) || return 1
ble/array#reverse sqls
sqls=("${sqls[@]/#/(}") # WA #D1570 checked
sqls=("${sqls[@]/%/)}") # WA #D1570 checked
ble/array#push sqls "''"
IFS=, builtin eval 'local query="select coalesce(${sqls[*]});"'
local ret
ble/histdb/sqlite3.request-single-value "$query" auto || return 1
[[ $ret == *:* ]] || return 1
local index=${ret%%:*} insert=${ret#*:}
if local comps=${_ble_edit_str:index:_ble_edit_ind-index}; [[ $insert == "$comps"* ]]; then
local ins=${insert:_ble_edit_ind-index}
ble/complete/auto-complete/enter c "$_ble_edit_ind" "$ins" "$insert" "$ins" "$ins" ' '
else
ble/complete/auto-complete/enter r "$index" " [$insert] " "$insert" "$insert" "$insert" ' '
fi
}
ble/util/import/eval-after-load core-complete '
ble/array#insert-before _ble_complete_auto_source history histdb-history
ble/array#push _ble_complete_auto_source histdb-word'
[[ $_ble_histdb_keepalive_enabled ]] &&
ble/util/idle.push ble/histdb/sqlite3.open
#------------------------------------------------------------------------------
# ble histdb command
function ble-histdb {
builtin eval -- "$_ble_bash_POSIXLY_CORRECT_local_adjust"
local set shopt ext
ble/base/.adjust-bash-options set shopt
if (($#==0)); then
ble/histdb/sub:query 'select command from command_history;'
ext=$?
elif ble/is-function ble/histdb/sub:"$1"; then
ble/histdb/sub:"$@"
ext=$?
else
builtin printf 'ble-histdb: unknown command "%s"\n' "$1"
ext=2
fi
ble/base/.restore-bash-options set shopt
ble/util/setexit "$ext"
builtin eval -- "$_ble_bash_POSIXLY_CORRECT_local_return"
}
# 一般的な補完のフレームワークを作っても良いのではないかという気がしてきたが、
# それは後で。
function ble/cmdinfo/complete:ble-histdb {
if ((comp_cword==1)); then
local ret sub
ble/util/compgen ret -A function -- 'ble/histdb/sub:'
((${#ret[@]})) || return 0
local cands
for sub in "${ret[@]#ble/histdb/sub:}"; do
if [[ $sub != */* && $sub == "$COMPV"* ]]; then
ble/array#push cands "$sub"
fi
done
if ((${#cands[@]})); then
local "${_ble_complete_yield_varnames[@]/%/=}" # disable=#D1570
ble/complete/cand/yield.initialize word
ble/complete/cand/yield.batch word
fi
fi
}
function ble/histdb/sub:query {
local ret
ble/histdb/.get-filename; local histdb_file=$ret
"$_ble_histdb_sqlite3" "$histdb_file" '.timeout 1000' "$@"
}
#------------------------------------------------------------------------------
function ble/histdb/count2si {
local si
si=('' k M G T P E Z Y R Q)
local count=$1 i
for ((i=0;i<${#si[@]}-1;i++,count/=1000)); do
if ((count<1000)); then
ret=$count${si[i]}
return 0
elif ((count<100000)); then
count=${count%???}.${count:${#count}-3}
ret=${count::4}${si[i+1]}
return 0
fi
done
ret=$count${si[${#si[@]}-1]}
}
# modified ble/contrib/prompt-elapsed/output-sec.ps
function ble/histdb/usec2s {
local usec=${1:-0}
if ((usec<1000)); then
ret=${usec}us
elif ((usec<100000)); then
usec=${usec%???}.${usec:${#usec}-3}
ret=${usec::4}ms
else
ble/histdb/msec2s "$((usec/1000))"
fi
}
function ble/histdb/msec2s {
local msec=${1:-0}
if ((msec<1000)); then
ret=${msec}ms
elif ((msec<100000)); then
msec=${msec%???}.${msec:${#msec}-3}
ret=${msec::4}s
else
ble/histdb/sec2s "$((msec/1000))"
fi
}
function ble/histdb/sec2s {
local sec=${1:-0} min
((min=sec/60,sec%=60))
if ((min<100)); then
ret=${min}m${sec}s
return 0
fi
local hour; ((hour=min/60,min%=60))
if ((hour<100)); then
ret="${hour}h:${min}m:${sec}s"
return 0
fi
local day; ((day=hour/24,hour%=24))
if ((day<365)); then
ret="${day}d-${hour}h:${min}m"
return 0
fi
local year; ((year=day/365,day%=365))
ret="${year}y-${day}d-${hour}h"
return 0
}
#------------------------------------------------------------------------------
# usage: ble histdb stats
bleopt/declare -v histdb_stats_items 'commands unique-commands successful-commands exec-time exec-cpu-time words sessions directories'
function ble/histdb/sub:stats/get-user-name {
ble/bin#has git && ble/util/assign ret '
git config user.name 2>/dev/null
' && [[ $ret ]] && return 0
ble/bin#has getenv && ble/util/assign ret '
getent passwd 2>/dev/null | ble/bin/awk -F : -v UID="$UID" '\''
$3==UID {
sub(/[[:blank:]]*[<>].*$/, "", $5);
print $5;
}
'\''
' && [[ $ret ]] && return 0
ret=${USER:-$_ble_base_env_USER}@${HOSTNAME:-$_ble_base_env_HOSTNAME}
}
## @fn ble/histdb/sub:stats/where.check condition
## @param[in] condition
## @var[ref] where
function ble/histdb/sub:stats/where.check {
where="${where:- WHERE}${where:+ AND} $1"
}
## @fn ble/histdb/sub:stats/where.check-datetime column
## @param[in] column
## @var[in] time_beg time_end
## @var[ref] where
function ble/histdb/sub:stats/where.check-datetime {
[[ $time_beg ]] && ble/histdb/sub:stats/where.check "$1 >= $time_beg"
[[ $time_end ]] && ble/histdb/sub:stats/where.check "$1 < $time_end"
}
function ble/histdb/sub:stats/item:commands {
case $1 in
(init)
local where=
ble/histdb/sub:stats/where.check-datetime issue_time
ble/array#push queries "SELECT count(*) FROM command_history$where;" ;;
(get)
ble/array#push names 'Total commands'
local ret
ble/histdb/count2si "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:unique-commands {
case $1 in
(init)
local where=
ble/histdb/sub:stats/where.check-datetime issue_time
ble/array#push queries "SELECT count(*) FROM (SELECT DISTINCT command FROM command_history$where);" ;;
(get)
ble/array#push names 'Total unique commands'
local ret
ble/histdb/count2si "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:successful-commands {
case $1 in
(init)
local where=
ble/histdb/sub:stats/where.check 'status == 0'
ble/histdb/sub:stats/where.check-datetime issue_time
ble/array#push queries "SELECT count(*) FROM (SELECT command FROM command_history$where);" ;;
(get)
ble/array#push names 'Total successful commands'
local ret
ble/histdb/count2si "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:sessions {
case $1 in
(init)
local where=
if [[ $time_end ]]; then
ble/histdb/sub:stats/where.check-datetime start_time
else
ble/histdb/sub:stats/where.check-datetime last_time
fi
ble/array#push queries "SELECT count(*) FROM sessions$where;" ;;
(get)
ble/array#push names 'Total sessions'
local ret
ble/histdb/count2si "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:words {
case $1 in
(init)
local where=
if [[ $time_end ]]; then
ble/histdb/sub:stats/where.check-datetime ctime
else
ble/histdb/sub:stats/where.check-datetime mtime
fi
ble/array#push queries "SELECT count(*) FROM words$where;" ;;
(get)
ble/array#push names 'Total distinct words'
local ret
ble/histdb/count2si "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:directories {
case $1 in
(init)
local where=
ble/histdb/sub:stats/where.check-datetime issue_time
ble/array#push queries "SELECT count(*) FROM (SELECT DISTINCT cwd FROM command_history$where);" ;;
(get)
ble/array#push names 'Total directories'
local ret
ble/histdb/count2si "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:exec-time {
case $1 in
(init)
local where=
ble/histdb/sub:stats/where.check-datetime issue_time
ble/array#push queries "SELECT sum(exec_time) FROM command_history$where;" ;;
(get)
ble/array#push names 'Total execution time'
local ret
ble/histdb/usec2s "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats/item:exec-cpu-time {
case $1 in
(init)
local where=
ble/histdb/sub:stats/where.check-datetime issue_time
ble/array#push queries "SELECT sum(exec_time_usr + exec_time_sys) FROM command_history$where;" ;;
(get)
ble/array#push names 'Total CPU time'
local ret
ble/histdb/msec2s "$2"
ble/array#push values "$ret" ;;
esac
}
function ble/histdb/sub:stats {
local period=${1-}
local time_beg= time_end=
if [[ $period ]]; then
local ret
if ble/string#match "$period" '^([0-9]+)([smhdMy])$'; then
local delta=${BASH_REMATCH[1]}
case ${BASH_REMATCH[2]} in
(m) ((delta*=60)) ;;
(h) ((delta*=3600)) ;;
(d) ((delta*=3600*24)) ;;
(M) ((delta*=3600*24*30)) ;;
(y) ((delta*=3600*24*365)) ;;
esac
ble/util/time
((time_beg=ret-delta))
elif ble/string#match "$period" '^2[0-9]{3}(-(0[1-9]|1[0-2])(-(0[1-9]|[12][0-9]|3[01]))?)?$'; then
local y=${period::4} m=${BASH_REMATCH[2]-} d=${BASH_REMATCH[4]-}
if [[ $d ]]; then
m=${m#0} d=${d#0}
ble/util/mktime "$y-$m-$d 00:00:00"
time_beg=$ret
# Note: we here assume that 01-32 is equivalent to 02-01, etc.
ble/util/mktime "$y-$m-$((d+1)) 00:00:00"
time_end=$ret
elif [[ $m ]]; then
m=${m#0}
ble/util/mktime "$y-$m-01 00:00:00"
time_beg=$ret
ble/util/mktime "$((y+m/12))-$((m%12+1))-01 00:00:00"
time_end=$ret
else
ble/util/mktime "$y-01-01 00:00:00"
time_beg=$ret
ble/util/mktime "$((y+1))-01-01 00:00:00"
time_end=$ret
fi
else
ble/util/print "ble-histdb-stats: unrecognized argument '$period'" 2>/dev/null
return 2
fi
fi
local -a queries=()
local items item
ble/string#split-words items "$bleopt_histdb_stats_items"
for item in "${items[@]}"; do
ble/histdb/sub:stats/item:"$item" init
done
local IFS=$_ble_term_IFS
ble/histdb/sub:query -separator ' ' "${queries[*]}" | {
local result
ble/util/mapfile result
local ret sgr0=$_ble_term_sgr0
ble/color/gspec2sgr 'fg=27,bold'; local sgr1=$ret
ble/histdb/sub:stats/get-user-name
ble/util/print "$sgr1$ret's Shell Stats${period:+ ($period)}$sgr0"
local -a names=() values=()
local i=0
for item in "${items[@]}"; do
ble/histdb/sub:stats/item:"$item" get "${result[i++]}"
done
local name max_name_width=0
for name in "${names[@]}"; do
local w=$((${#name}+1))
((max_name_width<w)) && ((max_name_width=w))
done
ble/color/gspec2sgr 'bold'; local sgr2=$ret
for i in "${!names[@]}"; do
builtin printf ' %s%-*s %s%s\n' "$sgr2" "$max_name_width" "${names[i]}:" "${values[i]}" "$sgr0"
done
}
}
#------------------------------------------------------------------------------
# lib: ble/getopts
## @fn ble/getopts/scan-definition type script
## @param[in] type
## Specify the type of
##
## @fn[opt] ble/getopts/scan-definition:TYPE/label
## @fn[opt] ble/getopts/scan-definition:TYPE/flag
## @fn[opt] ble/getopts/scan-definition:TYPE/option
##
## @param[in] script
## Define the command-line interface by calling label:, flag:, and option:
##
_ble_getopts_definition_headers=(label flag option arguments)
function ble/getopts/scan-definition {
local type=$1 def=$2 header fn
for header in "${_ble_getopts_definition_headers[@]}"; do
fn=ble/getopts/scan-definition:$type/$header