move shell common functions in a lib
[protos/libecoli.git] / examples / parse-yaml / parse-yaml.sh
1 #!/bin/sh
2
3 set -e
4
5 parse_yaml=ecoli-parse-yaml
6 libecoli=/usr/share/libecoli/ecoli.sh
7
8 usage()
9 {
10         cat <<- END_OF_HELP
11         This example demonstrates how to build an interactive command
12         line in a shell script, using a description in yaml format.
13
14         Usage: $0 [options...] [tests...]
15             -h
16                show this help
17             -p <path>
18                path to ecoli-parse-yaml binary (default is to search
19                in PATH).
20             -l <path>
21                path to libecoli.sh library (default is $libecoli)
22 END_OF_HELP
23 }
24
25 ARG=0
26 while getopts "hp:l:" opt; do
27         case "$opt" in
28         "h")
29                 usage
30                 exit 0
31                 ;;
32         "p")
33                 parse_yaml="$OPTARG"
34                 ;;
35         "l")
36                 libecoli="$OPTARG"
37                 ;;
38         esac
39 done
40
41 if ! command -v $parse_yaml > /dev/null 2> /dev/null && \
42                 ! readlink -e $parse_yaml > /dev/null 2> /dev/null; then
43         echo "Cannot find ecoli-parse-yaml ($parse_yaml)"
44         exit 1
45 fi
46 if ! readlink -e $libecoli > /dev/null 2> /dev/null; then
47         echo "Cannot find libecoli.sh ($libecoli)"
48         exit 1
49 fi
50
51 . $libecoli
52
53 yaml=$(mktemp)
54 cat << EOF > $yaml
55 type: or
56 children:
57 - type: seq
58   id: hello
59   help: Say hello to someone
60   children:
61   - type: str
62     string: hello
63   - type: or
64     id: name
65     help: Name of the person to greet
66     children:
67     - type: str
68       string: john
69     - type: str
70       string: mike
71 - type: seq
72   id: goodbye
73   help: Say good bye to someone
74   children:
75   - type: str
76     string: good
77   - type: str
78     string: bye
79   - type: or
80     id: name
81     help: Name of the person to greet
82     children:
83     - type: str
84       string: mary
85     - type: str
86       string: jessica
87 EOF
88
89 output=$(mktemp)
90 match=1
91 $parse_yaml -i $yaml -o $output || match=0
92 if [ "$match" = "1" ]; then
93         cat $output
94         . $output
95         name=$(ec_parse_get_str $(ec_parse_find_first ec_node1 name) 0)
96         hello=$(ec_parse_get_str $(ec_parse_find_first ec_node1 hello) 0)
97
98         if [ "$hello" != "" ]; then
99                 echo "$name says hello to you!"
100         else
101                 echo "$name says good bye to you!"
102         fi
103 else
104         echo "no match"
105 fi
106 rm $output
107 rm $yaml