-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcomb
executable file
·233 lines (198 loc) · 6.89 KB
/
comb
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/bin/sh
#_(
"exec" "bb" "-I" "$0" "$@"
)
;; Generated by uberscriptify, do not edit directly.
(ns comb.template
"Clojure templating library."
(:refer-clojure :exclude [fn eval])
(:require [clojure.core :as core]))
(defn- read-source [source]
(if (string? source)
source
(slurp source)))
(def delimiters ["<%" "%>"])
(def parser-regex
(re-pattern
(str "(?s)\\A"
"(?:" "(.*?)"
(first delimiters) "(.*?)" (last delimiters)
")?"
"(.*)\\z")))
(defn emit-string [s]
(print "(print " (pr-str s) ")"))
(defn emit-expr [expr]
(if (.startsWith expr "=")
(print "(print " (subs expr 1) ")")
(print expr)))
(defn- parse-string [src]
(with-out-str
(print "(do ")
(loop [src src]
(let [[_ before expr after] (re-matches parser-regex src)]
(if expr
(do (emit-string before)
(emit-expr expr)
(recur after))
(do (emit-string after)
(print ")")))))))
(defn compile-fn [args src]
(core/eval
`(core/fn ~args
(with-out-str
~(-> src read-source parse-string read-string)))))
(defmacro fn
"Compile a template into a function that takes the supplied arguments. The
template source may be a string, or an I/O source such as a File, Reader or
InputStream."
[args source]
`(compile-fn '~args ~source))
(defn eval
"Evaluate a template using the supplied bindings. The template source may
be a string, or an I/O source such as a File, Reader or InputStream."
([source]
(eval source {}))
([source bindings]
(let [keys (map (comp symbol name) (keys bindings))
func (compile-fn [{:keys (vec keys)}] source)]
(func bindings))))
(ns scribe.string
"String utilities."
(:require [clojure.string :as string]))
(defn- find-indent
[string]
(let [candidate (->> (string/split-lines string)
(next)
(filter seq)
first)
[_ indent] (when candidate (re-matches #"^(\s+).*" candidate))]
indent))
(defn dedent
"Remove leading indent on strings. Typically called on strings defined in
scripts that are to be printed to the terminal. If leading indent is not
passed, it will be detected from the first line with leading whitespace."
([string]
(dedent (find-indent string) string))
([indent string]
(cond->> (string/split-lines string)
indent (map #(string/replace % (re-pattern (str "^" indent)) ""))
:always (string/join "\n"))))
(ns scribe.opts
"A set of functions to handle command line options in an opinionated
functional manner. Here is the general strategy:
1. Args are parsed by clojure.tools.cli.
2. The parsed args are examined for errors and the --help flag with a pure
function.
3. If errors are found, an appropriate message (optionally with usage) is
assembled with a pure function.
4. The message is printed and the script exits.
Most of the above is pure, and therefore testable. Here's an example main
function:
(defn -main
[& args]
(let [parsed (parse-opts args [[\"-h\" \"--help\" \"Show help\"]
[\"-n\" \"--name NAME\" \"Name to use\" :default \"world\"]])
{:keys [name]} (:options parsed)]
(or (some-> (opts/validate parsed usage-text)
(opts/format-help parsed)
(opts/print-and-exit))
(println \"Hello\" name))))
For a more complete sample script, check out `samples` in the repository."
(:require [babashka.tasks :as tasks]
[clojure.java.io :as io]
[clojure.string :as string]
[scribe.string]))
(defn validate
"Look for the most common of errors:
* `--help` was passed
* clojure.tools.cli detected errors
To detect other errors specific to a given script, wrap the call with an
`or`, like this:
(or (opts/validate parsed usage-text)
(script-specific-validate parsed))
The script-specific-validate function should return a map with information
about the error that occurred. The keys are:
* :message - (optional) Message to be printed
* :exit - The numeric exit code that should be returned
* :wrap-context - Whether or not to wrap the message with script help heading
and options documentation"
[parsed usage]
(let [{:keys [errors options]} parsed
{:keys [help]} options]
(cond
help
{:exit 0
:message usage
:wrap-context true}
errors
{:exit 1
:message (string/join "\n" errors)
:wrap-context true})))
(defn detect-script-name
"Detect the name of the currently running script, for usage in the printed
help."
([]
(or (some->> (tasks/current-task)
:name
(format "bb %s"))
(some-> (System/getProperty "babashka.file")
detect-script-name)
;; Fallback if we're using the REPL for development
"script"))
([filename]
(.getName (io/file filename))))
(def ^:private help-fmt
(scribe.string/dedent
"usage: %s [opts]
%s
options:
%s"))
(defn format-help
"Take an error (as returned from `validate`) and format the help message
that will be printed to the end user."
([errors parsed]
(format-help errors (detect-script-name) parsed))
([errors script-name-or-ns parsed]
(let [script-name (str script-name-or-ns)
{:keys [summary]} parsed
{:keys [message exit wrap-context]} errors
final-message (-> message
scribe.string/dedent
(string/replace "SCRIPT_NAME" script-name))]
{:help (if wrap-context
(format help-fmt script-name final-message summary)
final-message)
:exit exit})))
(defn print-and-exit
"Print help message and exit. Accepts a map with `:help`
and `:exit` keys.
Uses the :babashka/exit ex-info trick to exit Babashka."
[{:keys [help exit]}]
(throw (ex-info help {:babashka/exit exit})))
(ns comb
(:require
[clojure.tools.cli :refer [parse-opts]]
[scribe.opts :as opts]
[comb.template :as template]
[user])
(:gen-class))
(def script-name (opts/detect-script-name))
(def cli-options
[["-t" "--template TEMPLATE" "Template to process"]
["-s" "--show-data" "Print incoming data to stderr"]
["-h" "--help"]])
(defn process
[options data]
(let [{:keys [template show-data]} options]
(when show-data
(binding [*out* *err*] (println "data:" (pr-str data))))
(template/eval template data)))
(defn -main [& args]
(let [parsed (parse-opts args cli-options)
{:keys [options]} parsed]
(or (some-> (opts/validate parsed "Command line templating using the comb library.")
(opts/format-help script-name parsed)
(opts/print-and-exit))
(->> (map (partial process options) user/*input*)
(run! println)))))
(ns user (:require [comb])) (apply comb/-main *command-line-args*)