: ' hook.sketch.prebuild process copies of sketch and replace some vars text wise. Date Version Comment 2018-12-22 1.0 initial version ' #set -x # saner programming env: these switches turn some bugs into errors set -o errexit -o pipefail -o noclobber -o nounset export PATH=/bin:/sbin:/usr/bin:/usr/sbin:$PATH echo Do some text templating... # Option handling as lined out by # https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash OPTIONS=v LONGOPTS=build.path:,build.project_name:,verbose # -use ! and PIPESTATUS to get exit code with errexit set # -temporarily store output to be able to check for errors # -activate quoting/enhanced mode (e.g. by writing out “--options”) # -pass arguments only via -- "$@" to separate them correctly ! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@") if [[ ${PIPESTATUS[0]} -ne 0 ]]; then # e.g. return value is 1 # then getopt has complained about wrong arguments to stdout exit 2 fi # read getopt’s output this way to handle the quoting right: eval set -- "$PARSED" verbose=0 # process each found option while true; do case "$1" in -v|--verbose) let verbose+=1 shift ;; --build.path) buildPath=$( cygpath $2 ) shift 2 ;; --build.project_name) buildProjectName=$2 shift 2 ;; --) shift break ;; *) echo Programming error: $1. exit -1 ;; esac done # End of option handling # Utilise json query tool to extract some elements sketchDir=$( jq -r .sketchLocation $buildPath/build.options.json ) sketchDir=$( dirname $sketchDir ) if [ ! -f "$sketchDir/hook.sketch.prebuild.template.txt" ]; then (( $verbose )) && echo "$sketchDir\\hook.sketch.prebuild.template.txt does not exist. No templating requested." exit 0 else (( $verbose )) && echo "$sketchDir\\hook.sketch.prebuild.template.txt found. Let's go to work." fi for file in $( find $buildPath/sketch -type f \( -iname \*.h -o -iname \*.cpp \) ) ; do (( $verbose )) && echo Process file $file. # reset some variables for next run. # used to replace with same value for each ocurrence per file randomSame='' for var in $( grep -o "{{MY_.*}}" $file ) ; do # -o have grep print only the matches not the whole line. (( $verbose )) && echo -n "Replace $var with " case "$var" in {{MY_RANDOM}} ) rnd=$RANDOM (( $verbose )) && echo "$rnd." sed -i -e "0,/$var/s//$rnd/" $file # -i for inplace operation. Changes the file itself directly # only replace the first ocurrence ;; {{MY_RANDOM_SAME}} ) # if randomSame is already non zero skip this branch as all replacements have been made on first run. if [ -z $randomSame ]; then randomSame=$RANDOM (( $verbose )) && echo "$randomSame." sed -i -e "s/$var/$randomSame/g" $file # -i in place operation. # replace all ocurrences else (( $verbose )) && echo "$randomSame." fi ;; *) echo Unknown variable to replace: $var. exit -1 ;; esac done # for each template variable done # for each supported file (( $verbose )) && echo Templating done.