summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDave Reisner <dreisner@archlinux.org>2012-09-28 19:54:10 +0200
committerDave Reisner <dreisner@archlinux.org>2012-10-07 02:38:02 +0200
commit367ac227f42ca9c8a7c050da0bcc04248fae29b1 (patch)
treef40bebd836e87a884b1995fac189d1da5edc6b42
parent4bbca4a841eb6810b003009838cb681fd7ace07a (diff)
downloadmkinitcpio-367ac227f42ca9c8a7c050da0bcc04248fae29b1.tar.gz
mkinitcpio-367ac227f42ca9c8a7c050da0bcc04248fae29b1.tar.xz
commit to some level of style in variable naming
This is an ugly patch, and probably does more than I'd like it to. The idea is that mkinitcpio adopts some sort of consistent style which I'm actually happy with. I define 3 kinds of variables: 1) local variables: all lower case, and scoped within functions. Use freely, as they're well contained. 2) global variables: these are known to mkinitcpio internally, but are global in scope. They mainly carry runtime configuration and collected data during the image generation process. These are always lower case, but carry a leading underscore to denote that they're global. 3) "API" variables: also global in scope, but exist "outside" of mkinitcpio -- either drawn in from the configuration file, or "exported" to the install hooks. These are always all upper case. When introducing new variables, extreme care must be taken to pick names that will not conflict with the environment inherited by mkinitcpio. A HACKING file is introduced with a similar description of the above, and more. Signed-off-by: Dave Reisner <dreisner@archlinux.org>
-rw-r--r--HACKING67
-rw-r--r--Makefile12
-rw-r--r--functions92
-rw-r--r--install/autodetect17
-rwxr-xr-xlsinitcpio109
-rwxr-xr-xmkinitcpio205
6 files changed, 285 insertions, 217 deletions
diff --git a/HACKING b/HACKING
new file mode 100644
index 0000000..774a03d
--- /dev/null
+++ b/HACKING
@@ -0,0 +1,67 @@
+Care and feeding of your initramfs generator
+--------------------------------------------
+
+This guide attempts to outline the style used in the mkinitcpio codebase.
+
+
+Bash v. POSIX
+-------------
+Never use POSIX syntax if Bash offers a construct of its own, even if the
+two are effectively identical. This means always using double braces over
+the inferior '[' and 'test'.
+
+
+Variable usage and naming convetions
+------------------------------------
+There are three classifications of variables in mkinitcpio.
+
+1) local variables: all lower case, and scoped within functions. Use
+freely, as they're well contained. Unless you're introducing a new
+option, this is what you want to use.
+
+ local foo=$1
+
+2) global variables: these are known to mkinitcpio internally, but are
+global in scope. They carry runtime configuration and data collected during the
+image generation process. These are always lower case, but carry a leading
+underscore to denote that they're global. It's helpful to prefix these
+variables instead with a '_f_' or '_d_' if they refer to a file or directory,
+respectively.
+
+ _optcolor=1
+ _d_hookdir=/etc/foo.d
+ _f_config=/etc/foo.conf
+
+3) "API" variables: also global in scope, but exist "outside" of
+mkinitcpio -- either drawn in from the configuration file, or "exported"
+to the install hooks. These are always all upper case. When introducing
+new variables, extreme care must be taken to pick names that will not
+conflict with the environment inherited by mkinitcpio.
+
+Function naming
+---------------
+Use all lower case with underscores where appropriate, for easy readability.
+Adhere to POSIX variable naming requirements for the contents of the name,
+that is: only alphanumerics, underscores, and the identifier must not start
+with a number.
+
+
+Quoting
+-------
+Overquoting is preferred to underquoting, but freely avoid quoting in the
+cases when expansion is guaranteed not to happen, such as in single argument
+test expressions or the subject of a case statement.
+
+
+Functions and block statements
+------------------------------
+Always use "top-right, "lower left" for blocks of code and functions.
+
+ do_glob() {
+ local g fn=$1; shift
+
+ for g in "$@"; do
+ "$fn" "$g"
+ done
+ }
+
diff --git a/Makefile b/Makefile
index 398be6d..02b042c 100644
--- a/Makefile
+++ b/Makefile
@@ -22,15 +22,15 @@ install: all
mkdir -p ${DESTDIR}
$(foreach dir,${DIRS},install -dm755 ${DESTDIR}${dir};)
- sed -e 's|^CONFIG=.*|CONFIG=/etc/mkinitcpio.conf|' \
- -e 's|^FUNCTIONS=.*|FUNCTIONS=/usr/lib/initcpio/functions|' \
- -e 's|^HOOKDIR=.*|HOOKDIR=({/usr,}/lib/initcpio/hooks)|' \
- -e 's|^INSTDIR=.*|INSTDIR=({/usr,}/lib/initcpio/install)|' \
- -e 's|^PRESETDIR=.*|PRESETDIR=/etc/mkinitcpio.d|' \
+ sed -e 's|^_f_config=.*|_f_config=/etc/mkinitcpio.conf|' \
+ -e 's|^_f_functions=.*|_f_functions=/usr/lib/initcpio/functions|' \
+ -e 's|^_d_hooks=.*|_d_hooks=({/usr,}/lib/initcpio/hooks)|' \
+ -e 's|^_d_install=.*|_d_install=({/usr,}/lib/initcpio/install)|' \
+ -e 's|^_d_presets=.*|_d_presets=/etc/mkinitcpio.d|' \
-e 's|%VERSION%|${VERSION}|g' \
< mkinitcpio > ${DESTDIR}/usr/bin/mkinitcpio
- sed -e 's|\(^declare FUNCTIONS\)=.*|\1=/usr/lib/initcpio/functions|' \
+ sed -e 's|\(^_f_functions\)=.*|\1=/usr/lib/initcpio/functions|' \
-e 's|%VERSION%|${VERSION}|g' \
< lsinitcpio > ${DESTDIR}/usr/bin/lsinitcpio
diff --git a/functions b/functions
index e213580..5a75a79 100644
--- a/functions
+++ b/functions
@@ -139,27 +139,31 @@ parseopts() {
plain() {
local mesg=$1; shift
- printf "$BOLD $mesg$NC\n" "$@" >&1
+ printf " $_color_bold$mesg$_color_none\n" "$@" >&1
+}
+
+quiet() {
+ (( _optquiet )) || plain "$@"
}
msg() {
local mesg=$1; shift
- printf "$GREEN==>$NC$BOLD $mesg$NC\n" "$@" >&1
+ printf "$_color_green==>$_color_none $_color_bold$mesg$_color_none\n" "$@" >&1
}
msg2() {
local mesg=$1; shift
- printf "$BLUE ->$NC$BOLD $mesg$NC\n" "$@" >&1
+ printf " $_color_blue->$_color_none $_color_bold$mesg$_color_none\n" "$@" >&1
}
warning() {
local mesg=$1; shift
- printf "$YELLOW==> WARNING:$NC$BOLD $mesg$NC\n" "$@" >&2
+ printf "$_color_yellow==> WARNING:$_color_none $_color_bold$mesg$_color_none\n" "$@" >&2
}
error() {
local mesg=$1; shift
- printf "$RED==> ERROR:$NC$BOLD $mesg$NC\n" "$@" >&2
+ printf "$_color_red==> ERROR:$_color_none $_color_bold$mesg$_color_none\n" "$@" >&2
return 1
}
@@ -242,7 +246,7 @@ all_modules() {
mod=${mod##*/}
mod="${mod%.ko*}"
printf '%s\n' "${mod//-/_}"
- done < <(find "$MODULEDIR" -name '*.ko*' -print0 2>/dev/null | grep -EZz "$@")
+ done < <(find "$_d_kmoduledir" -name '*.ko*' -print0 2>/dev/null | grep -EZz "$@")
(( count ))
}
@@ -269,8 +273,8 @@ add_checked_modules() {
local mod mods
- if [[ -s $MODULE_FILE ]]; then
- mapfile -t mods < <(all_modules "$@" | grep -xFf "$MODULE_FILE")
+ if [[ -s $_f_autodetect_cache ]]; then
+ mapfile -t mods < <(all_modules "$@" | grep -xFf "$_f_autodetect_cache")
else
mapfile -t mods < <(all_modules "$@")
fi
@@ -289,8 +293,8 @@ checked_modules() {
# DEPRECATED: Use add_checked_modules instead
#
- if [[ -s $MODULE_FILE ]]; then
- grep -xFf "$MODULE_FILE" <(all_modules "$@")
+ if [[ -s $_f_autodetect_cache ]]; then
+ grep -xFf "$_f_autodetect_cache" <(all_modules "$@")
return 1
else
all_modules "$@"
@@ -313,7 +317,7 @@ add_module() {
module=${1%.ko*}
# skip expensive stuff if this module has already been added
- (( ADDED_MODULES["${module//-/_}"] )) && return
+ (( _addedmodules["${module//-/_}"] )) && return
while IFS=':= ' read -r -d '' field value; do
case "$field" in
@@ -341,9 +345,9 @@ add_module() {
fi
# aggregate modules and add them all at once to save some forks
- (( QUIET )) || plain "adding module: %s" "$1"
- MODPATHS+=("$path")
- ADDED_MODULES["${module//-/_}"]=1
+ quiet "adding module: %s" "$1"
+ _modpaths+=("$path")
+ _addedmodules["${module//-/_}"]=1
# handle module quirks
case $module in
@@ -397,7 +401,7 @@ add_dir() {
return 0
fi
- (( QUIET )) || plain "adding dir: %s" "$path"
+ quiet "adding dir: %s" "$path"
command install -dm$mode "$BUILDROOT$path"
}
@@ -407,28 +411,26 @@ add_symlink() {
# $1: pathname of symlink on image
# $2: absolute path to target of symlink (optional, can be read from $1)
- local name_=$1 target_=$2
+ local name=$1 target=$2
(( $# == 1 || $# == 2 )) || return 1
- if [[ -z $target_ ]]; then
- target_=$(readlink -f "$name_")
- if [[ -z $target_ ]]; then
- error 'invalid symlink: %s' "$name_"
+ if [[ -z $target ]]; then
+ target=$(readlink -f "$name")
+ if [[ -z $target ]]; then
+ error 'invalid symlink: %s' "$name"
return 1
fi
fi
- add_dir "${name_%/*}"
+ add_dir "${name%/*}"
- if (( ! QUIET )); then
- if [[ -L $BUILDROOT$1 ]]; then
- plain "overwriting symlink %s -> %s" "$name_" "$target_"
- else
- plain "adding symlink: %s -> %s" "$name_" "$target_"
- fi
+ if [[ -L $BUILDROOT$1 ]]; then
+ quiet "overwriting symlink %s -> %s" "$name" "$target"
+ else
+ quiet "adding symlink: %s -> %s" "$name" "$target"
fi
- ln -sfn "$target_" "$BUILDROOT$name_"
+ ln -sfn "$target" "$BUILDROOT$name"
}
add_file() {
@@ -454,12 +456,10 @@ add_file() {
return 1
fi
- if (( ! QUIET )); then
- if [[ -e $BUILDROOT$dest ]]; then
- plain "overwriting file: %s" "$dest"
- else
- plain "adding file: %s" "$dest"
- fi
+ if [[ -e $BUILDROOT$dest ]]; then
+ quiet "overwriting file: %s" "$dest"
+ else
+ quiet "adding file: %s" "$dest"
fi
command install -Dm$mode "$src" "$BUILDROOT$dest"
}
@@ -473,7 +473,7 @@ add_runscript() {
local funcs fn script hookname=${SCRIPT:-${BASH_SOURCE[1]##*/}}
- if ! script=$(find_in_dirs "$hookname" "${HOOKDIR[@]}"); then
+ if ! script=$(find_in_dirs "$hookname" "${_d_hooks[@]}"); then
error "runtime script for \`%s' not found" "$hookname"
return
fi
@@ -485,16 +485,16 @@ add_runscript() {
for fn in "${funcs[@]}"; do
case $fn in
run_earlyhook)
- RUNHOOKS['early']+=" $hookname"
+ _runhooks['early']+=" $hookname"
;;
run_hook)
- RUNHOOKS['hooks']+=" $hookname"
+ _runhooks['hooks']+=" $hookname"
;;
run_latehook)
- RUNHOOKS['late']+=" $hookname"
+ _runhooks['late']+=" $hookname"
;;
run_cleanuphook)
- RUNHOOKS['cleanup']="$hookname ${RUNHOOKS['cleanup']}"
+ _runhooks['cleanup']="$hookname ${_runhooks['cleanup']}"
;;
esac
done
@@ -595,22 +595,22 @@ write_image_config() {
# write the config as runtime config and as a pristine build config
# (for audting purposes) to the image.
- tee "$BUILDROOT/buildconfig" < "$CONFIG" | {
+ tee "$BUILDROOT/buildconfig" < "$_f_config" | {
. /dev/stdin
# sanitize of any extra whitespace
read -ra modules <<<"${MODULES//-/_}"
for mod in "${modules[@]%\?}"; do
# only add real modules (2 == builtin)
- (( ADDED_MODULES["$mod"] == 1 )) && add+=("$mod")
+ (( _addedmodules["$mod"] == 1 )) && add+=("$mod")
done
(( ${#add[*]} )) && printf 'MODULES="%s"\n' "${add[*]}"
printf '%s="%s"\n' \
- 'EARLYHOOKS' "${RUNHOOKS['early']# }" \
- 'HOOKS' "${RUNHOOKS['hooks']# }" \
- 'LATEHOOKS' "${RUNHOOKS['late']# }" \
- 'CLEANUPHOOKS' "${RUNHOOKS['cleanup']% }"
+ 'EARLYHOOKS' "${_runhooks['early']# }" \
+ 'HOOKS' "${_runhooks['hooks']# }" \
+ 'LATEHOOKS' "${_runhooks['late']# }" \
+ 'CLEANUPHOOKS' "${_runhooks['cleanup']% }"
} >"$BUILDROOT/config"
}
@@ -653,7 +653,7 @@ run_build_hook() {
local MODULES= BINARIES= FILES= SCRIPT=
# find script in install dirs
- if ! script=$(find_in_dirs "$hook" "${INSTDIR[@]}"); then
+ if ! script=$(find_in_dirs "$hook" "${_d_install[@]}"); then
error "Hook '$hook' cannot be found"
return 1
fi
diff --git a/install/autodetect b/install/autodetect
index c0c7563..4f1e4bb 100644
--- a/install/autodetect
+++ b/install/autodetect
@@ -3,17 +3,17 @@
build() {
local -a md_devs
- MODULE_FILE=$workdir/autodetect_modules
+ _f_autodetect_cache=$_d_workdir/autodetect_modules
add_if_avail() {
local resolved
# treat this as an alias, since ext3 might be aliased to ext4.
IFS=$'\n' read -rd '' -a resolved < \
- <(modprobe -d "$MODULEROOT" -S "$KERNELVERSION" -R "$1" 2>/dev/null)
+ <(modprobe -d "$_optmoduleroot" -S "$KERNELVERSION" -R "$1" 2>/dev/null)
if (( ${#resolved[*]} )); then
- printf '%s\n' "${resolved[@]}" >>"$MODULE_FILE"
+ printf '%s\n' "${resolved[@]}" >>"$_f_autodetect_cache"
fi
}
@@ -22,7 +22,7 @@ build() {
return 1
fi
- auto_modules >"$MODULE_FILE"
+ auto_modules >"$_f_autodetect_cache"
# detect filesystem for root
if rootfstype=$(findmnt -uno fstype '/'); then
@@ -40,12 +40,13 @@ build() {
# scan for md raid devices
md_devs=(/sys/class/block/md*/md/level)
if [[ -e $md_devs ]]; then
- (( !QUIET )) && plain "found %d mdadm arrays to scan" "${#md_devs[*]}"
- awk '{ gsub(/raid[456]/, "raid456"); print; }' "${md_devs[@]}" | sort -u >>"$MODULE_FILE"
+ quiet "found %d mdadm arrays to scan" "${#md_devs[*]}"
+ awk '{ gsub(/raid[456]/, "raid456"); print; }' "${md_devs[@]}" |
+ sort -u >>"$_f_autodetect_cache"
fi
- if (( !QUIET )) && [[ -s $MODULE_FILE ]]; then
- plain "caching %d modules" $(wc -l < "$MODULE_FILE")
+ if [[ -s $_f_autodetect_cache ]]; then
+ quiet "caching %d modules" $(wc -l < "$_f_autodetect_cache")
fi
}
diff --git a/lsinitcpio b/lsinitcpio
index 2dc7d35..f94dd8c 100755
--- a/lsinitcpio
+++ b/lsinitcpio
@@ -5,11 +5,9 @@
shopt -s extglob
-declare verbose=
-declare list='--list'
-declare -i color=1
-declare NC= BOLD= BLUE= GREEN= RED= YELLOW=
-declare FUNCTIONS=functions
+_list='--list'
+_optcolor=1 _optverbose=0
+_f_functions=functions
usage() {
cat<<USAGE
@@ -31,10 +29,10 @@ USAGE
}
decomp() {
- ${compress:-cat} ${compress:+-cd} "$@"
+ ${_compress:-cat} ${_compress:+-cd} "$@"
}
-. "$FUNCTIONS"
+. "$_f_functions"
# override the die method from functions
die() {
@@ -73,19 +71,19 @@ analyze_image() {
# fallback in case tput failed us
columns=${columns:-80}
- zsize=$(stat -c %s "$image")
+ zsize=$(stat -c %s "$_image")
# calculate compression ratio
- TIMEFORMAT=%R decomptime=$({ time decomp "$image" >/dev/null; } 2>&1 )
- if [[ $compress ]]; then
- fullsize=$(decomp "$image" | bsdtar xOf - | wc -c)
+ TIMEFORMAT=%R decomptime=$({ time decomp "$_image" >/dev/null; } 2>&1 )
+ if [[ $_compress ]]; then
+ fullsize=$(decomp "$_image" | bsdtar xOf - | wc -c)
ratio=.$(( zsize * 1000 / fullsize % 1000 ))
fi
# decompress the image since we need to read from it multiple times. we
# have to pass this through decomp() since the image might be lzop which
# bsdtar can't read.
- decomp "$image" | bsdtar -C "$workdir" -xf -
+ decomp "$_image" | bsdtar -C "$workdir" -xf -
# collect stats
kernver=("$workdir"/usr/lib/modules/*/)
@@ -113,15 +111,15 @@ analyze_image() {
explicitmod=($MODULES)
# print results
- imagename=$image
- [[ -L $image ]] && imagename+=" -> $(readlink -e "$image")"
+ imagename=$_image
+ [[ -L $_image ]] && imagename+=" -> $(readlink -e "$_image")"
msg 'Image: %s %s' "$imagename"
[[ $version ]] && msg 'Created with mkinitcpio %s' "$version"
msg 'Kernel: %s' "${kernver:-unknown}"
msg 'Size: %s' "$(size_to_human "$zsize")"
- if [[ $compress ]]; then
- msg 'Compressed with: %s' "$compress"
+ if [[ $_compress ]]; then
+ msg 'Compressed with: %s' "$_compress"
msg2 'Uncompressed size: %s (%s ratio)' "$(size_to_human "$fullsize")" "$ratio"
fi
msg2 'Estimated extraction time: %ss' "$decomptime"
@@ -166,32 +164,32 @@ analyze_image() {
fi
}
-OPT_SHORT='achlnvx'
-OPT_LONG=('analyze' 'help' 'list' 'nocolor' 'showconfig' 'verbose' 'extract')
+_opt_short='achlnvx'
+_opt_long=('analyze' 'help' 'list' 'nocolor' 'showconfig' 'verbose' 'extract')
-if ! parseopts "$OPT_SHORT" "${OPT_LONG[@]}" -- "$@"; then
+if ! parseopts "$_opt_short" "${_opt_long[@]}" -- "$@"; then
exit 1
fi
set -- "${OPTRET[@]}"
-unset OPT_SHORT OPT_LONG OPTRET
+unset _opt_short _opt_long OPTRET
while :; do
case $1 in
-a|--analyze)
- analyze=1 ;;
+ _optanalyze=1 ;;
-c|--config)
- showconfig=1 ;;
+ _optshowconfig=1 ;;
-h|--help)
usage
exit 0 ;;
-l|--list)
- listcontents=1 ;;
+ _optlistcontents=1 ;;
-n|--nocolor)
- color=0 ;;
+ _optcolor=0 ;;
-v|--verbose)
- verbose='--verbose' ;;
+ _optverbose='--verbose' ;;
-x|--extract)
- unset list ;;
+ unset _list ;;
--)
shift
break 2 ;;
@@ -199,55 +197,54 @@ while :; do
shift
done
-declare image=$1
+_image=$1
-if [[ -t 1 ]] && (( color )); then
+if [[ -t 1 ]] && (( _optcolor )); then
# prefer terminal safe colored and bold text when tput is supported
if tput setaf 0 &>/dev/null; then
- NC="$(tput sgr0)"
- BOLD="$(tput bold)"
- BLUE="$BOLD$(tput setaf 4)"
- GREEN="$BOLD$(tput setaf 2)"
- RED="$BOLD$(tput setaf 1)"
- YELLOW="$BOLD$(tput setaf 3)"
+ _color_none="$(tput sgr0)"
+ _color_bold="$(tput bold)"
+ _color_blue="$_color_bold$(tput setaf 4)"
+ _color_green="$_color_bold$(tput setaf 2)"
+ _color_red="$_color_bold$(tput setaf 1)"
+ _color_yellow="$_color_bold$(tput setaf 3)"
else
- NC="\e[1;0m"
- BOLD="\e[1;1m"
- BLUE="$BOLD\e[1;34m"
- GREEN="$BOLD\e[1;32m"
- RED="$BOLD\e[1;31m"
- YELLOW="$BOLD\e[1;33m"
+ _color_none="\e[1;0m"
+ _color_bold="\e[1;1m"
+ _color_blue="$_color_bold\e[1;34m"
+ _color_green="$_color_bold\e[1;32m"
+ _color_red="$_color_bold\e[1;31m"
+ _color_yellow="$_color_bold\e[1;33m"
fi
fi
-readonly NC BOLD BLUE GREEN RED YELLOW
-[[ $image ]] || die "No image specified (use -h for help)"
-[[ -f $image ]] || die "No such file: $image"
+[[ $_image ]] || die "No image specified (use -h for help)"
+[[ -f $_image ]] || die "No such file: %s" "$_image"
-case $(( analyze + listcontents + showconfig )) in
+case $(( _optanalyze + _optlistcontents + _optshowconfig )) in
0)
# default action when none specified
- listcontents=1 ;;
+ _optlistcontents=1 ;;
[!1])
die "Only one action may be specified at a time" ;;
esac
# read compression type
-case "$(file -Lb "$image")" in
- @(data|LZMA)*) compress=lzma ;;
- gzip*) compress=gzip ;;
- bzip2*) compress=bzip2 ;;
- lzop*) compress=lzop ;;
- XZ*) compress=xz ;;
+case $(file -Lb "$_image") in
+ @(data|LZMA)*) _compress=lzma ;;
+ gzip*) _compress=gzip ;;
+ bzip2*) _compress=bzip2 ;;
+ lzop*) _compress=lzop ;;
+ XZ*) _compress=xz ;;
esac
-if (( analyze )); then
- analyze_image "$image"
-elif (( showconfig )); then
- decomp "$1" | bsdtar xOf - buildconfig 2>/dev/null ||
+if (( _optanalyze )); then
+ analyze_image "$_image"
+elif (( _optshowconfig )); then
+ decomp "$_image" | bsdtar xOf - buildconfig 2>/dev/null ||
die 'Failed to extract config from image (mkinitcpio too old?)'
else
- decomp "$image" | bsdcpio -i --quiet $verbose $list
+ decomp "$_image" | bsdcpio -i --quiet $_optverbose $_list
fi
# vim: set ft=sh ts=4 sw=4 et:
diff --git a/mkinitcpio b/mkinitcpio
index f92cc44..0300954 100755
--- a/mkinitcpio
+++ b/mkinitcpio
@@ -7,19 +7,22 @@ declare -r version=%VERSION%
shopt -s extglob
-# Settings
-FUNCTIONS=functions
-CONFIG=mkinitcpio.conf
-HOOKDIR=(hooks /usr/lib/initcpio/hooks /lib/initcpio/hooks)
-INSTDIR=(install /usr/lib/initcpio/install /lib/initcpio/install)
-PRESETDIR=mkinitcpio.d
-COMPRESSION=gzip
-
-declare MODULE_FILE= GENIMG= PRESET= COMPRESSION_OPTIONS= BUILDROOT=
-declare NC= BOLD= BLUE= GREEN= RED= YELLOW=
-declare -i QUIET=1 SHOW_AUTOMODS=0 SAVELIST=0 COLOR=1
-declare -a SKIPHOOKS MODPATHS
-declare -A RUNHOOKS ADDED_MODULES
+### globals within mkinitcpio, but not intended to be used by hooks
+
+# needed files/directories
+_f_functions=functions
+_f_config=mkinitcpio.conf
+_d_hooks=(hooks /usr/lib/initcpio/hooks /lib/initcpio/hooks)
+_d_install=(install /usr/lib/initcpio/install /lib/initcpio/install)
+_d_presets=mkinitcpio.d
+
+# options and runtime data
+_optmoduleroot= _optkver= _f_autodetect_cache= _optgenimg= _optpreset=
+_optcompress=
+_optshowautomods=0 _optsavetree=0 _optshowmods=0
+_optquiet=1 _optcolor=1
+_optskiphooks=() _optaddhooks=() _modpaths=() _hooks=()
+declare -A _runhooks=() _addedmodules=()
# export a sane PATH
export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
@@ -58,12 +61,12 @@ EOF
cleanup() {
local err=${1:-$?}
- if [[ $workdir ]]; then
- # when PRESET is set, we're in the main loop, not a worker process
- if (( SAVELIST )) && [[ -z $PRESET ]]; then
- msg "build directory saved in %s" "$workdir"
+ if [[ $_d_workdir ]]; then
+ # when _optpreset is set, we're in the main loop, not a worker process
+ if (( _optsavetree )) && [[ -z $_optpreset ]]; then
+ msg "build directory saved in %s" "$_d_workdir"
else
- rm -rf "$workdir"
+ rm -rf "$_d_workdir"
fi
fi
@@ -71,7 +74,7 @@ cleanup() {
}
resolve_kernver() {
- local kernver= kernel=$1
+ local kernel=$1
if [[ -z $kernel ]]; then
uname -r
@@ -92,7 +95,7 @@ resolve_kernver() {
return 0
fi
- error "invalid kernel specified: \`%s'" "$optkver"
+ error "invalid kernel specified: \`%s'" "$_optkver"
return 1
}
@@ -100,7 +103,7 @@ resolve_kernver() {
find_moduledir() {
local d
- for d in "$MODULEROOT"{/usr,}/lib/modules; do
+ for d in "$_optmoduleroot"{/usr,}/lib/modules; do
if [[ -d $d/$1/ ]]; then
printf '%s' "$d/$1/"
return 0
@@ -113,25 +116,27 @@ find_moduledir() {
}
compute_hookset() {
- for h in $HOOKS "${ADDHOOKS[@]}"; do
- in_array "$h" "${SKIPHOOKS[@]}" && continue
- hooks+=("$h")
+ local h
+
+ for h in $HOOKS "${_optaddhooks[@]}"; do
+ in_array "$h" "${_optskiphooks[@]}" && continue
+ _hooks+=("$h")
done
}
-. "$FUNCTIONS"
+. "$_f_functions"
trap 'cleanup 130' INT
trap 'cleanup 143' TERM
-OPT_SHORT='A:c:g:H:hk:mnLMp:r:S:st:vz:'
-OPT_LONG=('add:' 'addhooks:' 'config:' 'generate:' 'hookhelp:' 'help'
+_opt_short='A:c:g:H:hk:nLMp:r:S:st:vz:'
+_opt_long=('add:' 'addhooks:' 'config:' 'generate:' 'hookhelp:' 'help'
'kernel:' 'listhooks' 'automods' 'moduleroot:' 'nocolor'
'preset:' 'skiphooks:' 'save' 'builddir:' 'verbose' 'compress:')
-parseopts "$OPT_SHORT" "${OPT_LONG[@]}" -- "$@" || exit 1
+parseopts "$_opt_short" "${_opt_long[@]}" -- "$@" || exit 1
set -- "${OPTRET[@]}"
-unset OPT_SHORT OPT_LONG OPTRET
+unset _opt_short _opt_long OPTRET
while :; do
case $1 in
@@ -139,20 +144,20 @@ while :; do
-A|--add|--addhooks)
shift
IFS=, read -r -a add <<< "$1"
- ADDHOOKS+=("${add[@]}")
+ _optaddhooks+=("${add[@]}")
unset add ;;
-c|--config)
shift
- CONFIG=$1 ;;
+ _f_config=$1 ;;
-k|--kernel)
shift
- optkver=$1 ;;
+ _optkver=$1 ;;
-s|--save)
- SAVELIST=1 ;;
+ _optsavetree=1 ;;
-g|--generate)
shift
[[ -d $1 ]] && die "Invalid image path -- must not be a directory"
- if ! GENIMG=$(readlink -f "$1") || [[ ! -e ${GENIMG%/*} ]]; then
+ if ! _optgenimg=$(readlink -f "$1") || [[ ! -e ${_optgenimg%/*} ]]; then
die "Unable to write to path: \`%s'" "$1"
fi ;;
-h|--help)
@@ -160,19 +165,19 @@ while :; do
cleanup 0 ;;
-p|--preset)
shift
- PRESET=$1 ;;
+ _optpreset=$1 ;;
-n|--nocolor)
- COLOR=0 ;;
+ _optcolor=0 ;;
-v|--verbose)
- QUIET=0 ;;
+ _optquiet=0 ;;
-S|--skiphooks)
shift
IFS=, read -r -a skip <<< "$1"
- SKIPHOOKS+=("${skip[@]}")
+ _optskiphooks+=("${skip[@]}")
unset skip ;;
-H|--hookhelp)
shift
- if script=$(find_in_dirs "$1" "${INSTDIR[@]}"); then
+ if script=$(find_in_dirs "$1" "${_d_install[@]}"); then
. "$script"
if ! declare -f help >/dev/null; then
error "No help for hook $1"
@@ -188,21 +193,21 @@ while :; do
exit 0 ;;
-L|--listhooks)
msg "Available hooks"
- for dir in "${INSTDIR[@]}"; do
+ for dir in "${_d_install[@]}"; do
( cd "$dir" &>/dev/null && printf ' %s\n' * )
done | sort -u | column -c$(tput cols)
exit 0 ;;
-M|--automods)
- SHOW_AUTOMODS=1 ;;
+ _optshowautomods=1 ;;
-t|--builddir)
shift
export TMPDIR=$1 ;;
-z|--compress)
shift
- optcompress=$1 ;;
+ _optcompress=$1 ;;
-r|--moduleroot)
shift
- MODULEROOT=$1 ;;
+ _optmoduleroot=$1 ;;
--)
shift
break 2 ;;
@@ -210,25 +215,24 @@ while :; do
shift
done
-if [[ -t 1 ]] && (( COLOR )); then
+if [[ -t 1 ]] && (( _optcolor )); then
# prefer terminal safe colored and bold text when tput is supported
if tput setaf 0 &>/dev/null; then
- NC="$(tput sgr0)"
- BOLD="$(tput bold)"
- BLUE="$BOLD$(tput setaf 4)"
- GREEN="$BOLD$(tput setaf 2)"
- RED="$BOLD$(tput setaf 1)"
- YELLOW="$BOLD$(tput setaf 3)"
+ _color_none="$(tput sgr0)"
+ _color_bold="$(tput bold)"
+ _color_blue="$_color_bold$(tput setaf 4)"
+ _color_green="$_color_bold$(tput setaf 2)"
+ _color_red="$_color_bold$(tput setaf 1)"
+ _color_yellow="$_color_bold$(tput setaf 3)"
else
- NC="\e[1;0m"
- BOLD="\e[1;1m"
- BLUE="$BOLD\e[1;34m"
- GREEN="$BOLD\e[1;32m"
- RED="$BOLD\e[1;31m"
- YELLOW="$BOLD\e[1;33m"
+ _color_none="\e[1;0m"
+ _color_bold="\e[1;1m"
+ _color_blue="$_color_bold\e[1;34m"
+ _color_green="$_color_bold\e[1;32m"
+ _color_red="$_color_bold\e[1;31m"
+ _color_yellow="$_color_bold\e[1;33m"
fi
fi
-readonly NC BOLD BLUE GREEN RED YELLOW
# insist that /proc and /dev be mounted (important for chroots)
# NOTE: avoid using mountpoint for this -- look for the paths that we actually
@@ -236,18 +240,18 @@ readonly NC BOLD BLUE GREEN RED YELLOW
[[ -e /proc/self/mountinfo ]] || die "/proc must be mounted!"
[[ -e /dev/fd ]] || die "/dev must be mounted!"
-# use preset $PRESET
-if [[ $PRESET ]]; then
+# use preset $_optpreset
+if [[ $_optpreset ]]; then
# allow absolute path to preset file, else resolve it
- if [[ ${PRESET:0:1} != '/' ]]; then
- printf -v PRESET '%s/%s.preset' "$PRESETDIR" "$PRESET"
+ if [[ ${_optpreset:0:1} != '/' ]]; then
+ printf -v _optpreset '%s/%s.preset' "$_d_presets" "$_optpreset"
fi
- if [[ -f $PRESET ]]; then
+ if [[ -f $_optpreset ]]; then
# Use -b, -m and -v options specified earlier
declare -a preset_mkopts preset_cmd
- (( QUIET )) || preset_mkopts+=(-v)
+ (( _optquiet )) || preset_mkopts+=(-v)
# Build all images
- . "$PRESET"
+ . "$_optpreset"
for p in "${PRESETS[@]}"; do
msg "Building image from preset: '$p'"
preset_cmd=("${preset_mkopts[@]}")
@@ -286,53 +290,52 @@ if [[ $PRESET ]]; then
done
cleanup 0
else
- die "Preset not found: \`%s'" "$PRESET"
+ die "Preset not found: \`%s'" "$_optpreset"
fi
fi
-KERNELVERSION=$(resolve_kernver "$optkver") || cleanup 1
-MODULEDIR=$(find_moduledir "$KERNELVERSION") || cleanup 1
+KERNELVERSION=$(resolve_kernver "$_optkver") || cleanup 1
+_d_kmoduledir=$(find_moduledir "$KERNELVERSION") || cleanup 1
-# initialize the working directory and buildroot
-workdir=$(initialize_buildroot "$KERNELVERSION") || cleanup 1
-BUILDROOT=$workdir/root
+_d_workdir=$(initialize_buildroot "$KERNELVERSION") || cleanup 1
+BUILDROOT=$_d_workdir/root
-. "$CONFIG" || die "Failed to read configuration \`%s'" "$CONFIG"
+. "$_f_config" || die "Failed to read configuration \`%s'" "$_f_config"
-# after returning, hooks are populated into the array 'hooks'
+# after returning, hooks are populated into the array '_hooks'
# HOOKS should not be referenced from here on
compute_hookset
-if (( ${#hooks[*]} == 0 )); then
+if (( ${#_hooks[*]} == 0 )); then
die "Invalid config: No hooks found"
fi
-if [[ ! -d $MODULEDIR ]]; then
- die "'$MODULEDIR' is not a valid kernel module directory"
+if [[ ! -d $_d_kmoduledir ]]; then
+ die "'$_d_kmoduledir' is not a valid kernel module directory"
fi
-if (( SHOW_AUTOMODS )); then
+if (( _optshowautomods )); then
msg "Modules autodetected"
- autodetect=$(find_in_dirs 'autodetect' "${INSTDIR[@]}")
- . "$autodetect"
+ _f_autodetect_hook=$(find_in_dirs 'autodetect' "${_d_install[@]}")
+ . "$_f_autodetect_hook"
build
- cat "$MODULE_FILE"
+ cat "$_f_autodetect_cache"
cleanup 0
fi
-if [[ -z $GENIMG ]]; then
+if [[ -z $_optgenimg ]]; then
msg "Starting dry run: %s" "$KERNELVERSION"
else
# check for permissions. if the image doesn't already exist,
# then check the directory
- if [[ ( -e $GENIMG && ! -w $GENIMG ) ||
- ( ! -d ${GENIMG%/*} || ! -w ${GENIMG%/*} ) ]]; then
- die 'Unable to write to %s' "$GENIMG"
+ if [[ ( -e $_optgenimg && ! -w $_optgenimg ) ||
+ ( ! -d ${_optgenimg%/*} || ! -w ${_optgenimg%/*} ) ]]; then
+ die 'Unable to write to %s' "$_optgenimg"
fi
- COMPRESSION=${optcompress:-$COMPRESSION}
- if ! type -P "$COMPRESSION" >/dev/null; then
- die "Unable to locate compression method: %s" "$COMPRESSION"
+ _optcompress=${_optcompress:-${COMPRESSION:-gzip}}
+ if ! type -P "$_optcompress" >/dev/null; then
+ die "Unable to locate compression method: %s" "$_optcompress"
fi
msg "Starting build: %s" "$KERNELVERSION"
@@ -343,14 +346,14 @@ declare -i builderrors=0
set -o functrace
trap '(( $? )) && [[ $FUNCNAME = add_* ]] && (( ++builderrors ))' RETURN
-# prime the ADDED_MODULES list with the builtins for this kernel
-if [[ -r $MODULEDIR/modules.builtin ]]; then
+# prime the _addedmodules list with the builtins for this kernel
+if [[ -r $_d_kmoduledir/modules.builtin ]]; then
while read -a path; do
- ADDED_MODULES["${path[-1]%.ko}"]=2
- done <"$MODULEDIR/modules.builtin"
+ _addedmodules["${path[-1]%.ko}"]=2
+ done <"$_d_kmoduledir/modules.builtin"
fi
-for hook in "${hooks[@]}"; do
+for hook in "${_hooks[@]}"; do
run_build_hook "$hook" || (( ++builderrors ))
done
@@ -362,8 +365,8 @@ write_image_config
trap -- RETURN
trap '(( ++builderrors ))' ERR
-if (( ${#MODPATHS[*]} )); then
- printf '%s\0' "${MODPATHS[@]}" | sort -zu |
+if (( ${#_modpaths[*]} )); then
+ printf '%s\0' "${_modpaths[@]}" | sort -zu |
xargs -0 cp -t "$BUILDROOT/usr/lib/modules/$KERNELVERSION/kernel"
# unzip modules prior to recompression
@@ -371,12 +374,12 @@ if (( ${#MODPATHS[*]} )); then
msg "Generating module dependencies"
install -m644 -t "$BUILDROOT/usr/lib/modules/$KERNELVERSION" \
- "$MODULEDIR"/modules.builtin
+ "$_d_kmoduledir"/modules.builtin
# we install all modules into kernel/, making the .order file incorrect
# for the module tree. munge it, so that we have an accurate index.
awk -F'/' '{ print "kernel/" $NF }' \
- "$MODULEDIR"/modules.order >"$BUILDROOT/lib/modules/$KERNELVERSION/modules.order"
+ "$_d_kmoduledir"/modules.order >"$BUILDROOT/lib/modules/$KERNELVERSION/modules.order"
depmod -b "$BUILDROOT" "$KERNELVERSION"
@@ -392,17 +395,17 @@ set +o functrace
trap -- ERR
declare -i status=0
-if [[ $GENIMG ]]; then
- msg "Creating $COMPRESSION initcpio image: %s" "$GENIMG"
+if [[ $_optgenimg ]]; then
+ msg "Creating $_optcompress initcpio image: %s" "$_optgenimg"
- case $COMPRESSION in
+ case $_optcompress in
xz)
COMPRESSION_OPTIONS+=' --check=crc32'
;;
esac
cpio_opts=('-R' '0:0' '-0' '-o' '-H' 'newc')
- if (( QUIET )); then
+ if (( _optquiet )); then
cpio_opts+=('--quiet')
fi
@@ -412,7 +415,7 @@ if [[ $GENIMG ]]; then
pushd "$BUILDROOT" >/dev/null
find . -print0 |
LANG=C bsdcpio "${cpio_opts[@]}" |
- $COMPRESSION $COMPRESSION_OPTIONS > "$GENIMG"
+ $_optcompress $COMPRESSION_OPTIONS > "$_optgenimg"
pipesave=("${PIPESTATUS[@]}") # save immediately
popd >/dev/null
@@ -421,7 +424,7 @@ if [[ $GENIMG ]]; then
elif (( pipesave[1] )); then
errmsg="bsdcpio reported an error"
elif (( pipesave[2] )); then
- errmsg="$COMPRESSION reported an error"
+ errmsg="$_optcompress reported an error"
fi
if (( builderrors )); then