-
Notifications
You must be signed in to change notification settings - Fork 1
/
bl
executable file
·65 lines (58 loc) · 2.48 KB
/
bl
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
#!/usr/bin/env bb
;; vim: set filetype=clojure:
;; (b)abashka (l)aunch - Launches a bb command quickly by matching on start
;; of command after `bb-`.
;; bb commands assumed to start with `bb-`.
;; Example: `bl t -h` -> bb-table -h
(ns bl
(:require [clojure.java.io :as io]
[babashka.tasks :refer [shell]]
[clojure.string :as str]))
(defn- match-alias
"Tries matching a query substring on a list of potential candidates. The following
approaches are tried in order:
* Match full word on first letter of each clojure cased word of a candidate e.g.
gr -> github-repo but not grep-result-frequencies
* Same as last match but match on partial word e.g. gp -> github-pr-for-commit
* Match on start of candidate e.g. ta -> table"
[query candidates]
(let [full-clojure-case-abbrev
(let [match-regex (re-pattern (str "^bb-"
(->> query seq (map #(str % "[^-]+")) (str/join "-"))
"$"))]
#(re-find match-regex %))
matches (filterv full-clojure-case-abbrev candidates)]
(if (= 1 (count matches))
matches
(let [partial-clojure-case-abbrev
(let [match-regex (re-pattern (str "^bb-"
(->> query seq (map #(str % "[^-]+")) (str/join "-"))))]
#(re-find match-regex %))
matches_ (filterv partial-clojure-case-abbrev candidates)]
(if (= 1 (count matches_))
matches_
(filterv #(str/starts-with? % (str "bb-" query)) candidates))))))
(defn -main [args]
(let [bb-commands (->> (str/split (System/getenv "PATH") #":")
distinct
(mapcat (fn [path] (seq (.list (io/file path)))))
(filter #(str/starts-with? % "bb-")))
cmd-alias (first args)
cmds (match-alias cmd-alias bb-commands)
help-string (str "Available commands: " (str/join ", " bb-commands))]
(cond
(nil? cmd-alias)
(println help-string)
(zero? (count cmds))
(do
(println (str "Error: No commands matched for " (pr-str cmd-alias)
"\n" help-string))
(System/exit 1))
(> (count cmds) 1)
(do
(println (str "Error: More than one command matched for " (pr-str cmd-alias)
"\n" help-string))
(System/exit 1))
:else (do (apply shell (into cmds (rest args)))
nil))))
(-main *command-line-args*)