Debian Codegraph @

src/clout/core.clj

raw
1 (ns clout.core
2 "A small language for routing."
3 (:require [clojure.string :as string]
4 [clojure.set :as set]
5 [instaparse.core :as insta]))
6
7 (def ^:private re-chars (set "\\.*+|?()[]{}$^"))
8
9 (defn- re-escape [s]
10 (string/escape s #(if (re-chars %) (str \\ %))))
11
12 (defn- re-groups* [^java.util.regex.Matcher matcher]
13 (for [i (range (.groupCount matcher))]
14 (.group matcher (int (inc i)))))
15
16 (defn- assoc-conj [m k v]
17 (assoc m k
18 (if-let [cur (get m k)]
19 (if (vector? cur)
20 (conj cur v)
21 [cur v])
22 v)))
23
24 (defn- assoc-keys-with-groups [groups keys]
25 (reduce (fn [m [k v]] (assoc-conj m k v))
26 {}
27 (map vector keys groups)))
28
29 (defn- request-url [request]
30 (str (name (:scheme request))
31 "://"
32 (get-in request [:headers "host"])
33 (:uri request)))
34
35 (defn- path-info [request]
36 (or (:path-info request)
37 (:uri request)))
38
39 (defprotocol Route
40 (route-matches [route request]
41 "If the route matches the supplied request, the matched keywords are
42 returned as a map. Otherwise, nil is returned."))
43
44 (defrecord CompiledRoute [source re keys absolute?]
45 Route
46 (route-matches [_ request]
47 (let [path-info (if absolute?
48 (request-url request)
49 (path-info request))
50 matcher (re-matcher re path-info)]
51 (if (.matches matcher)
52 (assoc-keys-with-groups (re-groups* matcher) keys))))
53 Object
54 (toString [_] source))
55
56 (def ^:private route-parser
57 (insta/parser
58 "route = (scheme / part) part*
59 scheme = #'(https?:)?//'
60
61 <part> = literal | escaped | wildcard | param
62 literal = #'(:[^\\p{L}_*{}\\\\]|[^:*{}\\\\])+'
63 escaped = #'\\\\.'
64 wildcard = '*'
65
66 param = key pattern?
67 key = <':'> #'([\\p{L}_][\\p{L}_0-9-]*)'
68 pattern = '{' (#'(?:[^{}\\\\]|\\\\.)+' | pattern)* '}'"
69 :no-slurp true))
70
71 (defn- parse [parser text]
72 (let [result (insta/parse parser text)]
73 (if (insta/failure? result)
74 (throw (ex-info "Parse error in route string" {:failure result}))
75 result)))
76
77 (defn- find-route-key [form]
78 (case (first form)
79 :wildcard :*
80 :param (-> form second second keyword)))
81
82 (defn- route-keys [parse-tree]
83 (->> (rest parse-tree)
84 (filter (comp #{:param :wildcard} first))
85 (map find-route-key)))
86
87 (defn- trim-pattern [pattern]
88 (some-> pattern (subs 1 (dec (count pattern)))))
89
90 (defn- param-regex [regexs key & [pattern]]
91 (str "(" (or (trim-pattern pattern) (regexs key) "[^/,;?]+") ")"))
92
93 (defn- route-regex [parse-tree regexs]
94 (insta/transform
95 {:route (comp re-pattern str)
96 :scheme #(if (= % "//") "https?://" %)
97 :literal re-escape
98 :escaped #(re-escape (subs % 1))
99 :wildcard (constantly "(.*?)")
100 :param (partial param-regex regexs)
101 :key keyword
102 :pattern str}
103 parse-tree))
104
105 (defn- absolute-url? [path]
106 (boolean (re-matches #"(https?:)?//.*" path)))
107
108 (defn route-compile
109 "Compile a route string for more efficient route matching."
110 ([path]
111 (route-compile path {}))
112 ([path regexs]
113 (let [ast (parse route-parser path)
114 ks (route-keys ast)]
115 (assert (set/subset? (set (keys regexs)) (set ks))
116 "unused keys in regular expression map")
117 (CompiledRoute.
118 path
119 (route-regex ast regexs)
120 (vec ks)
121 (absolute-url? path)))))
122
123 (extend-type String
124 Route
125 (route-matches [route request]
126 (route-matches (route-compile route) request)))