tg.sh: move tmpdir cleanup into its own function
[topgit/pro.git] / tg-shell.sh
blob02cfa2a82bceaefeda88c5a70b0c25951c510f26
1 #!/bin/sh
2 # TopGit wayback machine shell command
3 # (C) 2017 Kyle J. McKay <mackyle@gmail.com>
4 # All rights reserved
5 # GPLv2
7 USAGE="\
8 Usage: ${tgname:-tg} [...] -w [:]<tgtag> shell [--directory=<dirpath>] [-q] [--] [<arg>...]"
10 usage()
12 if [ "${1:-0}" != 0 ]; then
13 printf '%s\n' "$USAGE" >&2
14 else
15 printf '%s\n' "$USAGE"
17 exit ${1:-0}
20 quote=
22 while [ $# -gt 0 ]; do case "$1" in
23 -h|--help|--directory|--directory=*)
24 usage
26 --directory|--directory=*)
27 # only one is allowed and it should have been handled by tg.sh
28 # which means this is the second one and it's a usage error
29 usage 1
31 --quote|-q)
32 quote=1
34 --)
35 shift
36 break
38 -?*)
39 echo "Unknown option: $1" >&2
40 usage 1
43 break
45 esac; shift; done
46 [ -n "$wayback" ] || usage 1
48 # Everything's been handled by tg.sh except for verifying a TTY
49 # is present for an interactive shell
51 cmd=
52 redir=
53 theshell=@SHELL_PATH@
54 if [ $# -eq 0 ]; then
55 [ -z "$SHELL" ] || theshell="$SHELL"
56 test -t 0 || die "cannot use interactive wayback shell on non-TTY STDIN"
57 if test -t 1; then
58 test -t 2 || redir='2>&1'
59 elif test -t 2; then
60 redir='>&2'
61 else
62 die "cannot use interactive wayback shell on non-TTY STDOUT/STDERR"
64 PS1='[../${PWD##*/}] wayback$ ' && export PS1
65 wbname="${wayback#:}"
66 [ -n "$wbname" ] || wbname='now?!'
67 eval 'info "going wayback to $wbname..."' "$redir"
68 else
69 if [ -z "$quote" ]; then
70 cmd='-c "$*"'
71 else
72 # attempt to "quote" the arguments and then glue them together
73 cmdstr=
74 for cmdword in "$@"; do
75 cmdworddq=1
76 case "$cmdword" in [A-Za-z_]*)
77 if test z"${cmdword%%[!A-Za-z_0-9]*}" = z"$cmdword"
78 then
79 cmdworddq=
80 else case "$cmdword" in *=*)
81 cmdvar="${cmdword%%=*}"
82 if test z"${cmdvar%%[!A-Za-z_0-9]*}" = z"$cmdvar"
83 then
84 v_quotearg cmdword "${cmdword#*=}"
85 cmdword="$cmdvar=$cmdword"
86 cmdworddq=
88 esac; fi
89 esac
90 test z"$cmdworddq" = z || v_quotearg cmdword "$cmdword"
91 cmdstr="${cmdstr:+$cmdstr }$cmdword"
92 done
93 cmd='-c "$cmdstr"'
96 eval '"$theshell"' "$cmd" "$redir"