~kris/dots

srice

9f828eb14bdd54d2c4fd8a3b2c90253021df3152 — Kris Yotam 2 months ago a71a43c
mksh: backslash-escape commands in history hook to bypass module aliases (wc=tokei, tr=transmission-remote, cat=bat)
1 files changed, 10 insertions(+), 7 deletions(-)

M .mkshrc
M .mkshrc => .mkshrc +10 -7
@@ 32,10 32,12 @@ _kh_log() {
	case "$cmd" in history*) return ;; esac
	[ -f "$_kh_key_file" ] || return
	[ -f "$_kh_db" ] || return
	typeset escaped_cmd=$(print -r -- "$cmd" | sed "s/'/''/g")
	typeset escaped_pwd=$(print -r -- "$pwd_path" | sed "s/'/''/g")
	typeset key=$(cat "$_kh_key_file")
	(sqlcipher "$_kh_db" "PRAGMA key = '$key'; INSERT INTO terminal_history (command, exit_code, pwd, shell) VALUES ('$escaped_cmd', $exit_code, '$escaped_pwd', 'mksh');" &) >/dev/null 2>&1
	# backslash-escape command names: interactive mksh expands aliases
	# inside command substitution, and the modules alias cat/sed/etc.
	typeset escaped_cmd=$(print -r -- "$cmd" | \sed "s/'/''/g")
	typeset escaped_pwd=$(print -r -- "$pwd_path" | \sed "s/'/''/g")
	typeset key=$(\cat "$_kh_key_file")
	(\sqlcipher "$_kh_db" "PRAGMA key = '$key'; INSERT INTO terminal_history (command, exit_code, pwd, shell) VALUES ('$escaped_cmd', $exit_code, '$escaped_pwd', 'mksh');" &) >/dev/null 2>&1
}

# Command history logging hook.


@@ 60,14 62,15 @@ else
	_kh_prompt() {
		typeset ec="$1" sz prev cmd
		[ -f "$HISTFILE" ] || return
		sz=$(wc -c < "$HISTFILE" 2>/dev/null)
		prev=$(cat "$_kh_state" 2>/dev/null)
		# backslash-escapes bypass the module aliases (wc=tokei, tr=..., cat=bat)
		sz=$(\wc -c < "$HISTFILE" 2>/dev/null)
		prev=$(\cat "$_kh_state" 2>/dev/null)
		print -r -- "$sz" > "$_kh_state"
		# first prompt of the session: record baseline, do not log
		[ -z "$prev" ] && return
		# only log when a new command was appended to history
		[ "$sz" -gt "$prev" ] 2>/dev/null || return
		cmd=$(tail -c 4096 "$HISTFILE" | tr "\377" "\n" | tail -n1 | cut -b5- | tr -d "\0")
		cmd=$(\tail -c 4096 "$HISTFILE" | \tr "\377" "\n" | \tail -n1 | \cut -b5- | \tr -d "\0")
		_kh_log "$cmd" "$ec"
	}
	# leading $(...) captures $? first so the exit code is accurate; the