Style - churchers/vm-bhyve GitHub Wiki
Variables
In general we take the following format for variables:
Global - ${ALL_CAPS}
Local - ${_variable}
Unless variables are designed to be global, they should always be declared at the top of the current function using local. Quite often functions are designed to modify variables declared in a parent function. In this case, the variable should be listed in the @modifies list in the function description to make it clear that the function modifies variables declared outside of its scope.
All variables are accessed using braces - ${_variable}
Functions
The majority of functions are prefixed with the name of the library they belong to, as this helps make it obvious where functions are defined.
lib::function_name
We precede most functions with a small description that explains what the function does, and lists arguments and/or return values, unless the code is obvious.
Private functions are prefixed with __.
Coding Style
Commenting
Any code should be well commented, especially if it's not instantly clear exactly what the code is doing.
Indentation & Length
All code should be correctly indented, using 4 spaces.
Line length should be kept to a reasonable length, making use of \ to split code across multiple lines if necessary.
If Statements
If statements are written as follows. If there are multiple statements, there should be a blank line inbetween.
# check something
if [ test ]; then
code
fi
# check something else
if [ test2 ]; then
code2
fi
Where appropriate, tests are reduced to one line for brevity and clarity
[ "check err" ] && util::err "Some error"
[ "check ok" ] || util::err "Another error"
In order to simply code and help reduce line length, code should be designed to perform a check, then return or exit if appropriate, rather than containing large blocks of code inside if statements, e.g.:
lib::good_function(){
[ "check err condition" ] && return 1
main_code_block
}
lib::bad_function(){
if [ "check ok condition" ]; then
main_code_block
else
return 1
fi
}
Return Values
Where it makes sense, functions return 0 on success, or any other integer on error. For return values we prefer using setvar, rather than $(func) and echo, which requires a subshell. Not using a subshell has been shown to improve performance.
lib::good_function(){
local _var="$1"
setvar "${_var}" "return value"
}
lib::bad_function(){
echo "return value"
}
_variable=$(lib::bad_function)
lib::good_function "_variable"
Case Statements
In general, ;; should be placed on a new line to improve readability. The exception to this is when each case only contains one line, where adding ;; on a newline would needlessly increase code length. The function calls should however be lined up.
case "${_variable}" in
one) func_one ;;
two) func_two ;;
three) func_three ;;
esac