github.com/canonical/ubuntu-image@v0.0.0-20240430122802-2202fe98b290/tests/lib/external/snapd-testing-tools/tools/tests.cleanup (about) 1 #!/bin/bash -e 2 3 show_help() { 4 echo "usage: tests.cleanup defer <cmd> [args]" 5 echo " tests.cleanup pop" 6 echo " tests.cleanup restore" 7 echo 8 echo "COMMANDS:" 9 echo " restore: invokes all cleanup commands in reverse order" 10 echo " defer: pushes a command onto the cleanup stack" 11 echo " pop: invoke the most recently deferred command, discarding it" 12 echo 13 echo "The defer and pop commands can be to establish temporary" 14 echo "cleanup handler and remove it, in the case of success" 15 } 16 17 cmd_defer() { 18 if [ ! -e defer.sh ]; then 19 truncate --size=0 defer.sh 20 chmod +x defer.sh 21 fi 22 echo "$*" >> defer.sh 23 } 24 25 run_one_cmd() { 26 CMD="$1" 27 set +e 28 sh -ec "$CMD" 29 RET=$? 30 set -e 31 if [ $RET -ne 0 ]; then 32 echo "tests.cleanup: deferred command \"$CMD\" failed with exit code $RET" 33 exit $RET 34 fi 35 } 36 37 cmd_pop() { 38 if [ ! -s defer.sh ]; then 39 echo "tests.cleanup: cannot pop, cleanup stack is empty" >&2 40 exit 1 41 fi 42 head -n-1 defer.sh >defer.sh.pop 43 trap "mv defer.sh.pop defer.sh" EXIT 44 tail -n-1 defer.sh | while read -r CMD; do 45 run_one_cmd "$CMD" 46 done 47 } 48 49 cmd_restore() { 50 if [ -e defer.sh ]; then 51 tac defer.sh | while read -r CMD; do 52 run_one_cmd "$CMD" 53 done 54 rm -f defer.sh 55 fi 56 } 57 58 main() { 59 if [ $# -eq 0 ]; then 60 show_help 61 exit 62 fi 63 64 while [ $# -gt 0 ]; do 65 case "$1" in 66 -h|--help) 67 show_help 68 exit 69 ;; 70 defer) 71 shift 72 cmd_defer "$@" 73 exit 74 ;; 75 pop) 76 shift 77 cmd_pop "$@" 78 exit 79 ;; 80 restore) 81 shift 82 cmd_restore 83 exit 84 ;; 85 -*) 86 echo "tests.cleanup: unknown option $1" >&2 87 exit 1 88 ;; 89 *) 90 echo "tests.cleanup: unknown command $1" >&2 91 exit 1 92 ;; 93 esac 94 done 95 } 96 97 main "$@"