notes/scripts/dye
2022-12-19 17:27:44 -08:00

95 lines
2.6 KiB
Bash
Executable file

#!/usr/bin/env bash
# set -vx
# Copyright (C) 2022 Brian Hayes
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
printhelp() {
cat << EOM
usage: dye [-h|-r] [color_code]
options:
-x hex code to rgb
-r rgb to hex
examples:
dye -x "#FFFFFF"
dye -r 255 255 255
EOM
exit 1
}
hex_to_rgb() {
: "${1/\#}"
((r=16#${_:0:2},g=16#${_:2:2},b=16#${_:4:2}))
printf '%s\n' "rgba($r, $g, $b)"
}
rgb_to_hex() {
printf '#%02x%02x%02x\n' "$1" "$2" "$3"
}
error() {
printf "error: %s\n" "$1" 1>&2
${2:+exit $2}
}
dependencycheck() {
local dep missingdependencies=0
for dep in "$@" ; do
if ! command -v "$dep" &> /dev/null ; then
error "dependency not met: $dep"
fi
done
if [[ $missingdependencies -gt 0 ]] ; then
exit 1
fi
}
main() {
while getopts ":x:r:?" arg; do
case $arg in
x)
rgbaval=$(hex_to_rgb "${2:-''}")
printf "%s\n" "$rgbaval"
read -e -r -p "save code to clipboard?(y/n): " clipit
if [[ "$clipit" == "yes" || "$clipit" == "y" ]]; then
dependencycheck xclip
printf "%s" "$rgbaval" | xclip -sel clip
fi
;;
r)
hexval=$(rgb_to_hex "${2:-''}")
printf "%s\n" "$hexval"
read -e -r -p "save code to clipboard?(y/n): " clipit
if [[ "$clipit" == "yes" || "$clipit" == "y" ]]; then
dependencycheck xclip
printf "%s" "$hexval" | xclip -sel clip
fi
;;
?)
printhelp
;;
esac
done
}
main "$@"
# Credits:
# hex_to_rgb() and rgb_to_hex() taken from Akash Mittal:
# https://akashmittal.com/code-example-convert-hex-color-to-rgb-rgb-to-hex-using-bash-script/
# https://www.linkedin.com/in/akashrishimittal/
#
# error() and dependencycheck() copied from tomocafe:
# https://github.com/tomocafe