-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshell_utils
executable file
·122 lines (101 loc) · 2.65 KB
/
shell_utils
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
#!/usr/bin/env bash
# get base directory
BASEDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# define colors
red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
blue=$(tput setaf 4)
normal=$(tput sgr0)
# Header logging
function p_header {
printf "\n${blue}%s${normal}\n--------------------------------\n" "$@"
}
# Success logging
function p_success {
printf "${green}✓ %s${normal}\n\n" "$@"
}
# Error logging
function p_error {
printf "${red}x %s${normal}\n" "$@"
}
# Warning logging
function p_warning {
printf "${yellow}! %s${normal}\n" "$@"
}
# Create symbolic link for dotfiles at home directory
# link_dotfile {source} {symlink}
function link_dotfile {
p_header "Creating symlink to ${2} in ${HOME} directory..."
if [ -f "${HOME}/${2}" ] && [ -L "${HOME}/${2}" ]; then
rm -v "${HOME}/${2}"
elif [ -f "${HOME}/${2}" ] && [ ! -L "${HOME}/${2}" ]; then
# shellcheck disable=SC2088
p_warning "${HOME}/${2} exists, backing it up to ${HOME}/${2}.backup"
# force overwriting backup file
mv -f "${HOME}/${2}" "${HOME}/${2}.backup"
fi
# Create the symlink.
# -s for symbolic
# -v for verbose
# -f for force
if ln -svf "${BASEDIR}/${1}" "${HOME}/${2}"; then
p_success "Done"
return 0
else
p_error "Failed to create symlink for ${1}"
return 1
fi
}
# ----------------------------------------------------------
# Test whether a command exists
# $1 - cmd to test
type_exists() {
if type -P "$1" > /dev/null; then
return 0
fi
return 1
}
# Test whether a Homebrew formula is already installed
# $1 - formula name (may include options)
formula_exists() {
if brew list "$1" &> /dev/null; then
return 0
fi
return 1
}
# Check whether the first argument is present in the
# array which is the second argument
contains_element() {
local element match=$1
# shift the argument list by 1 to the left
# dropping the first argument
shift
# for without an in implicitly iterates over the
# argument list
for element; do
if [[ "${element}" == "${match}" ]]; then
return 0
fi
done
return 1
}
# ----------------------------------------------------------
# Ask for confirmation before proceeding
seek_confirmation() {
printf "\n"
e_warning "$@"
read -rp "Continue? (y/n) " -n 1
printf "\n"
}
# Test whether the result of an 'ask' is a confirmation
is_confirmed() {
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
return 0
fi
return 1
}
# Test whether we're in a git repo
is_git_repo() {
git rev-parse --is-inside-work-tree &> /dev/null
}