Merge pull request #1820 from buhl/composure

Vendoring the composure
pull/1823/head
Noah Gorny 2021-02-03 09:06:35 +02:00 committed by GitHub
commit ce6487f63e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 1588 additions and 677 deletions

View File

@ -38,6 +38,7 @@ repos:
types: [file] types: [file]
- id: dot-bash - id: dot-bash
name: Check .bash files against bash-it requirements name: Check .bash files against bash-it requirements
exclude: "test/test_helper.bash"
entry: ./hooks/dot-bash.sh entry: ./hooks/dot-bash.sh
language: system language: system
files: "\\.bash$" files: "\\.bash$"

View File

@ -3,8 +3,7 @@
BASH_IT_LOG_PREFIX="core: main: " BASH_IT_LOG_PREFIX="core: main: "
# Only set $BASH_IT if it's not already set # Only set $BASH_IT if it's not already set
if [ -z "$BASH_IT" ]; if [ -z "$BASH_IT" ]; then
then
# Setting $BASH to maintain backwards compatibility # Setting $BASH to maintain backwards compatibility
export BASH_IT=$BASH export BASH_IT=$BASH
BASH="$(bash -c 'echo $BASH')" BASH="$(bash -c 'echo $BASH')"
@ -13,8 +12,9 @@ then
fi fi
# Load composure first, so we support function metadata # Load composure first, so we support function metadata
# shellcheck source=./lib/composure.bash # shellcheck disable=SC1090
source "${BASH_IT}/lib/composure.bash" source "${BASH_IT}"/vendor/github.com/erichs/composure/composure.sh
# We need to load logging module first as well in order to be able to log # We need to load logging module first as well in order to be able to log
# shellcheck source=./lib/log.bash # shellcheck source=./lib/log.bash
source "${BASH_IT}/lib/log.bash" source "${BASH_IT}/lib/log.bash"
@ -23,22 +23,21 @@ source "${BASH_IT}/lib/log.bash"
[ -z "$BASH_IT_OLD_BASH_SETUP" ] || _log_warning "BASH_IT variable not initialized, please upgrade your bash-it version and reinstall it!" [ -z "$BASH_IT_OLD_BASH_SETUP" ] || _log_warning "BASH_IT variable not initialized, please upgrade your bash-it version and reinstall it!"
# For backwards compatibility, look in old BASH_THEME location # For backwards compatibility, look in old BASH_THEME location
if [ -z "$BASH_IT_THEME" ]; if [ -z "$BASH_IT_THEME" ]; then
then
_log_warning "BASH_IT_THEME variable not initialized, please upgrade your bash-it version and reinstall it!" _log_warning "BASH_IT_THEME variable not initialized, please upgrade your bash-it version and reinstall it!"
export BASH_IT_THEME="$BASH_THEME"; export BASH_IT_THEME="$BASH_THEME"
unset BASH_THEME; unset BASH_THEME
fi fi
# support 'plumbing' metadata # support 'plumbing' metadata
cite _about _param _example _group _author _version cite _about _param _example _group _author _version
cite about-alias about-plugin about-completion
# libraries, but skip appearance (themes) for now # libraries, but skip appearance (themes) for now
_log_debug "Loading libraries(except appearance)..." _log_debug "Loading libraries(except appearance)..."
LIB="${BASH_IT}/lib/*.bash" LIB="${BASH_IT}/lib/*.bash"
APPEARANCE_LIB="${BASH_IT}/lib/appearance.bash" APPEARANCE_LIB="${BASH_IT}/lib/appearance.bash"
for _bash_it_config_file in $LIB for _bash_it_config_file in $LIB; do
do
if [ "$_bash_it_config_file" != "$APPEARANCE_LIB" ]; then if [ "$_bash_it_config_file" != "$APPEARANCE_LIB" ]; then
filename=${_bash_it_config_file##*/} filename=${_bash_it_config_file##*/}
filename=${filename%.bash} filename=${filename%.bash}
@ -51,8 +50,7 @@ done
# Load vendors # Load vendors
BASH_IT_LOG_PREFIX="vendor: " BASH_IT_LOG_PREFIX="vendor: "
for _bash_it_vendor_init in "${BASH_IT}"/vendor/init.d/*.bash for _bash_it_vendor_init in "${BASH_IT}"/vendor/init.d/*.bash; do
do
_log_debug "Loading \"$(basename "${_bash_it_vendor_init}" .bash)\"..." _log_debug "Loading \"$(basename "${_bash_it_vendor_init}" .bash)\"..."
# shellcheck disable=SC1090 # shellcheck disable=SC1090
source "${_bash_it_vendor_init}" source "${_bash_it_vendor_init}"
@ -66,8 +64,7 @@ BASH_IT_LOG_PREFIX="core: main: "
source "${BASH_IT}/scripts/reloader.bash" source "${BASH_IT}/scripts/reloader.bash"
# Load enabled aliases, completion, plugins # Load enabled aliases, completion, plugins
for file_type in "aliases" "plugins" "completion" for file_type in "aliases" "plugins" "completion"; do
do
# shellcheck source=./scripts/reloader.bash # shellcheck source=./scripts/reloader.bash
source "${BASH_IT}/scripts/reloader.bash" "skip" "$file_type" source "${BASH_IT}/scripts/reloader.bash" "skip" "$file_type"
done done
@ -100,10 +97,8 @@ fi
BASH_IT_LOG_PREFIX="core: main: " BASH_IT_LOG_PREFIX="core: main: "
_log_debug "Loading custom aliases, completion, plugins..." _log_debug "Loading custom aliases, completion, plugins..."
for file_type in "aliases" "completion" "plugins" for file_type in "aliases" "completion" "plugins"; do
do if [ -e "${BASH_IT}/${file_type}/custom.${file_type}.bash" ]; then
if [ -e "${BASH_IT}/${file_type}/custom.${file_type}.bash" ]
then
BASH_IT_LOG_PREFIX="${file_type}: custom: " BASH_IT_LOG_PREFIX="${file_type}: custom: "
_log_debug "Loading component..." _log_debug "Loading component..."
# shellcheck disable=SC1090 # shellcheck disable=SC1090
@ -115,8 +110,7 @@ done
BASH_IT_LOG_PREFIX="core: main: " BASH_IT_LOG_PREFIX="core: main: "
_log_debug "Loading general custom files..." _log_debug "Loading general custom files..."
CUSTOM="${BASH_IT_CUSTOM:=${BASH_IT}/custom}/*.bash ${BASH_IT_CUSTOM:=${BASH_IT}/custom}/**/*.bash" CUSTOM="${BASH_IT_CUSTOM:=${BASH_IT}/custom}/*.bash ${BASH_IT_CUSTOM:=${BASH_IT}/custom}/**/*.bash"
for _bash_it_config_file in $CUSTOM for _bash_it_config_file in $CUSTOM; do
do
if [ -e "${_bash_it_config_file}" ]; then if [ -e "${_bash_it_config_file}" ]; then
filename=$(basename "${_bash_it_config_file}") filename=$(basename "${_bash_it_config_file}")
filename=${filename%*.bash} filename=${filename%*.bash}
@ -144,14 +138,13 @@ fi
# Load all the Jekyll stuff # Load all the Jekyll stuff
if [ -e "$HOME/.jekyllconfig" ] if [ -e "$HOME/.jekyllconfig" ]; then
then
# shellcheck disable=SC1090 # shellcheck disable=SC1090
. "$HOME/.jekyllconfig" . "$HOME/.jekyllconfig"
fi fi
# BASH_IT_RELOAD_LEGACY is set. # BASH_IT_RELOAD_LEGACY is set.
if ! command -v reload &>/dev/null && [ -n "$BASH_IT_RELOAD_LEGACY" ]; then if ! command -v reload &> /dev/null && [ -n "$BASH_IT_RELOAD_LEGACY" ]; then
case $OSTYPE in case $OSTYPE in
darwin*) darwin*)
alias reload='source ~/.bash_profile' alias reload='source ~/.bash_profile'

View File

@ -23,6 +23,8 @@ hooks
# #
.gitattributes .gitattributes
lint_clean_files.sh lint_clean_files.sh
install.sh
bash_it.sh
# plugins # plugins
# #
@ -92,5 +94,9 @@ aliases/available/dnf.aliases.bash
aliases/available/vim.aliases.bash aliases/available/vim.aliases.bash
aliases/available/git.aliases.bash aliases/available/git.aliases.bash
# tests
test/test_helper.bash
# vendor init files # vendor init files
vendor/.gitattributes
vendor/init.d vendor/init.d

View File

@ -37,9 +37,12 @@ General Load Order
The main ``bash_it.sh`` script loads the frameworks individual components in the following order: The main ``bash_it.sh`` script loads the frameworks individual components in the following order:
* ``lib/composure.bash``
* ``vendor/github.com/erichs/composure/composure.sh``
* ``lib/log.bash``
* ``vendor/init.d/*.bash`` * ``vendor/init.d/*.bash``
* Files in ``lib`` with the exception of ``appearance.bash`` - this means that ``composure.bash`` is loaded again here (possible improvement?) * Files in ``lib`` with the exception of ``appearance.bash`` - this means that ``log.bash`` is loaded again here (possible improvement?)
* Enabled ``aliases`` * Enabled ``aliases``
* Enabled ``plugins`` * Enabled ``plugins``
* Enabled ``completions`` * Enabled ``completions``

View File

@ -7,11 +7,11 @@ function show_usage() {
echo -e "Usage:\n$0 [arguments] \n" echo -e "Usage:\n$0 [arguments] \n"
echo "Arguments:" echo "Arguments:"
echo "--help (-h): Display this help message" echo "--help (-h): Display this help message"
echo "--silent (-s): Install default settings without prompting for input"; echo "--silent (-s): Install default settings without prompting for input"
echo "--interactive (-i): Interactively choose plugins" echo "--interactive (-i): Interactively choose plugins"
echo "--no-modify-config (-n): Do not modify existing config file" echo "--no-modify-config (-n): Do not modify existing config file"
echo "--append-to-config (-a): Keep existing config file and append bash-it templates at the end" echo "--append-to-config (-a): Keep existing config file and append bash-it templates at the end"
exit 0; exit 0
} }
# enable a thing # enable a thing
@ -34,19 +34,17 @@ function load_some() {
single_type=$(echo "$file_type" | sed -e "s/aliases$/alias/g" | sed -e "s/plugins$/plugin/g") single_type=$(echo "$file_type" | sed -e "s/aliases$/alias/g" | sed -e "s/plugins$/plugin/g")
enable_func="_enable-$single_type" enable_func="_enable-$single_type"
[ -d "$BASH_IT/$file_type/enabled" ] || mkdir "$BASH_IT/$file_type/enabled" [ -d "$BASH_IT/$file_type/enabled" ] || mkdir "$BASH_IT/$file_type/enabled"
for path in "$BASH_IT/${file_type}/available/"[^_]* for path in "$BASH_IT/${file_type}/available/"[^_]*; do
do
file_name=$(basename "$path") file_name=$(basename "$path")
while true while true; do
do
just_the_name="${file_name%%.*}" just_the_name="${file_name%%.*}"
read -e -n 1 -p "Would you like to enable the $just_the_name $file_type? [y/N] " RESP read -r -e -n 1 -p "Would you like to enable the $just_the_name $file_type? [y/N] " RESP
case $RESP in case $RESP in
[yY]) [yY])
$enable_func $just_the_name $enable_func "$just_the_name"
break break
;; ;;
[nN]|"") [nN] | "")
break break
;; ;;
*) *)
@ -59,9 +57,9 @@ function load_some() {
# Back up existing profile # Back up existing profile
function backup() { function backup() {
test -w "$HOME/$CONFIG_FILE" && test -w "$HOME/$CONFIG_FILE" \
cp -aL "$HOME/$CONFIG_FILE" "$HOME/$CONFIG_FILE.bak" && && cp -aL "$HOME/$CONFIG_FILE" "$HOME/$CONFIG_FILE.bak" \
echo -e "\033[0;32mYour original $CONFIG_FILE has been backed up to $CONFIG_FILE.bak\033[0m" && echo -e "\033[0;32mYour original $CONFIG_FILE has been backed up to $CONFIG_FILE.bak\033[0m"
} }
# Back up existing profile and create new one for bash-it # Back up existing profile and create new one for bash-it
@ -86,32 +84,37 @@ for param in "$@"; do
"--interactive") set -- "$@" "-i" ;; "--interactive") set -- "$@" "-i" ;;
"--no-modify-config") set -- "$@" "-n" ;; "--no-modify-config") set -- "$@" "-n" ;;
"--append-to-config") set -- "$@" "-a" ;; "--append-to-config") set -- "$@" "-a" ;;
*) set -- "$@" "$param" *) set -- "$@" "$param" ;;
esac esac
done done
OPTIND=1 OPTIND=1
while getopts "hsina" opt while getopts "hsina" opt; do
do
case "$opt" in case "$opt" in
"h") show_usage; exit 0 ;; "h")
show_usage
exit 0
;;
"s") silent=true ;; "s") silent=true ;;
"i") interactive=true ;; "i") interactive=true ;;
"n") no_modify_config=true ;; "n") no_modify_config=true ;;
"a") append_to_config=true ;; "a") append_to_config=true ;;
"?") show_usage >&2; exit 1 ;; "?")
show_usage >&2
exit 1
;;
esac esac
done done
shift $(expr $OPTIND - 1) shift $(("$OPTIND" - 1))
if [[ $silent ]] && [[ $interactive ]]; then if [[ $silent ]] && [[ $interactive ]]; then
echo -e "\033[91mOptions --silent and --interactive are mutually exclusive. Please choose one or the other.\033[m" echo -e "\033[91mOptions --silent and --interactive are mutually exclusive. Please choose one or the other.\033[m"
exit 1; exit 1
fi fi
if [[ $no_modify_config ]] && [[ $append_to_config ]]; then if [[ $no_modify_config ]] && [[ $append_to_config ]]; then
echo -e "\033[91mOptions --no-modify-config and --append-to-config are mutually exclusive. Please choose one or the other.\033[m" echo -e "\033[91mOptions --no-modify-config and --append-to-config are mutually exclusive. Please choose one or the other.\033[m"
exit 1; exit 1
fi fi
BASH_IT="$(cd "$(dirname "$0")" && pwd)" BASH_IT="$(cd "$(dirname "$0")" && pwd)"
@ -136,7 +139,7 @@ if ! [[ $silent ]] && ! [[ $no_modify_config ]]; then
[yY]) [yY])
break break
;; ;;
[nN]|"") [nN] | "")
echo -e "\033[91mInstallation aborted. Please come back soon!\033[m" echo -e "\033[91mInstallation aborted. Please come back soon!\033[m"
exit 1 exit 1
;; ;;
@ -154,7 +157,7 @@ if ! [[ $silent ]] && ! [[ $no_modify_config ]]; then
backup_append backup_append
break break
;; ;;
[nN]|"") [nN] | "")
backup_new backup_new
break break
;; ;;
@ -174,15 +177,16 @@ fi
# Disable auto-reload in case its enabled # Disable auto-reload in case its enabled
export BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE='' export BASH_IT_AUTOMATIC_RELOAD_AFTER_CONFIG_CHANGE=''
# Load dependencies for enabling components # Load dependencies for enabling components
source "$BASH_IT/lib/composure.bash" # shellcheck disable=SC1090
source "${BASH_IT}"/vendor/github.com/erichs/composure/composure.sh
# shellcheck source=./lib/utilities.bash
source "$BASH_IT/lib/utilities.bash" source "$BASH_IT/lib/utilities.bash"
cite _about _param _example _group _author _version cite _about _param _example _group _author _version
# shellcheck source=./lib/helpers.bash
source "$BASH_IT/lib/helpers.bash" source "$BASH_IT/lib/helpers.bash"
if [[ $interactive ]] && ! [[ $silent ]] ; if [[ $interactive ]] && ! [[ $silent ]]; then
then for type in "aliases" "plugins" "completion"; do
for type in "aliases" "plugins" "completion"
do
echo -e "\033[0;32mEnabling $type\033[0m" echo -e "\033[0;32mEnabling $type\033[0m"
load_some $type load_some $type
done done
@ -198,6 +202,7 @@ fi
echo "" echo ""
echo -e "\033[0;32mInstallation finished successfully! Enjoy bash-it!\033[0m" echo -e "\033[0;32mInstallation finished successfully! Enjoy bash-it!\033[0m"
# shellcheck disable=SC2086
echo -e "\033[0;32mTo start using it, open a new tab or 'source "$HOME/$CONFIG_FILE"'.\033[0m" echo -e "\033[0;32mTo start using it, open a new tab or 'source "$HOME/$CONFIG_FILE"'.\033[0m"
echo "" echo ""
echo "To show the available aliases/completions/plugins, type one of the following:" echo "To show the available aliases/completions/plugins, type one of the following:"

View File

@ -1,380 +0,0 @@
# composure - by erichs
# light-hearted functions for intuitive shell programming
# install: source this script in your ~/.profile or ~/.${SHELL}rc script
# latest source available at http://git.io/composure
# known to work on bash, zsh, and ksh93
# 'plumbing' functions
composure_keywords ()
{
echo "about author example group param version"
}
letterpress ()
{
typeset rightcol="$1" leftcol="${2:- }"
if [ -z "$rightcol" ]; then
return
fi
printf "%-20s%s\n" "$leftcol" "$rightcol"
}
transcribe ()
{
typeset func=$1
typeset file=$2
typeset operation="$3"
if git --version >/dev/null 2>&1; then
if [ -d ~/.composure ]; then
(
cd ~/.composure
if git rev-parse 2>/dev/null; then
if [ ! -f $file ]; then
printf "%s\n" "Oops! Couldn't find $file to version it for you..."
return
fi
cp $file ~/.composure/$func.inc
git add --all .
git commit -m "$operation $func"
fi
)
else
if [ "$USE_COMPOSURE_REPO" = "0" ]; then
return # if you say so...
fi
printf "%s\n" "I see you don't have a ~/.composure repo..."
typeset input
typeset valid=0
while [ $valid != 1 ]; do
printf "\n%s" 'would you like to create one? y/n: '
read input
case $input in
y|yes|Y|Yes|YES)
(
echo 'creating git repository for your functions...'
mkdir ~/.composure
cd ~/.composure
git init
echo "composure stores your function definitions here" > README.txt
git add README.txt
git commit -m 'initial commit'
)
# if at first you don't succeed...
transcribe "$func" "$file" "$operation"
valid=1
;;
n|no|N|No|NO)
printf "%s\n" "ok. add 'export USE_COMPOSURE_REPO=0' to your startup script to disable this message."
valid=1
;;
*)
printf "%s\n" "sorry, didn't get that..."
;;
esac
done
fi
fi
}
typeset_functions ()
{
# unfortunately, there does not seem to be a easy, portable way to list just the
# names of the defined shell functions...
# first, determine our shell:
typeset shell
if [ -n "$SHELL" ]; then
shell=$(basename $SHELL) # we assume this is set correctly!
else
# we'll have to try harder
# here's a hack I modified from a StackOverflow post:
# we loop over the ps listing for the current process ($$), and print the last column (CMD)
# stripping any leading hyphens bash sometimes throws in there
typeset x ans
typeset this=$(for x in $(ps -p $$); do ans=$x; done; printf "%s\n" $ans | sed 's/^-*//')
typeset shell=$(basename $this) # e.g. /bin/bash => bash
fi
case "$shell" in
bash)
typeset -F | awk '{print $3}'
;;
*)
# trim everything following '()' in ksh
typeset +f | sed 's/().*$//'
;;
esac
}
# bootstrap metadata keywords for porcelain functions
for f in $(composure_keywords)
do
eval "$f() { :; }"
done
unset f
# 'porcelain' functions
cite ()
{
about creates one or more meta keywords for use in your functions
param one or more keywords
example '$ cite url username'
example '$ url http://somewhere.com'
example '$ username alice'
group composure
# this is the storage half of the 'metadata' system:
# we create dynamic metadata keywords with function wrappers around
# the NOP command, ':'
# anything following a keyword will get parsed as a positional
# parameter, but stay resident in the ENV. As opposed to shell
# comments, '#', which do not get parsed and are not available
# at runtime.
# a BIG caveat--your metadata must be roughly parsable: do not use
# contractions, and consider single or double quoting if it contains
# non-alphanumeric characters
if [ -z "$1" ]; then
printf '%s\n' 'missing parameter(s)'
reference cite
return
fi
typeset keyword
for keyword in $*; do
eval "$keyword() { :; }"
done
}
draft ()
{
about wraps command from history into a new function, default is last command
param 1: name to give function
param 2: optional history line number
example '$ ls'
example '$ draft list'
example '$ draft newfunc 1120 # wraps command at history line 1120 in newfunc()'
group composure
typeset func=$1
typeset num=$2
typeset cmd
if [ -z "$func" ]; then
printf '%s\n' 'missing parameter(s)'
reference draft
return
fi
# aliases bind tighter than function names, disallow them
if [ -n "$(LANG=C type -t $func 2>/dev/null | grep 'alias')" ]; then
printf '%s\n' "sorry, $(type -a $func). please choose another name."
return
fi
if [ -z "$num" ]; then
# parse last command from fc output
# some versions of 'fix command, fc' need corrective lenses...
typeset myopic=$(fc -ln -1 | grep draft)
typeset lines=1
if [ -n "$myopic" ]; then
lines=2
fi
cmd=$(fc -ln -$lines | head -1 | sed 's/^[[:blank:]]*//')
else
# parse command from history line number
cmd=$(eval "history | grep '^[[:blank:]]*$num' | head -1" | sed 's/^[[:blank:][:digit:]]*//')
fi
eval "$func() { $cmd; }"
typeset file=$(mktemp -t draft.XXXX)
typeset -f $func > $file
transcribe $func $file draft
rm $file 2>/dev/null
}
glossary ()
{
about displays help summary for all functions, or summary for a group of functions
param 1: optional, group name
example '$ glossary'
example '$ glossary misc'
group composure
typeset targetgroup=${1:-}
for func in $(typeset_functions); do
if [ -n "$targetgroup" ]; then
typeset group="$(typeset -f $func | metafor group)"
if [ "$group" != "$targetgroup" ]; then
continue # skip non-matching groups, if specified
fi
fi
typeset about="$(typeset -f $func | metafor about)"
letterpress "$about" $func
done
}
metafor ()
{
about prints function metadata associated with keyword
param 1: meta keyword
example '$ typeset -f glossary | metafor example'
group composure
typeset keyword=$1
if [ -z "$keyword" ]; then
printf '%s\n' 'missing parameter(s)'
reference metafor
return
fi
# this sed-fu is the retrieval half of the 'metadata' system:
# 'grep' for the metadata keyword, and then parse/filter the matching line
# grep keyword # strip trailing '|"|; # ignore thru keyword and leading '|"
sed -n "/$keyword / s/['\";]*$//;s/^[ ]*$keyword ['\"]*\([^([].*\)*$/\1/p"
}
reference ()
{
about displays apidoc help for a specific function
param 1: function name
example '$ reference revise'
group composure
typeset func=$1
if [ -z "$func" ]; then
printf '%s\n' 'missing parameter(s)'
reference reference
return
fi
typeset line
typeset about="$(typeset -f $func | metafor about)"
letterpress "$about" $func
typeset author="$(typeset -f $func | metafor author)"
if [ -n "$author" ]; then
letterpress "$author" 'author:'
fi
typeset version="$(typeset -f $func | metafor version)"
if [ -n "$version" ]; then
letterpress "$version" 'version:'
fi
if [ -n "$(typeset -f $func | metafor param)" ]; then
printf "parameters:\n"
typeset -f $func | metafor param | while read line
do
letterpress "$line"
done
fi
if [ -n "$(typeset -f $func | metafor example)" ]; then
printf "examples:\n"
typeset -f $func | metafor example | while read line
do
letterpress "$line"
done
fi
}
revise ()
{
about loads function into editor for revision
param 1: name of function
example '$ revise myfunction'
group composure
typeset func=$1
typeset temp=$(mktemp -t revise.XXXX)
if [ -z "$func" ]; then
printf '%s\n' 'missing parameter(s)'
reference revise
return
fi
# populate tempfile...
if [ -f ~/.composure/$func.inc ]; then
# ...with contents of latest git revision...
cat ~/.composure/$func.inc >> $temp
else
# ...or from ENV if not previously versioned
typeset -f $func >> $temp
fi
if [ -z "$EDITOR" ]
then
typeset EDITOR=vi
fi
$EDITOR $temp
. $temp # source edited file
transcribe $func $temp revise
rm $temp
}
write ()
{
about writes one or more composed function definitions to stdout
param one or more function names
example '$ write finddown foo'
example '$ write finddown'
group composure
if [ -z "$1" ]; then
printf '%s\n' 'missing parameter(s)'
reference write
return
fi
# bootstrap metadata
cat <<END
for f in $(composure_keywords)
do
eval "\$f() { :; }"
done
unset f
END
# include cite() to enable custom keywords
typeset -f cite $*
}
: <<EOF
License: The MIT License
Copyright © 2012 Erich Smith
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
EOF

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
function local_setup { function local_setup {
setup_test_fixture setup_test_fixture

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../completion/available/bash-it.completion load ../../completion/available/bash-it.completion
function local_setup { function local_setup {

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
# Determine which config file to use based on OS. # Determine which config file to use based on OS.
case $OSTYPE in case $OSTYPE in

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
# Determine which config file to use based on OS. # Determine which config file to use based on OS.
case $OSTYPE in case $OSTYPE in

View File

@ -1,9 +1,9 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
@test "lib composure: composure_keywords()" { @test "lib composure: _composure_keywords()" {
run composure_keywords run _composure_keywords
assert_output "about author example group param version" assert_output "about author example group param version"
} }

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/log load ../../lib/log
load ../../lib/utilities load ../../lib/utilities
load ../../lib/search load ../../lib/search

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/appearance load ../../lib/appearance
load ../../plugins/available/base.plugin load ../../plugins/available/base.plugin

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/log load ../../lib/log
load ../../lib/helpers load ../../lib/helpers
load ../../lib/utilities load ../../lib/utilities

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/helpers load ../../lib/helpers
load ../../lib/utilities load ../../lib/utilities
load ../../lib/search load ../../lib/search

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/log load ../../lib/log
load ../../lib/helpers load ../../lib/helpers

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../plugins/available/base.plugin load ../../plugins/available/base.plugin
@test 'plugins base: ips()' { @test 'plugins base: ips()' {

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
cite _about _param _example _group _author _version cite _about _param _example _group _author _version

View File

@ -2,7 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/helpers load ../../lib/helpers
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../plugins/available/cmd-returned-notify.plugin load ../../plugins/available/cmd-returned-notify.plugin

View File

@ -2,7 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/helpers load ../../lib/helpers
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
@test 'ensure _go_pathmunge_wrap is defined' { @test 'ensure _go_pathmunge_wrap is defined' {
{ [[ $CI ]] || _command_exists go; } || skip 'golang not found' { [[ $CI ]] || _command_exists go; } || skip 'golang not found'

View File

@ -2,7 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/helpers load ../../lib/helpers
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../plugins/available/ruby.plugin load ../../plugins/available/ruby.plugin
function local_setup { function local_setup {

View File

@ -2,7 +2,7 @@
load ../test_helper load ../test_helper
load ../../lib/helpers load ../../lib/helpers
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../plugins/available/xterm.plugin load ../../plugins/available/xterm.plugin

View File

@ -1,5 +1,5 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
unset BASH_IT_THEME unset BASH_IT_THEME
unset GIT_HOSTING unset GIT_HOSTING
@ -39,8 +39,7 @@ setup_test_fixture() {
lib_directory="$(cd "$(dirname "$0")" && pwd)" lib_directory="$(cd "$(dirname "$0")" && pwd)"
local src_topdir="$lib_directory/../../../.." local src_topdir="$lib_directory/../../../.."
if command -v rsync &> /dev/null if command -v rsync &> /dev/null; then
then
# Use rsync to copy Bash-it to the temp folder # Use rsync to copy Bash-it to the temp folder
rsync -qavrKL -d --delete-excluded --exclude=.git --exclude=enabled "$src_topdir" "$BASH_IT" rsync -qavrKL -d --delete-excluded --exclude=.git --exclude=enabled "$src_topdir" "$BASH_IT"
else else

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/log load ../../lib/log
cite _about _param _example _group _author _version cite _about _param _example _group _author _version

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/log load ../../lib/log
cite _about _param _example _group _author _version cite _about _param _example _group _author _version

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bats #!/usr/bin/env bats
load ../test_helper load ../test_helper
load ../../lib/composure load "${BASH_IT}/vendor/github.com/erichs/composure/composure.sh"
load ../../lib/log load ../../lib/log
cite _about _param _example _group _author _version cite _about _param _example _group _author _version

2
vendor/.gitattributes vendored 100644
View File

@ -0,0 +1,2 @@
* -whitespace
init.d/*.bash text eol=lf

1
vendor/github.com/erichs/composure/.gitignore generated vendored 100644
View File

@ -0,0 +1 @@
composure_test/**

View File

@ -0,0 +1,9 @@
language: c
script: make tests
branches:
only:
- testing
- master
before_install:
- sudo apt-get update -qq
- sudo apt-get install -qq ksh zsh

90
vendor/github.com/erichs/composure/History.md generated vendored 100644
View File

@ -0,0 +1,90 @@
1.3 / 2015-11-04
==================
* Make glossary() faster by not introspecting loaded shell functions
* Remove brittle and incomplete test suite
* Fixes for shellcheck.net
1.2.4 / 2015-08-29
==================
* Minor updates for latest shellcheck.net codes
* Fix write() function, thanks @IsoLinearCHiP!
1.2.3 / 2015-04-01
==================
* Minor fixes for latest shellcheck.net codes
* Better wrapping for long about metadata
* Support leading hyphens in function names
1.2.2 / 2015-01-16
==================
various fixes, including contributions from:
* @nilbus
* @martinlauer
* @DrVanScott
1.2.1 / 2014-01-05
==================
* Tab completion for revise(), new compost() func
* Improve shell determination and bootstrapping sequence
1.2.0 / 2013-11-17
==================
* Auto-load composed functions
1.1.1 / 2013-10-29
==================
* Fix issue with zsh noclobber option
1.1.0 / 2013-10-23
==================
* Auto-revise drafted functions
* Populate author metadata on draft
* Use tpope-style commit msgs
* Respect XDG_DATA_HOME
1.0.4 / 2013-08-30
==================
* increase letterpress spacing
* refactor composure extras
1.0.3 / 2012-11-29
==================
* make revise() smarter
* write() includes shebang and main() invocation
1.0.2 / 2012-05-24
==================
* use _plumbing nomenclature
1.0.1 / 2012-05-19
==================
* revise() takes an optional -e flag
* revise() aborts on an empty file
* metadata cleaned up
1.0 / 2012-05-17
==================
* performance improvements
* fix draft(): ensure alias names are not used for function names
* porcelain is self-referential
* consolidate plumbing fns
* add diagram
* write() porcelain
* apidoc for author & version
* second-order functions
* asciicast demo!
* prompt for git repo creation
* full POSIX compatibility
* revised documentation
* sed-fu rescues case blocks - solves #1
* basic git tracking
* remove hyphens from function names
* fix for non-interactive shells
* respect EDITOR preference
* add readme
* initial commit

10
vendor/github.com/erichs/composure/Makefile generated vendored 100644
View File

@ -0,0 +1,10 @@
TARGET = tests
all: $(TARGET)
tests:
cd test && make tests
clean::
rm -f test/*~ test/t/*~
rm -rf test/composure_test

240
vendor/github.com/erichs/composure/README.md generated vendored 100644
View File

@ -0,0 +1,240 @@
e88~~\ e88~-_ 888-~88e-~88e 888-~88e e88~-_ d88~\ 888 888 888-~\ e88~~8e
d888 d888 i 888 888 888 888 888b d888 i C888 888 888 888 d888 88b
8888 8888 | 888 888 888 888 8888 8888 | Y88b 888 888 888 8888__888
Y888 Y888 ' 888 888 888 888 888P Y888 ' 888D 888 888 888 Y888 ,
"88__/ "88_-~ 888 888 888 888-_88" "88_-~ \_88P "88_-888 888 "88___/
888
# Composure: don't fear the Unix chainsaw
These light-hearted functions make programming the shell easier and
more intuitive:
* Transition organically from command, to function, to script
* Use an unobtrusive help system with arbitrary shell metadata
* Automatically version and store your shell functions with Git
static analysis and automated tests: [![Build Status](https://travis-ci.org/erichs/composure.png?branch=master)](https://travis-ci.org/erichs/composure)
## Demo!
[Composing a simple network monitoring script](http://asciinema.org/a/476) (4 minutes)
## Compatibility
Composure is POSIX-compliant, and is known to work on ksh93, zsh, and
bash, on osx and linux.
Please feel free to open an issue if you have any difficulties on your system.
## Installing
Put composure.sh where you'd like it to live and source it from your
shell's profile or rc file.
On Bash:
```bash
cd /your/favorite/directory
curl -L http://git.io/composure > composure.sh
chmod +x composure.sh
echo "source $(pwd)/composure.sh" >> ~/.bashrc # or, ~/.bash_profile on osx
```
Users upgrading from a version prior to 1.1.0 need to execute the following commands, as the directory for composure's local repo has changed:
```bash
mkdir ~/.local 2>/dev/null
mv ~/.composure ~/.local/composure
```
## Craft - Draft - Revise - Write
<img src="http://yuml.me/47fcf7e2" />
### Crafting the command line
[REPL environments](http://repl.it) are great for trying out programming ideas
and crafting snippets of working code, aren't they? Composure helps you make
better use of the REPL environment constantly at your fingertips: the shell.
Many Unix users I know like to iteratively build up complex commands by trying
something out, hitting the up arrow and perhaps adding a filter with a pipe:
```bash
$ cat servers.txt
bashful: up
doc: down
up-arrow
$ cat servers.txt | grep down
doc: down
up-arrow
$ cat servers.txt | grep down | mail -s "down server(s)" admin@here.com
```
Composure helps by letting you quickly draft simple shell functions, breaking down
your long pipe filters and complex commands into readable and reusable chunks.
### Draft first, ask questions later
Once you've crafted your gem of a command, don't throw it away! Use 'draft ()'
and give it a [good name](http://martinfowler.com/bliki/TwoHardThings.html).
This stores your last command as a function you can reuse later. Think of it
like a rough draft.
```bash
$ cat servers.txt
bashful: up
doc: down
up-arrow
$ cat servers.txt | grep down
doc: down
$ draft finddown
$ finddown | mail -s "down server(s)" admin@here.com
```
### Revise, revise, revise!
Now that you've got a minimal shell function, you may want to make it better
through refactoring and revision. Use the 'revise ()' command to revise your
shell function in your favorite editor.
* generalize functions with input parameters
* add or remove functionality
* add supporting metadata for documentation
```bash
$ revise finddown
finddown ()
{
about finds servers marked 'down' in text file
group admin
cat $1 | grep down
}
$ finddown servers.txt
doc: down
```
### Get it in Writing
When it is time to put your function or functions to use in a shell script, just call write:
```bash
$ write finddown > finddown.sh
```
Edit the main() function, chmod +x, and you're ready to go!
## Arbitrary shell metadata!
Composure uses a simple system of dynamic keywords that allow you to add
metadata to your functions. Just call 'cite ()' to initialize your new
keyword(s), and use them freely in your functions:
```bash
foo()
{
cite about
about perform mad script-foo
echo 'foo'
}
```
Retrieve your metadata later by calling 'metafor ()':
```bash
typeset -f foo | metafor about # displays:
perform mad script-foo
```
By default, composure knows the keywords: about, param, group, author, and example.
These default keywords are used by the help system:
## Intuitive help system
The 'glossary ()' function will automatically summarize all functions with
'about' metadata. If called with a 'group' name as a parameter, it will
summarize functions belonging to that group.
To display apidoc-style help for a function, use 'reference ()'.
```bash
$ glossary # displays:
cite creates a new meta keyword for use in your functions
draft wraps last command into a new function
finddown finds servers marked 'down' in text file
foo perform mad script-foo
glossary displays help summary for all functions, or summary for a group of functions
metafor prints function metadata associated with keyword
reference displays apidoc help for a specific function
revise loads function into editor for revision
write writes one or more composed function definitions to stdout
meanwhile
$ glossary admin # displays:
finddown finds servers marked 'down' in text file
and
$ reference draft # displays:
draft wraps last command into a new function
parameters:
1: name to give function
examples:
$ ls
$ draft list
$ list
```
## Git integration
If you already use git, installing composure will initialize a ~/.local/composure
repository, and store and version your functions there. Just use 'draft ()' and
'revise ()', they automatically version for you.
Composure supports the [XDG Base Directory](http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html)
specification, and will respect your local XDG_DATA_HOME environment variable.
Why do this?
* the latest version of any function you've composed may always be sourced from
your composure repo
* never throw away code--keep your one-off functions in your composure 'junk
drawer', and grep through it later for long-forgotten gems
* every version of every function you write is always
available to you via basic git commands
## Persistent access
Draft or revise a function, and the latest version is automatically sourced into your current shell environment. By default, composure automatically sources all of your composed functions when you source the composure.sh script. If you are concerned about shell startup time, have many hundreds of versioned shell functions, or otherwise want to control which functions are loaded from your composure repository, you may disable the default behavior by adding the following line to your shell's startup script:
```shell
export LOAD_COMPOSED_FUNCTIONS=0
```
# Credits
Composure grew out of ideas taken from from Gary Bernhardt's hilarious talk [The Unix
Chainsaw](http://www.confreaks.com/videos/615-cascadiaruby2011-the-unix-chainsaw) (31 minutes),
which refers to the Elements of Programming described in MIT's [SICP
text](http://mitpress.mit.edu/sicp/full-text/book/book.html):
* primitive expressions
* means of combination
* means of abstraction
## Known Issues
'glossary ()' and 'reference ()' do not support nested functions with metadata.

145
vendor/github.com/erichs/composure/c_extras.sh generated vendored 100644
View File

@ -0,0 +1,145 @@
#!/bin/bash
_basename_no_extension () {
sed -e 's/^.*\/\(.*\)\.inc$/\1/'
}
_composure_functions () {
_list_composure_files | _basename_no_extension
}
_load_tab_completions () {
# support tab completion for 'revise' command
# you may disable this by adding the following line to your shell startup:
# export COMPOSURE_TAB_COMPLETION=0
if [ "$COMPOSURE_TAB_COMPLETION" = "0" ]; then
return # if you say so...
fi
case "$(_shell)" in
zsh)
read -r -d '' SCRIPT <<ZSHDATA
_zsh_revise_complete () {
typeset word completions
word="\$1"
completions="\$(_composure_functions)"
reply=( "\${(ps:\n:)completions}" )
}
compctl -K _zsh_revise_complete revise
ZSHDATA
eval "$SCRIPT"
unset SCRIPT
;;
bash)
read -r -d '' SCRIPT <<BASHDATA
_bash_revise_complete () {
typeset cur
cur=\${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( \$(compgen -W "\$(_composure_functions)" -- \$cur) )
return 0
}
complete -F _bash_revise_complete revise
BASHDATA
eval "$SCRIPT"
unset SCRIPT
;;
*)
echo "composure tab completions unavailable"
;;
esac
}
# Second-order functions for composure
findgroup ()
{
about 'finds all functions belonging to group'
param '1: name of group'
example '$ findgroup tools'
group 'composure'
typeset func
for func in $(_typeset_functions)
do
typeset group="$(typeset -f $func | metafor group)"
if [ "$group" = "$1" ]; then
echo "$func"
fi
done
}
overview ()
{
about 'gives overview of available shell functions, by group'
group 'composure'
# display a brief progress message...
printf '%s' 'building documentation...'
typeset grouplist=$(mktemp /tmp/grouplist.XXXX);
typeset func;
for func in $(_typeset_functions);
do
typeset group="$(typeset -f $func | metafor group)";
if [ -z "$group" ]; then
group='misc';
fi;
typeset about="$(typeset -f $func | metafor about)";
_letterpress "$about" $func >> $grouplist.$group;
echo $grouplist.$group >> $grouplist;
done;
# clear progress message
printf '\r%s\n' ' '
typeset group;
typeset gfile;
for gfile in $(cat $grouplist | sort | uniq);
do
printf '%s\n' "${gfile##*.}:";
cat $gfile;
printf '\n';
command rm $gfile 2> /dev/null;
done | less
command rm $grouplist 2> /dev/null
}
recompose ()
{
about 'loads a stored function from ~/.composure repo'
param '1: name of function'
example '$ load myfunc'
group 'composure'
. $(_get_composure_dir)/$1.inc
}
unique_metafor ()
{
about 'displays all unique metadata for a given keyword'
param '1: keyword'
example '$ unique_metafor group'
group 'composure'
typeset keyword=$1
typeset file=$(mktemp /tmp/composure.XXXX)
typeset -f | metafor $keyword >> $file
cat $file | sort | uniq
command rm $file 2>/dev/null
}
compost () {
about 'delete function stored in composure repo'
param '1: name of function'
example '$ compost myfunc'
group 'composure'
typeset func=$1
[ -z "$func" ] && echo "you must specify a function name!" && return 1
(
cd $(_get_composure_dir)
git rm "$func.inc" && git commit -m "Delete function $func"
)
}
_load_tab_completions

549
vendor/github.com/erichs/composure/composure.sh generated vendored 100755
View File

@ -0,0 +1,549 @@
#!/bin/bash
# composure - by erichs
# light-hearted functions for intuitive shell programming
# version: 1.3.1
# latest source available at http://git.io/composure
# install: source this script in your ~/.profile or ~/.${SHELL}rc script
# known to work on bash, zsh, and ksh93
# 'plumbing' functions
_bootstrap_composure() {
_generate_metadata_functions
_load_composed_functions
_determine_printf_cmd
}
_get_composure_dir ()
{
if [ -n "$XDG_DATA_HOME" ]; then
echo "$XDG_DATA_HOME/composure"
else
echo "$HOME/.local/composure"
fi
}
_get_author_name ()
{
typeset name localname
localname="$(git --git-dir "$(_get_composure_dir)/.git" config --get user.name)"
for name in "$GIT_AUTHOR_NAME" "$localname"; do
if [ -n "$name" ]; then
echo "$name"
break
fi
done
}
_composure_keywords ()
{
echo "about author example group param version"
}
_letterpress ()
{
typeset rightcol="$1" leftcol="${2:- }" leftwidth="${3:-20}"
if [ -z "$rightcol" ]; then
return
fi
$_printf_cmd "%-*s%s\n" "$leftwidth" "$leftcol" "$rightcol"
}
_determine_printf_cmd() {
if [ -z "$_printf_cmd" ]; then
_printf_cmd=printf
# prefer GNU gprintf if available
[ -x "$(which gprintf)" ] && _printf_cmd=gprintf
export _printf_cmd
fi
}
_longest_function_name_length ()
{
_typeset_functions | awk 'BEGIN{ maxlength=0 }
{
for(i=1;i<=NF;i++)
if (length($i)>maxlength)
{
maxlength=length($i)
}
}
END{ print maxlength}'
}
_temp_filename_for ()
{
typeset file=$(mktemp "/tmp/$1.XXXX")
command rm "$file" 2>/dev/null # ensure file is unlinked prior to use
echo "$file"
}
_prompt ()
{
typeset prompt="$1"
typeset result
case "$(_shell)" in
bash)
read -r -e -p "$prompt" result;;
*)
echo -n "$prompt" >&2; read -r result;;
esac
echo "$result"
}
_add_composure_file ()
{
typeset func="$1"
typeset file="$2"
typeset operation="$3"
typeset comment="${4:-}"
typeset composure_dir=$(_get_composure_dir)
(
if ! cd "$composure_dir"; then
printf "%s\n" "Oops! Can't find $composure_dir!"
return
fi
if git rev-parse 2>/dev/null; then
if [ ! -f "$file" ]; then
printf "%s\n" "Oops! Couldn't find $file to version it for you..."
return
fi
cp "$file" "$composure_dir/$func.inc"
git add --all .
if [ -z "$comment" ]; then
comment="$(_prompt 'Git Comment: ')"
fi
git commit -m "$operation $func: $comment"
fi
)
}
_transcribe ()
{
typeset func="$1"
typeset file="$2"
typeset operation="$3"
typeset comment="${4:-}"
typeset composure_dir=$(_get_composure_dir)
if git --version >/dev/null 2>&1; then
if [ -d "$composure_dir" ]; then
_add_composure_file "$func" "$file" "$operation" "$comment"
else
if [ "$USE_COMPOSURE_REPO" = "0" ]; then
return # if you say so...
fi
printf "%s\n" "I see you don't have a $composure_dir repo..."
typeset input=''
typeset valid=0
while [ $valid != 1 ]; do
printf "\n%s" 'would you like to create one? y/n: '
read -r input
case $input in
y|yes|Y|Yes|YES)
(
echo 'creating git repository for your functions...'
mkdir -p "$composure_dir" || return 1
cd "$composure_dir" || return 1
git init
echo "composure stores your function definitions here" > README.txt
git add README.txt
git commit -m 'initial commit'
)
# if at first you don't succeed...
_transcribe "$func" "$file" "$operation" "$comment"
valid=1
;;
n|no|N|No|NO)
printf "%s\n" "ok. add 'export USE_COMPOSURE_REPO=0' to your startup script to disable this message."
valid=1
;;
*)
printf "%s\n" "sorry, didn't get that..."
;;
esac
done
fi
fi
}
_typeset_functions ()
{
typeset f
for f in "$(_get_composure_dir)"/*.inc; do
# Without nullglob, we'll get back the glob
[[ -f "$f" ]] || continue
f="${f##*/}"
f="${f%.inc}"
echo "$f"
done | cat - <(echo "cite\ndraft\nglossary\nmetafor\nreference\nrevise\nwrite") | sort | uniq
}
_shell () {
# here's a hack I modified from a StackOverflow post:
# get the ps listing for the current process ($$), and print the last column (CMD)
# stripping any leading hyphens shells sometimes throw in there
typeset this=$(ps -p $$ | tail -1 | awk '{print $4}' | sed 's/^-*//')
echo "${this##*/}" # e.g. /bin/bash => bash
}
_generate_metadata_functions() {
typeset f
for f in $(_composure_keywords)
do
eval "$f() { :; }"
done
}
_list_composure_files () {
typeset composure_dir="$(_get_composure_dir)"
[ -d "$composure_dir" ] && find "$composure_dir" -maxdepth 1 -name '*.inc'
}
_load_composed_functions () {
# load previously composed functions into shell
# you may disable this by adding the following line to your shell startup:
# export LOAD_COMPOSED_FUNCTIONS=0
if [ "$LOAD_COMPOSED_FUNCTIONS" = "0" ]; then
return # if you say so...
fi
typeset inc
for inc in $(_list_composure_files); do
# shellcheck source=/dev/null
. "$inc"
done
}
_strip_trailing_whitespace () {
sed -e 's/ \+$//'
}
_strip_semicolons () {
sed -e 's/;$//'
}
# 'porcelain' functions
cite ()
{
about 'creates one or more meta keywords for use in your functions'
param 'one or more keywords'
example '$ cite url username'
example '$ url http://somewhere.com'
example '$ username alice'
group 'composure'
# this is the storage half of the 'metadata' system:
# we create dynamic metadata keywords with function wrappers around
# the NOP command, ':'
# anything following a keyword will get parsed as a positional
# parameter, but stay resident in the ENV. As opposed to shell
# comments, '#', which do not get parsed and are not available
# at runtime.
# a BIG caveat--your metadata must be roughly parsable: do not use
# contractions, and consider single or double quoting if it contains
# non-alphanumeric characters
if [ -z "$1" ]; then
printf '%s\n' 'missing parameter(s)'
reference cite
return
fi
typeset keyword
for keyword in "$@"; do
eval "$keyword() { :; }"
done
}
draft ()
{
about 'wraps command from history into a new function, default is last command'
param '1: name to give function'
param '2: optional history line number'
example '$ ls'
example '$ draft list'
example '$ draft newfunc 1120 # wraps command at history line 1120 in newfunc()'
group 'composure'
typeset func=$1
typeset num=$2
if [ -z "$func" ]; then
printf '%s\n' 'missing parameter(s)'
reference draft
return
fi
# aliases bind tighter than function names, disallow them
if type -a "$func" 2>/dev/null | grep -q 'is.*alias'; then
printf '%s\n' "sorry, $(type -a "$func"). please choose another name."
return
fi
typeset cmd
if [ -z "$num" ]; then
# some versions of 'fix command, fc' need corrective lenses...
typeset lines=$(fc -ln -1 | grep -q draft && echo 2 || echo 1)
# parse last command from fc output
# shellcheck disable=SC2086
cmd=$(fc -ln -$lines | head -1 | sed 's/^[[:blank:]]*//')
else
# parse command from history line number
cmd=$(eval "history | grep '^[[:blank:]]*$num' | head -1" | sed 's/^[[:blank:][:digit:]]*//')
fi
eval "function $func {
author '$(_get_author_name)'
about ''
param ''
example ''
group ''
$cmd;
}"
typeset file=$(_temp_filename_for draft)
typeset -f "$func" | _strip_trailing_whitespace | _strip_semicolons > "$file"
_transcribe "$func" "$file" Draft "Initial draft"
command rm "$file" 2>/dev/null
revise "$func"
}
glossary ()
{
about 'displays help summary for all functions, or summary for a group of functions'
param '1: optional, group name'
example '$ glossary'
example '$ glossary misc'
group 'composure'
typeset targetgroup=${1:-}
typeset maxwidth=$(_longest_function_name_length | awk '{print $1 + 5}')
for func in $(_typeset_functions); do
if [ "X${targetgroup}X" != "XX" ]; then
typeset group="$(typeset -f -- $func | metafor group)"
if [ "$group" != "$targetgroup" ]; then
continue # skip non-matching groups, if specified
fi
fi
typeset about="$(typeset -f -- $func | metafor about)"
typeset aboutline=
echo "$about" | fmt | while read -r aboutline; do
_letterpress "$aboutline" "$func" "$maxwidth"
func=" " # only display function name once
done
done
}
metafor ()
{
about 'prints function metadata associated with keyword'
param '1: meta keyword'
example '$ typeset -f glossary | metafor example'
group 'composure'
typeset keyword=$1
if [ -z "$keyword" ]; then
printf '%s\n' 'missing parameter(s)'
reference metafor
return
fi
# this sed-fu is the retrieval half of the 'metadata' system:
# 'grep' for the metadata keyword, and then parse/filter the matching line
# grep keyword # strip trailing '|"|; # ignore thru keyword and leading '|"
sed -n "/$keyword / s/['\";]*\$//;s/^[ ]*$keyword ['\"]*\([^([].*\)*\$/\1/p"
}
reference ()
{
about 'displays apidoc help for a specific function'
param '1: function name'
example '$ reference revise'
group 'composure'
typeset func=$1
if [ -z "$func" ]; then
printf '%s\n' 'missing parameter(s)'
reference reference
return
fi
typeset line
typeset about="$(typeset -f "$func" | metafor about)"
_letterpress "$about" "$func"
typeset author="$(typeset -f $func | metafor author)"
if [ -n "$author" ]; then
_letterpress "$author" 'author:'
fi
typeset version="$(typeset -f $func | metafor version)"
if [ -n "$version" ]; then
_letterpress "$version" 'version:'
fi
if [ -n "$(typeset -f $func | metafor param)" ]; then
printf "parameters:\n"
typeset -f $func | metafor param | while read -r line
do
_letterpress "$line"
done
fi
if [ -n "$(typeset -f $func | metafor example)" ]; then
printf "examples:\n"
typeset -f $func | metafor example | while read -r line
do
_letterpress "$line"
done
fi
}
revise ()
{
about 'loads function into editor for revision'
param '<optional> -e: revise version stored in ENV'
param '1: name of function'
example '$ revise myfunction'
example '$ revise -e myfunction'
example 'save a zero-length file to abort revision'
group 'composure'
typeset source='git'
if [ "$1" = '-e' ]; then
source='env'
shift
fi
typeset func=$1
if [ -z "$func" ]; then
printf '%s\n' 'missing parameter(s)'
reference revise
return
fi
typeset composure_dir=$(_get_composure_dir)
typeset temp=$(_temp_filename_for revise)
# populate tempfile...
if [ "$source" = 'env' ] || [ ! -f "$composure_dir/$func.inc" ]; then
# ...with ENV if specified or not previously versioned
typeset -f $func > $temp
else
# ...or with contents of latest git revision
cat "$composure_dir/$func.inc" > "$temp"
fi
if [ -z "$EDITOR" ]
then
typeset EDITOR=vi
fi
$EDITOR "$temp"
if [ -s "$temp" ]; then
typeset edit='N'
# source edited file
# shellcheck source=/dev/null
. "$temp" || edit='Y'
while [ $edit = 'Y' ]; do
echo -n "Re-edit? Y/N: "
read -r edit
case $edit in
y|yes|Y|Yes|YES)
edit='Y'
$EDITOR "$temp"
# shellcheck source=/dev/null
. "$temp" && edit='N';;
*)
edit='N';;
esac
done
_transcribe "$func" "$temp" Revise
else
# zero-length files abort revision
printf '%s\n' 'zero-length file, revision aborted!'
fi
command rm "$temp"
}
write ()
{
about 'writes one or more composed function definitions to stdout'
param 'one or more function names'
example '$ write finddown foo'
example '$ write finddown'
group 'composure'
if [ -z "$1" ]; then
printf '%s\n' 'missing parameter(s)'
reference write
return
fi
echo "#!/usr/bin/env ${SHELL##*/}"
# bootstrap metadata
cat <<END
for f in $(_composure_keywords)
do
eval "\$f() { :; }"
done
unset f
END
# write out function definitons
# shellcheck disable=SC2034
typeset -f cite "$@"
cat <<END
main() {
echo "edit me to do something useful!"
exit 0
}
main \$*
END
}
_bootstrap_composure
: <<EOF
License: The MIT License
Copyright © 2012, 2013 Erich Smith
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
EOF

View File

@ -0,0 +1,18 @@
TARGET = tests
all: $(TARGET)
runtests:
./runtests.sh
runshellcheck:
./runshellcheck.sh
tests:
./wvtestrun $(MAKE) runshellcheck
clean::
rm -f *~ t/*~
rm -rf composure_test

View File

@ -0,0 +1,31 @@
#!/usr/bin/env sh
# run code quality metrics
echo "Testing \"code quality\" with shellcheck.net in ../composure.sh:"
datafile=shellcheck.raw
metricfile=shellcheck.out
curl -s --data-urlencode script="$(cat ../composure.sh)" \
www.shellcheck.net/shellcheck.php > $datafile
cat $datafile | python -mjson.tool > $metricfile
rm $datafile
cat $metricfile
# check for shellcheck.net errors
cat $metricfile | grep -q error
if [ $? -eq 0 ]; then
echo "! shellcheck.net:../composure.sh:0 [ errors ] FAILED"
rm $metricfile
exit 2
fi
# check for shellcheck.net warnings
cat $metricfile | grep -q warning
if [ $? -eq 0 ]; then
echo "! shellcheck.net:../composure.sh:0 [ warnings ] FAILED"
rm $metricfile
exit 2
fi
echo "! shellcheck.net:../composure.sh:0 [ no errors or warnings ] ok"
rm $metricfile

View File

@ -0,0 +1,189 @@
#!/usr/bin/perl -w
#
# WvTest:
# Copyright (C)2007-2012 Versabanq Innovations Inc. and contributors.
# Licensed under the GNU Library General Public License, version 2.
# See the included file named LICENSE for license information.
# You can get wvtest from: http://github.com/apenwarr/wvtest
#
use strict;
use Time::HiRes qw(time);
# always flush
$| = 1;
if (@ARGV < 1) {
print STDERR "Usage: $0 <command line...>\n";
exit 127;
}
print STDERR "Testing \"all\" in @ARGV:\n";
my $pid = open(my $fh, "-|");
if (!$pid) {
# child
setpgrp();
open STDERR, '>&STDOUT' or die("Can't dup stdout: $!\n");
exec(@ARGV);
exit 126; # just in case
}
my $istty = -t STDOUT && $ENV{'TERM'} ne "dumb";
my @log = ();
my ($gpasses, $gfails) = (0,0);
sub bigkill($)
{
my $pid = shift;
if (@log) {
print "\n" . join("\n", @log) . "\n";
}
print STDERR "\n! Killed by signal FAILED\n";
($pid > 0) || die("pid is '$pid'?!\n");
local $SIG{CHLD} = sub { }; # this will wake us from sleep() faster
kill 15, $pid;
sleep(2);
if ($pid > 1) {
kill 9, -$pid;
}
kill 9, $pid;
exit(125);
}
# parent
local $SIG{INT} = sub { bigkill($pid); };
local $SIG{TERM} = sub { bigkill($pid); };
local $SIG{ALRM} = sub {
print STDERR "Alarm timed out! No test results for too long.\n";
bigkill($pid);
};
sub colourize($)
{
my $result = shift;
my $pass = ($result eq "ok");
if ($istty) {
my $colour = $pass ? "\e[32;1m" : "\e[31;1m";
return "$colour$result\e[0m";
} else {
return $result;
}
}
sub mstime($$$)
{
my ($floatsec, $warntime, $badtime) = @_;
my $ms = int($floatsec * 1000);
my $str = sprintf("%d.%03ds", $ms/1000, $ms % 1000);
if ($istty && $ms > $badtime) {
return "\e[31;1m$str\e[0m";
} elsif ($istty && $ms > $warntime) {
return "\e[33;1m$str\e[0m";
} else {
return "$str";
}
}
sub resultline($$)
{
my ($name, $result) = @_;
return sprintf("! %-65s %s", $name, colourize($result));
}
my $allstart = time();
my ($start, $stop);
sub endsect()
{
$stop = time();
if ($start) {
printf " %s %s\n", mstime($stop - $start, 500, 1000), colourize("ok");
}
}
while (<$fh>)
{
chomp;
s/\r//g;
if (/^\s*Testing "(.*)" with (.*) in (.*):\s*$/)
{
alarm(120);
my ($sect, $shell, $file) = ($1, $2, $3);
endsect();
chomp($shell=`basename $shell`);
printf("! %s %s %s: ", $shell, $file, $sect);
@log = ();
$start = $stop;
}
elsif (/^!\s*(.*?)\s+(\S+)\s*$/)
{
alarm(120);
my ($name, $result) = ($1, $2);
my $pass = ($result eq "ok");
if (!$start) {
printf("\n! Startup: ");
$start = time();
}
push @log, resultline($name, $result);
if (!$pass) {
$gfails++;
if (@log) {
print "\n" . join("\n", @log) . "\n";
@log = ();
}
} else {
$gpasses++;
print ".";
}
}
else
{
push @log, $_;
}
}
endsect();
my $newpid = waitpid($pid, 0);
if ($newpid != $pid) {
die("waitpid returned '$newpid', expected '$pid'\n");
}
my $code = $?;
my $ret = ($code >> 8);
# return death-from-signal exits as >128. This is what bash does if you ran
# the program directly.
if ($code && !$ret) { $ret = $code | 128; }
if ($ret && @log) {
print "\n" . join("\n", @log) . "\n";
}
if ($code != 0) {
print resultline("Program returned non-zero exit code ($ret)", "FAILED");
}
my $gtotal = $gpasses+$gfails;
printf("\nWvTest: %d test%s, %d failure%s, total time %s.\n",
$gtotal, $gtotal==1 ? "" : "s",
$gfails, $gfails==1 ? "" : "s",
mstime(time() - $allstart, 2000, 5000));
print STDERR "\nWvTest result code: $ret\n";
exit( $ret ? $ret : ($gfails ? 125 : 0) );