-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhighlight
executable file
·405 lines (348 loc) · 13.4 KB
/
highlight
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/env bb
;; Generated by uberscriptify, do not edit directly.
(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 scribe.highlight
"Utilities for highlighting portions of strings with color. Primary
entrypoint is the `add` function."
(:require [clojure.string :as string]))
;; RGB color selection and DJB2 hashing is a direct port from the original
;; batchcolor. All credit for it's coolness goes to Steve Losh. Any bugs are mine.
(defn rgb-code
"Generate 8-bit RGB code.
From: https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit"
[r g b]
(+ (* r 36)
(* g 6)
(* b 1)
16))
(defn- make-colors
[include-fn]
(for [r (range 6)
g (range 6)
b (range 6)
:when (include-fn (+ r g b))]
(rgb-code r g b)))
;; Cut off the dark corner of the cube for dark terminals...
(def colors-for-dark
"Colors that look good on a dark terminal."
(make-colors #(> % 3)))
;; ...and cut off the light corner for light terminals
(def colors-for-light
"Colors that look good on a light terminal."
(make-colors #(< % 11)))
(defn- djb2
[string]
(reduce
(fn [h v]
(mod (+ (* 33 h) v) (Math/pow 2 32)))
5381
(map int string)))
;; End ported coolness from batchcolor.
(defn fg
"Return a string wrapped in the proper escape codes to set the foreground
color in the passed string."
[string color-code]
(format "\033[38;5;%dm%s\033[0m" color-code string))
(defn bg
"Return a string wrapped in the proper escape codes to set the background
color in the passed string."
[string color-code]
(format "\033[48;5;%dm%s\033[0m" color-code string))
(defn- wrap
[match opts]
(let [{:keys [reverse? offset colors explicit]} opts
string (cond-> match
(vector? match) first)
color (or (get explicit string)
(nth colors
(mod (cond-> string
reverse? reverse
:always djb2
offset (+ offset))
(count colors))))]
(fg string color)))
(def default-opts
"Default options for add function."
{:colors :colors-for-dark
:explicit {}
:offset 0
:reverse? false})
(def ^:private keyword-colors
{:colors-for-dark colors-for-dark
:colors-for-light colors-for-light})
(defn- finalize-opts
[opts]
(-> (merge default-opts opts)
(update :colors (fn [color-opt]
(let [default-colors (keyword-colors (:colors default-opts))]
(cond
(coll? color-opt) color-opt
(keyword? color-opt) (or (keyword-colors color-opt) default-colors)
:else default-colors))))))
(defn add
"Highlight regex matches in line string by adding color. All instances of the
same match are colored the same. The color is picked by hashing the match
into an index into available colors, which makes the coloring stable across
multiple runs.
Options include:
* `:colors` - Which set of colors to use. Can be either a keyword or vector
of colors. Default is colors suitable for a dark background
(`:colors-for-dark`). For light backgrounds, use `:colors-for-light`.
* `:explicit` - Explicit colors for specific matched strings. Map of string to
color code.
* `:offset` - Additional offset after calculating color code. Defaults to 0.
* `:reverse?` - Should matches be reversed before selecting a color. Setting
this to true can help differentiate matches that share a common
prefix."
([string regex]
(add string regex nil))
([string regex opts]
(let [final-opts (finalize-opts opts)]
(string/replace string regex #(wrap % final-opts)))))
(ns highlight
(:require [clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]]
[scribe.highlight :as highlight]
[scribe.opts :as opts]
[scribe.string]))
(def cli-options
[["-h" "--help" "Show help."]
[nil "--dark" "Use dark mode. (default)"
:default-desc ""
:default true]
[nil "--light" "Use light mode."]
["-o" "--offset OFFSET" "Specify the color offset. (default: 0)"
:default 0
:default-desc ""
:parse-fn parse-long]
["-r" "--randomize-offset" "Randomize the color offset."]
["-R" "--reverse" "Reverse matched strings before assigning a color."
:default-desc ""
:default false]
["-e" "--explicit R,G,B:STRING" "Colorize a match explicitly."
:default []
:default-desc ""
:update-fn conj
:multi true]
[nil "--print-colors" "Print color reference."]])
(defn parse-explicit
[opt]
(let [[_ r g b m1] (re-matches #"([0-5]),([0-5]),([0-5]):(.*)" opt)
[_ rgb m2] (re-matches #"(\d{1,3}):(.*)" opt)]
(cond
rgb {:match m2 :rgb-code (parse-long rgb)}
(and r g b) {:match m1 :rgb-code (highlight/rgb-code (parse-long r)
(parse-long g)
(parse-long b))})))
(def usage
"Colorize matches in streaming text.
highlight takes a regular expression and highlights any matches in piped
input. Each match string gets a unique color, making it useful for quickly
categorizing information.
For example, to compare sha256 sums and identify identical files:
sha256sum * | highlight '[0-9a-ef]{40,}'
Or, to track IP addresses in a request log:
tail -F /var/log/apache/access_log | highlight '\\d+\\.\\d+\\.\\d+\\.\\d+'
highlight picks colors by hashing matches and using that to index into a set
of colors. Two different sets of colors are supported, one for light
backgrounds and one for dark backgrounds. By default, colors that will look
good on dark backgrounds are used. This indexing will be consistent between
runs and can be altered via the --offset and --randomize-offset flags.
Due to highlight's hashing, it will pick adjacent colors for strings that have
identical prefixes and only vary by a few characters. Since this can make
differentiating colors difficult, use the --reverse flag to reverse matches
before hashing. This will result in highlight selecting colors further apart.
A match's color can be explicitly specified with the --explicit flag. The
color can be specified by comma delimited triplet from 0-5 (e.g. 5,0,0) or
the RGB code directly (16-255).
tail -F foo.log | highlight 'WARN|INFO|ERROR' -e 160:ERROR -e 220:WARN -e 99:INFO
Use the --print-colors option to print a color table with numbers to use.
highlight is *heavily* inspired by batchcolor, as detailed in Steve Losh's
blog post: https://stevelosh.com/blog/2021/03/small-common-lisp-cli-programs/")
(defn find-errors
[parsed]
(or (opts/validate parsed usage)
(let [{:keys [arguments options]} parsed
{:keys [explicit]} options
regex (first arguments)
failed-explicits (remove parse-explicit explicit)]
(cond
(nil? regex)
{:message "Pass regex to match."
:exit 1}
(seq failed-explicits)
{:message (str "Bad explicit arguments: " (string/join ", " failed-explicits))
:exit 1}))))
(defn parsed->color-opts
[{:keys [options arguments]}]
(let [regex (some-> arguments first re-pattern)
{:keys [dark light offset randomize-offset reverse explicit]} options]
[regex
{:reverse? reverse
:explicit (->> (map parse-explicit explicit)
(reduce
(fn [r {:keys [match rgb-code]}]
(assoc r match rgb-code))
{}))
:offset (cond
randomize-offset (rand-int 256)
:else offset)
:colors (cond
light highlight/colors-for-light
dark highlight/colors-for-dark)}]))
(defn format-color
[bg-color fb-color string]
(-> string
(highlight/fg fb-color)
(highlight/bg bg-color)))
(defn print-colors
[]
(println "Base colors:")
(doseq [base (range 16)
:let [fb-color (if (< 7 base) 0 15)]]
(print (format-color base fb-color (format " %2s" base))))
(newline)
(newline)
(println "216 colors:")
(doseq [r (range 6)]
(doseq [g (range 6)]
(doseq [b (range 6)
:let [color (highlight/rgb-code r g b)
fb-color (if (< 2 g) 0 15)]]
(print (format-color color fb-color (format " %3s" color)))
(when (and (= g 5) (= b 5))
(newline)))))
(newline)
(println "Grayscale:")
(doseq [gray (range 232 256)
:let [fb-color (if (< 243 gray) 0 15)]]
(print (format-color gray fb-color (format " %3d" gray))))
(newline))
(defn -main [& args]
(let [parsed (parse-opts args cli-options)
[regex opts] (parsed->color-opts parsed)]
(cond
(-> parsed :options :print-colors)
(print-colors)
:else
(do
(some-> (find-errors parsed)
(opts/format-help parsed)
(opts/print-and-exit))
(loop []
(when-let [line (read-line)]
(println (highlight/add line regex opts))
(recur)))))))
(ns user (:require [highlight])) (apply highlight/-main *command-line-args*)