about summary refs log tree commit diff stats
path: root/bash/prompt.bash
blob: e51db96e4d39fcf19177a395e0bfab8391488e92 (plain)
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
# bash prompt

MY_BASH_PROMPT=smiley_prompt

# terminal title (current directory)
__prompt_term_title() { # __prompt_term_title TITLE...
	printf '\033]0;%s\007\n' "$*"
}

__prompt_exit_code() { # __prompt_exit_code CODES...
	# Each CODE is of the form N=STR.  If the code doesn't match one of CODES,
	# its number will be printed.
	local ec=$?
	for code; do
		if ((ec == ${code%=*})); then
			printf '%s\n' "${code#*=}"
			return
		elif ((ec == 0)) && [[ "${code%=*}" = ok ]]; then
			printf '%s\n' "${code#*=}"
			return
		elif ((ec > 0)) && [[ "${code%=*}" = fail ]]; then
			printf '%s\n' "${code#*=}"
			return
		fi
	done
	printf '%s\n' "$ec"
}

git_prompt_integration() {
	# git bit
	# see https://unix.stackexchange.com/questions/278206
	possible_git_prompt_locations=(
		/usr/share/git/git-prompt.sh                         # Arch, etc. (default?)
		/usr/lib/git-core/git-sh-prompt                      # Debian, Ubuntu ...
		/usr/share/git-core/contrib/completion/git-prompt.sh # Fedora ??
		# I have yet to find Alpine's git prompt location.
	)

	for file in "${possible_git_prompt_locations[@]}"; do
		if [[ -f "$file" ]]; then
			source "$file" &&
				PS1+='\[\e[35m\]$(__git_ps1) \[\e[0m\]'
			break
		fi
	done
}

two_line_prompt() {
	PS1=

	# user, host, and cwd
	PROMPT_DIRTRIM=3 # how many dirs above current to print (rest are '...')
	PS1+='\[\e[0;46m\]\u@\h \w'

	# newline
	PS1+='\[\e[0m\]\n'

	PS1+='\[\e[31m\]$(__prompt_exit_code 0=)\[\e[0m\]'
	PS1+='\[$(__prompt_term_title "$USER@$(hostname): $PWD")\]'

	# delimiter
	PS1+='; '
}

smiley_prompt() {
	__prompt_ec() { case $? in 0) echo '^_^' ;; *) echo ';_;' ;; esac }

	PS1='\[\e[33m\]$(__prompt_exit_code "ok=^_^" "fail=;_;")'
	PS1+=' \w\[\e[0m\]'

	git_prompt_integration

	PS1+='\[$(__prompt_term_title "$USER@$(hostname): $PWD")\]'
	PS1+=' \$ '
}

eval "$MY_BASH_PROMPT"