File: tests.cleanup

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (97 lines) | stat: -rwxr-xr-x 2,174 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/bin/bash -e

show_help() {
    echo "usage: tests.cleanup defer <cmd> [args]"
    echo "       tests.cleanup pop"
    echo "       tests.cleanup restore"
    echo
    echo "COMMANDS:"
    echo "  restore: invokes all cleanup commands in reverse order"
    echo "  defer: pushes a command onto the cleanup stack"
    echo "  pop: invoke the most recently deferred command, discarding it"
    echo
    echo "The defer and pop commands can be to establish temporary"
    echo "cleanup handler and remove it, in the case of success"
}

cmd_defer() {
    if [ ! -e defer.sh ]; then
        truncate --size=0 defer.sh
        chmod +x defer.sh
    fi
    echo "$*" >> defer.sh
}

run_one_cmd() {
    CMD="$1"
    set +e
    sh -ec "$CMD"
    RET=$?
    set -e
    if [ $RET -ne 0 ]; then
        echo "tests.cleanup: deferred command \"$CMD\" failed with exit code $RET"
        exit $RET
    fi
}

cmd_pop() {
    if [ ! -s defer.sh ]; then
        echo "tests.cleanup: cannot pop, cleanup stack is empty" >&2
        exit 1
    fi
    head -n-1 defer.sh >defer.sh.pop
    trap "mv defer.sh.pop defer.sh" EXIT
    tail -n-1 defer.sh | while read -r CMD; do
        run_one_cmd "$CMD"
    done
}

cmd_restore() {
    if [ -e defer.sh ]; then
        tac defer.sh | while read -r CMD; do
            run_one_cmd "$CMD"
        done
        rm -f defer.sh
    fi
}

main() {
    if [ $# -eq 0 ]; then
        show_help
        exit
    fi

    while [ $# -gt 0 ]; do
        case "$1" in
            -h|--help)
                show_help
                exit
                ;;
            defer)
                shift
                cmd_defer "$@"
                exit
                ;;
            pop)
                shift
                cmd_pop "$@"
                exit
                ;;
            restore)
                shift
                cmd_restore
                exit
                ;;
            -*)
                echo "tests.cleanup: unknown option $1" >&2
                exit 1
                ;;
            *)
                echo "tests.cleanup: unknown command $1" >&2
                exit 1
                ;;
        esac
    done
}

main "$@"