1#!/bin/bash
2########################################################################
3# Converts pikchr-format text files into a form usable by the
4# Fossil SCM's pikchrshow page's "example scripts" JS code.
5#
6# Usage: $0 [options] [file1.pikchr [...fileN.pikchr]]
7#
8# Options:
9#
10#  -o outfile, defaulting to /dev/stdout
11#
12# Its list of files defaults to $(ls -1 *.pikchr | sort).
13########################################################################
14
15function die(){
16    local rc=$1
17    shift
18    echo "$@" 1>&2
19    exit $rc
20}
21
22optOutfile=/dev/stdout
23scriptList=()
24while [[ x != "x$1" ]]; do
25    case "$1" in
26        -o) shift
27            optOutfile="$1"
28            shift
29            [[ x = "x${optOutfile}" ]] && die 1 "Missing filename for -o arg."
30            ;;
31        *) scriptList+=("$1")
32           shift
33    esac
34done
35
36[[ 0 = ${#scriptList[@]} ]] && {
37    scriptList=( $(ls -1 *.pikchr | sort) )
38    [[ 0 = ${#scriptList[@]} ]] && die 1 "Cannot find any *.pikchr files."
39}
40
41########################################################################
42# Optional *brief* user-friendly descriptive name of test files, in
43# the form desc_TESTNAME="name", where TESTNAME is the base filename
44# part of an input file. If none is set, the file is grepped for
45# a line with:
46#
47#  demo label: ...
48#
49# and if set, that is used. The default friendly name is that base
50# filename. These names are the ones shown in pikchrshow's example
51# script selection list.
52#desc_objects="Core object types"
53#desc_swimlane="Swimlanes"
54#desc_headings01="Cardinal headings"
55########################################################################
56
57#echo "scriptList=${scriptList[@]}"
58#echo optOutfile=${optOutfile}
59########################################################################
60# Output 1 JS object per file, comma-separated:
61#
62#  {name: "filename or desc_BASENAME value",
63#   code: `file content`}
64#
65# Note that the output is intended for embedding in an array but does
66# not emit the [...] part itself because of how its output is used.
67{
68    n=0 # object count
69    for f in ${scriptList[@]}; do
70        [[ -f "$f" ]] || die $? "Missing file: $f"
71        fb=${f%%.pikchr}
72        fb=${fb##*/}
73        descVar=desc_${fb}
74        desc=${!descVar}
75        if [[ x = "x${desc}" ]]; then
76            desc=$(awk -F: '/demo label: */{gsub(/^ /, "", $2); print $2}' < "$f")
77            if [[ x = "x${desc}" ]]; then
78                desc="$fb"
79            fi
80        fi
81        #echo f=${f} fb=${fb} descV=${descV} desc=$desc
82        [[ $n -gt 0 ]] && echo -n ","
83        echo -n '{name:"'${desc}'",'
84        echo -n 'code:`'
85        cat $f
86        echo -n '`}'
87        n=$((n + 1))
88    done
89    echo
90} > "${optOutfile}"
91#echo "Done: ${n} file(s) processes. Output is in ${optOutfile}."
92