#!/bin/bash # $1 file to bundle # $2 bundled output file (optional) # if no output file then the bundled source is returned # it can be immediately invoked like this # source <(bundle myscript.sh) # or # scpt=$(bundle myscript.sh) # source <(echo -e "$scpt") module_load debug module_load file bundle () { local file local code local compact if [[ $1 == "-c" ]]; then module_load helpers compact=true shift 1 fi # todo add -c for compacting the bundle, change this to options parsing. if [[ "$1" ]]; then if [[ -f $1 ]]; then file=$1 else if [[ $1 == "-m" ]]; then file=$(module_find $2) shift 1 else if [[ $1 == "-mf" ]]; then module_load $2 code="$(declare -f $3)" shift 1 else code="$1" shift 1 fi fi fi else echo "aborting, no file, module or function passed for bundling" return 1 fi tmp_file=$( mktemp -t TEMP_FILE_bundle.XXXXXXXX ) chmod 600 "$tmp_file" # if [[ $2 == "__recurse__" ]] || [[ $file ]]; then if [[ $file ]]; then \cp $file $tmp_file else echo "$code" > $tmp_file fi if [[ ! $2 == "__recurse__" ]]; then _modules="" output=$2 debug outputing bundle to: $output debug "bash code to bundle \n $(cat $tmp_file)" fi modules=$(sed -n -e 's/^\s*module_load //p' < $tmp_file) if [[ $modules ]]; then # remove found module_load before continuing sed -i '/^\s*module_load/d' $tmp_file [[ $_modules ]] && debug "already bundled modules: $_modules" for module in $(printf '%s\n' "${modules[@]}"|tac); do if [[ $_modules == " $module "* ]]; then [[ $_modules ]] && debug module $module already bundled else if modp=$(module_find ${module}); then debug bundling module ${module} at: $modp prepend_file $modp $tmp_file fi fi done _modules="$_modules $modules" bundle $tmp_file __recurse__ fi # the recursion is done if [[ ! $2 == "__recurse__" ]]; then [[ $compact ]] && compact_file $tmp_file if [[ $BASH_DEBUG ]]; then debug "\n ------------code as bundled--------------\n \ $(cat $tmp_file) \ \n ------------------------------------------------------------ \n" debug "bundled modules were $_modules" fi if [[ $2 ]]; then \cp $tmp_file $output else echo -e "$(cat $tmp_file)" fi rm -f $tmp_file; return 0 fi } # # if script was executed then call the function (return 0 2>/dev/null) || bundle $@