entities
listlengths 1
44.6k
| max_stars_repo_path
stringlengths 6
160
| max_stars_repo_name
stringlengths 6
66
| max_stars_count
int64 0
47.9k
| content
stringlengths 18
1.04M
| id
stringlengths 1
6
| new_content
stringlengths 18
1.04M
| modified
bool 1
class | references
stringlengths 32
1.52M
|
---|---|---|---|---|---|---|---|---|
[
{
"context": "t-token resp)]\n (client/post \"https://github.com/sesson\"\n {:form-params {:authenticity_toke",
"end": 445,
"score": 0.999419093132019,
"start": 439,
"tag": "USERNAME",
"value": "sesson"
},
{
"context": "mit \"Sign+in\"\n :login user\n :password pass\n ",
"end": 592,
"score": 0.6777974367141724,
"start": 588,
"tag": "USERNAME",
"value": "user"
},
{
"context": "login user\n :password pass\n :utf8 \"\\u2713\"}}))\n",
"end": 637,
"score": 0.998741626739502,
"start": 633,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": ":password pass\n :utf8 \"\\u2713\"}}))\n\n(defn build-url\n [day]\n (str \"http://adve",
"end": 681,
"score": 0.8776325583457947,
"start": 674,
"tag": "PASSWORD",
"value": "\"\\u2713"
}
] |
src/adventofcode2017/util.clj
|
wtneal/adventofcode2017
| 0 |
(ns adventofcode2017.util
(:require [clj-http.client :as client]
[net.cgrand.enlive-html :as html]))
(defn get-token
[resp]
(-> (:body)
(html/snippet)
(html/select [[:input (html/attr= :name "authenticity_token")]])
(get-in [:attrs :value])))
(defn login
[user pass]
(let [resp (client/get "https://adventofcode.com/auth/github")
token (get-token resp)]
(client/post "https://github.com/sesson"
{:form-params {:authenticity_token token
:commit "Sign+in"
:login user
:password pass
:utf8 "\u2713"}}))
(defn build-url
[day]
(str "http://adventofcode.com/2017/day/" day "/input"))
(defn scrape-input
[day]
(client/get (build-url day)))
|
76958
|
(ns adventofcode2017.util
(:require [clj-http.client :as client]
[net.cgrand.enlive-html :as html]))
(defn get-token
[resp]
(-> (:body)
(html/snippet)
(html/select [[:input (html/attr= :name "authenticity_token")]])
(get-in [:attrs :value])))
(defn login
[user pass]
(let [resp (client/get "https://adventofcode.com/auth/github")
token (get-token resp)]
(client/post "https://github.com/sesson"
{:form-params {:authenticity_token token
:commit "Sign+in"
:login user
:password <PASSWORD>
:utf8 <PASSWORD>"}}))
(defn build-url
[day]
(str "http://adventofcode.com/2017/day/" day "/input"))
(defn scrape-input
[day]
(client/get (build-url day)))
| true |
(ns adventofcode2017.util
(:require [clj-http.client :as client]
[net.cgrand.enlive-html :as html]))
(defn get-token
[resp]
(-> (:body)
(html/snippet)
(html/select [[:input (html/attr= :name "authenticity_token")]])
(get-in [:attrs :value])))
(defn login
[user pass]
(let [resp (client/get "https://adventofcode.com/auth/github")
token (get-token resp)]
(client/post "https://github.com/sesson"
{:form-params {:authenticity_token token
:commit "Sign+in"
:login user
:password PI:PASSWORD:<PASSWORD>END_PI
:utf8 PI:PASSWORD:<PASSWORD>END_PI"}}))
(defn build-url
[day]
(str "http://adventofcode.com/2017/day/" day "/input"))
(defn scrape-input
[day]
(client/get (build-url day)))
|
[
{
"context": ":sim/input-loc \"https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input",
"end": 4772,
"score": 0.9502385854721069,
"start": 4760,
"tag": "USERNAME",
"value": "yetanalytics"
},
{
"context": "{:select-agents\n #{\"mbox::mailto:[email protected]\"}\n :strip-ids? nil\n ",
"end": 4919,
"score": 0.9998690485954285,
"start": 4900,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": ":sim/input-loc \"https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input",
"end": 5337,
"score": 0.8933101892471313,
"start": 5325,
"tag": "USERNAME",
"value": "yetanalytics"
},
{
"context": "gents\n #{\"mbox::mailto:[email protected]\"}\n :strip-ids? nil\n ",
"end": 5504,
"score": 0.9998249411582947,
"start": 5485,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/onyx/com/yetanalytics/datasim/onyx/sim.clj
|
yetanalytics/datasim
| 12 |
(ns com.yetanalytics.datasim.onyx.sim
"Feed datasim seqs into onyx"
(:require [com.yetanalytics.datasim.sim :as sim]
[com.yetanalytics.datasim.input :as input]
[com.yetanalytics.datasim.onyx.util :as u]
[onyx.plugin.protocols :as p]
[clojure.core.async :as a]
[com.yetanalytics.datasim.util.sequence :as su]
[taoensso.timbre :refer [fatal infof debug warnf] :as timbre]))
(defn init-seq
[input
{:keys [select-agents
strip-ids?
remove-refs?
take-n
drop-n
batch-size]
:as args}
task-prefix
]
(lazy-seq
(cond->> (if select-agents
(sim/sim-seq
input
:select-agents select-agents)
(sim/sim-seq
input))
take-n (take take-n)
drop-n (drop (* drop-n batch-size))
strip-ids?
(map
#(dissoc % "id"))
remove-refs?
(remove
#(= "StatementRef"
(get-in % ["object" "objectType"])))
;; chop em up
batch-size
(partition-all batch-size)
batch-size
(map-indexed
(fn [idx statements]
{:task-prefix task-prefix
:chunk-idx (cond-> idx
drop-n (+ (quot drop-n batch-size)))
:range [(-> statements
first
meta
:timestamp-ms)
(-> statements
last
meta
:timestamp-ms)]
:statements (into []
(map
#(with-meta % nil)
statements))})))))
(defn inject-sim-input [_ {input-loc ::input-loc
select-agents ::select-agents
strip-ids? ::strip-ids?
remove-refs? ::remove-refs?
?take-n ::take-n
?drop-n ::drop-n
batch-size ::batch-size
:or {strip-ids? false
remove-refs? false
batch-size 1}
:as lifecycle}]
{:sim/input-loc input-loc
:sim/args {:select-agents select-agents
:strip-ids? strip-ids?
:remove-refs? remove-refs?
:take-n ?take-n
:drop-n ?drop-n
:batch-size batch-size}})
;; Onyx Plugin impl lets us do what we want
(defn plugin
[{:keys [onyx.core/task-map
sim/input-loc
sim/args
onyx.core/task
onyx.core/tenancy-id
onyx.core/job-id] :as event}]
(let [task-prefix (format "%s_%s_%s"
tenancy-id
job-id
(name task))
{?take-n :take-n} args
input (cond-> (input/from-location :input :json
input-loc)
?take-n (u/override-max! ?take-n))
rst (volatile! nil)
completed? (volatile! nil)
offset (volatile! nil)]
(reify
p/Plugin
(start [this event]
this)
(stop [this event]
(vreset! rst nil)
(vreset! completed? nil)
(vreset! offset nil)
this)
p/Checkpointed
(checkpoint [this]
@offset)
(recover! [this _ checkpoint]
(if (nil? checkpoint)
(do
(infof "DATASIM Input starting up...")
(vreset! rst (init-seq
input
args
task-prefix))
(vreset! completed? false)
(vreset! offset 0))
(do
(warnf "DATASIM recovering by dropping %d segments" checkpoint)
(vreset! rst (init-seq
input
(assoc args :drop-n checkpoint)
task-prefix))
(vreset! completed? false)
(vreset! offset checkpoint)))
this)
(checkpointed! [this epoch]) ;; TODO: keep a running log of n segs for replay, clear here
p/BarrierSynchronization
(synced? [this epoch]
true)
(completed? [this]
@completed?)
p/Input
(poll! [this _ timeout-ms]
(if-let [seg (first @rst)]
(do
(vswap! rst rest)
(vswap! offset inc)
seg)
(do (vreset! completed? true)
nil))))))
(def in-calls
{:lifecycle/before-task-start inject-sim-input})
(comment
(clojure.pprint/pprint
(time
(p/poll!
(plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:[email protected]"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})
nil nil
))
)
(let [reader (plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:[email protected]"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil
}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})]
(p/recover! reader nil nil)
(time
(dotimes [n 10000]
(when-not (p/poll! reader nil nil)
(print 'x))
(when (zero? (rem n 1000))
(println 'seg n 'checkpoint (p/checkpoint reader)))))
)
(def i (input/from-location :input :json "dev-resources/input/mom.json"))
(first (init-seq i {:batch-size 10} ""))
)
|
105363
|
(ns com.yetanalytics.datasim.onyx.sim
"Feed datasim seqs into onyx"
(:require [com.yetanalytics.datasim.sim :as sim]
[com.yetanalytics.datasim.input :as input]
[com.yetanalytics.datasim.onyx.util :as u]
[onyx.plugin.protocols :as p]
[clojure.core.async :as a]
[com.yetanalytics.datasim.util.sequence :as su]
[taoensso.timbre :refer [fatal infof debug warnf] :as timbre]))
(defn init-seq
[input
{:keys [select-agents
strip-ids?
remove-refs?
take-n
drop-n
batch-size]
:as args}
task-prefix
]
(lazy-seq
(cond->> (if select-agents
(sim/sim-seq
input
:select-agents select-agents)
(sim/sim-seq
input))
take-n (take take-n)
drop-n (drop (* drop-n batch-size))
strip-ids?
(map
#(dissoc % "id"))
remove-refs?
(remove
#(= "StatementRef"
(get-in % ["object" "objectType"])))
;; chop em up
batch-size
(partition-all batch-size)
batch-size
(map-indexed
(fn [idx statements]
{:task-prefix task-prefix
:chunk-idx (cond-> idx
drop-n (+ (quot drop-n batch-size)))
:range [(-> statements
first
meta
:timestamp-ms)
(-> statements
last
meta
:timestamp-ms)]
:statements (into []
(map
#(with-meta % nil)
statements))})))))
(defn inject-sim-input [_ {input-loc ::input-loc
select-agents ::select-agents
strip-ids? ::strip-ids?
remove-refs? ::remove-refs?
?take-n ::take-n
?drop-n ::drop-n
batch-size ::batch-size
:or {strip-ids? false
remove-refs? false
batch-size 1}
:as lifecycle}]
{:sim/input-loc input-loc
:sim/args {:select-agents select-agents
:strip-ids? strip-ids?
:remove-refs? remove-refs?
:take-n ?take-n
:drop-n ?drop-n
:batch-size batch-size}})
;; Onyx Plugin impl lets us do what we want
(defn plugin
[{:keys [onyx.core/task-map
sim/input-loc
sim/args
onyx.core/task
onyx.core/tenancy-id
onyx.core/job-id] :as event}]
(let [task-prefix (format "%s_%s_%s"
tenancy-id
job-id
(name task))
{?take-n :take-n} args
input (cond-> (input/from-location :input :json
input-loc)
?take-n (u/override-max! ?take-n))
rst (volatile! nil)
completed? (volatile! nil)
offset (volatile! nil)]
(reify
p/Plugin
(start [this event]
this)
(stop [this event]
(vreset! rst nil)
(vreset! completed? nil)
(vreset! offset nil)
this)
p/Checkpointed
(checkpoint [this]
@offset)
(recover! [this _ checkpoint]
(if (nil? checkpoint)
(do
(infof "DATASIM Input starting up...")
(vreset! rst (init-seq
input
args
task-prefix))
(vreset! completed? false)
(vreset! offset 0))
(do
(warnf "DATASIM recovering by dropping %d segments" checkpoint)
(vreset! rst (init-seq
input
(assoc args :drop-n checkpoint)
task-prefix))
(vreset! completed? false)
(vreset! offset checkpoint)))
this)
(checkpointed! [this epoch]) ;; TODO: keep a running log of n segs for replay, clear here
p/BarrierSynchronization
(synced? [this epoch]
true)
(completed? [this]
@completed?)
p/Input
(poll! [this _ timeout-ms]
(if-let [seg (first @rst)]
(do
(vswap! rst rest)
(vswap! offset inc)
seg)
(do (vreset! completed? true)
nil))))))
(def in-calls
{:lifecycle/before-task-start inject-sim-input})
(comment
(clojure.pprint/pprint
(time
(p/poll!
(plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:<EMAIL>"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})
nil nil
))
)
(let [reader (plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:<EMAIL>"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil
}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})]
(p/recover! reader nil nil)
(time
(dotimes [n 10000]
(when-not (p/poll! reader nil nil)
(print 'x))
(when (zero? (rem n 1000))
(println 'seg n 'checkpoint (p/checkpoint reader)))))
)
(def i (input/from-location :input :json "dev-resources/input/mom.json"))
(first (init-seq i {:batch-size 10} ""))
)
| true |
(ns com.yetanalytics.datasim.onyx.sim
"Feed datasim seqs into onyx"
(:require [com.yetanalytics.datasim.sim :as sim]
[com.yetanalytics.datasim.input :as input]
[com.yetanalytics.datasim.onyx.util :as u]
[onyx.plugin.protocols :as p]
[clojure.core.async :as a]
[com.yetanalytics.datasim.util.sequence :as su]
[taoensso.timbre :refer [fatal infof debug warnf] :as timbre]))
(defn init-seq
[input
{:keys [select-agents
strip-ids?
remove-refs?
take-n
drop-n
batch-size]
:as args}
task-prefix
]
(lazy-seq
(cond->> (if select-agents
(sim/sim-seq
input
:select-agents select-agents)
(sim/sim-seq
input))
take-n (take take-n)
drop-n (drop (* drop-n batch-size))
strip-ids?
(map
#(dissoc % "id"))
remove-refs?
(remove
#(= "StatementRef"
(get-in % ["object" "objectType"])))
;; chop em up
batch-size
(partition-all batch-size)
batch-size
(map-indexed
(fn [idx statements]
{:task-prefix task-prefix
:chunk-idx (cond-> idx
drop-n (+ (quot drop-n batch-size)))
:range [(-> statements
first
meta
:timestamp-ms)
(-> statements
last
meta
:timestamp-ms)]
:statements (into []
(map
#(with-meta % nil)
statements))})))))
(defn inject-sim-input [_ {input-loc ::input-loc
select-agents ::select-agents
strip-ids? ::strip-ids?
remove-refs? ::remove-refs?
?take-n ::take-n
?drop-n ::drop-n
batch-size ::batch-size
:or {strip-ids? false
remove-refs? false
batch-size 1}
:as lifecycle}]
{:sim/input-loc input-loc
:sim/args {:select-agents select-agents
:strip-ids? strip-ids?
:remove-refs? remove-refs?
:take-n ?take-n
:drop-n ?drop-n
:batch-size batch-size}})
;; Onyx Plugin impl lets us do what we want
(defn plugin
[{:keys [onyx.core/task-map
sim/input-loc
sim/args
onyx.core/task
onyx.core/tenancy-id
onyx.core/job-id] :as event}]
(let [task-prefix (format "%s_%s_%s"
tenancy-id
job-id
(name task))
{?take-n :take-n} args
input (cond-> (input/from-location :input :json
input-loc)
?take-n (u/override-max! ?take-n))
rst (volatile! nil)
completed? (volatile! nil)
offset (volatile! nil)]
(reify
p/Plugin
(start [this event]
this)
(stop [this event]
(vreset! rst nil)
(vreset! completed? nil)
(vreset! offset nil)
this)
p/Checkpointed
(checkpoint [this]
@offset)
(recover! [this _ checkpoint]
(if (nil? checkpoint)
(do
(infof "DATASIM Input starting up...")
(vreset! rst (init-seq
input
args
task-prefix))
(vreset! completed? false)
(vreset! offset 0))
(do
(warnf "DATASIM recovering by dropping %d segments" checkpoint)
(vreset! rst (init-seq
input
(assoc args :drop-n checkpoint)
task-prefix))
(vreset! completed? false)
(vreset! offset checkpoint)))
this)
(checkpointed! [this epoch]) ;; TODO: keep a running log of n segs for replay, clear here
p/BarrierSynchronization
(synced? [this epoch]
true)
(completed? [this]
@completed?)
p/Input
(poll! [this _ timeout-ms]
(if-let [seg (first @rst)]
(do
(vswap! rst rest)
(vswap! offset inc)
seg)
(do (vreset! completed? true)
nil))))))
(def in-calls
{:lifecycle/before-task-start inject-sim-input})
(comment
(clojure.pprint/pprint
(time
(p/poll!
(plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:PI:EMAIL:<EMAIL>END_PI"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})
nil nil
))
)
(let [reader (plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:PI:EMAIL:<EMAIL>END_PI"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil
}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})]
(p/recover! reader nil nil)
(time
(dotimes [n 10000]
(when-not (p/poll! reader nil nil)
(print 'x))
(when (zero? (rem n 1000))
(println 'seg n 'checkpoint (p/checkpoint reader)))))
)
(def i (input/from-location :input :json "dev-resources/input/mom.json"))
(first (init-seq i {:batch-size 10} ""))
)
|
[
{
"context": "leSpeed\"\n :min-rotation \"minRotation\"\n :name \"name\"\n :on \"on\"\n :on-destroy \"onDestroy\"\n :parti",
"end": 3382,
"score": 0.7594870328903198,
"start": 3378,
"tag": "NAME",
"value": "name"
}
] |
src/phzr/impl/accessors/particles/arcade/emitter.cljs
|
dparis/phzr
| 120 |
(ns phzr.impl.accessors.particles.arcade.emitter)
(def emitter-get-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bottom "bottom"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:left "left"
:length "length"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:parent "parent"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:right "right"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:stage "stage"
:top "top"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def emitter-set-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
|
64440
|
(ns phzr.impl.accessors.particles.arcade.emitter)
(def emitter-get-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bottom "bottom"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:left "left"
:length "length"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:parent "parent"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:right "right"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:stage "stage"
:top "top"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def emitter-set-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "<NAME>"
:on "on"
:on-destroy "onDestroy"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
| true |
(ns phzr.impl.accessors.particles.arcade.emitter)
(def emitter-get-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bottom "bottom"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:left "left"
:length "length"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:parent "parent"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:right "right"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:stage "stage"
:top "top"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def emitter-set-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "PI:NAME:<NAME>END_PI"
:on "on"
:on-destroy "onDestroy"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
|
[
{
"context": "is (= {:event :followed\n :handle \"@doofus\"\n :name \"Doofus\"}\n ",
"end": 4960,
"score": 0.9992132186889648,
"start": 4952,
"tag": "USERNAME",
"value": "\"@doofus"
},
{
"context": " :handle \"@doofus\"\n :name \"Doofus\"}\n (try-match* \"F @doofus Doofus\"",
"end": 4995,
"score": 0.8378555774688721,
"start": 4989,
"tag": "NAME",
"value": "Doofus"
}
] |
akar-core/test/akar/patterns_test.clj
|
missingfaktor/akar
| 194 |
(ns akar.patterns-test
(:require [akar.patterns :refer :all]
[akar.primitives :refer :all]
[akar.combinators :refer :all]
[clojure.test :refer :all]
[akar.test-support :refer :all])
(:import [clojure.lang Keyword]
[akar.test_support Add Sub Num Node]))
(deftest patterns-test
(testing "basic patterns"
(testing "!any"
(is (= :success
(match* :random-value (clauses*
!any (fn [] :success))))))
(testing "!pfail"
(is (= clause-not-applied
(try-match* :some-value (clauses*
!fail (fn [] :success))))))
(testing "!var"
(is (= :some-value
(match* :some-value (clauses*
!bind (fn [x] x))))))
(testing "!pred"
(let [!even (!pred even?)
!odd (!pred odd?)
block (clauses*
!even (fn [] :even)
!odd (fn [] :odd))]
(is (= :odd
(match* 9 block)))
(is (= :even
(match* 8 block)))))
(testing "!constant"
(let [block (clauses*
(!constant 4) (fn [] :fier)
(!constant 5) (fn [] :fünf))]
(is (= :fier
(match* 4 block)))
(is (= :fünf
(match* 5 block)))))
(testing "!some and !nil"
(let [block (clauses*
!some (fn [] :some)
!nil (fn [] :nil))]
(is (= :some
(match* 21 block)))
(is (= :nil
(match* nil block))))))
(testing "collection patterns"
(let [block (clauses*
!empty (fn [] :empty)
!cons (fn [hd tl] {:hd hd :tl tl})
!any (fn [] :not-sequential))]
(testing "!empty"
(is (= :empty
(match* [] block))))
(testing "!cons"
(is (= {:hd 3 :tl [4 5]}
(match* [3 4 5] block))))
(testing "non-sequential data fallthrough for both !empty and !cons"
(is (= :not-sequential
(match* :some-random-data block)))))
(let [block (clauses*
(!further-many !seq [!bind !any !bind]) (fn [a b] [a b]))]
(testing "!seq"
(is (= [2 4]
(match* [2 3 4] block)))))
(let [block (clauses*
(!and (!key "k") (!optional-key :l) (!optional-key :m)) (fn [a b c] [a b c])
!any (fn [] :stuff))]
(testing "!key and !optional-key, with regular maps"
(is (= [:x :y nil]
(match* {"k" :x :l :y} block)))
(is (= :stuff
(match* [] block)))))
(let [block (clauses*
(!key :tag) (fn [tag] tag)
(!optional-key :contents) (fn [contents] contents))]
(testing "!key and !optional-key, with records"
(is (= "i"
(match* (->Node "i" "k") block)))
(is (= "c"
(match* (->Node nil "c") block)))
(is (= nil
(match* (->Node nil nil) block)))))
(let [some-map {"XBD" 112}
block (clauses*
(!look-in some-map) (fn [v] v)
!any (fn [] :not-registered))]
(testing "!look-in"
(is (= 112
(match* "XBD" block)))
(is (= :not-registered
(match* "XKD" block)))))
(let [block (clauses*
(!further (!variant :add) [(!constant 0) !bind]) (fn [y] [:num y])
(!further (!variant :sub) [!bind (!constant 0)]) (fn [x] [:num x])
(!at (!variant :num)) (fn [node _] node))]
(testing "!variant"
(is (= [:num 3]
(match* [:add 0 3] block)))
(is (= [:num 5]
(match* [:sub 5 0] block)))
(is (= [:num 11]
(match* [:num 11] block)))))
(let [block (clauses*
(!further (!record Add) [(!constant 0) !bind]) (fn [y] (->Num y))
(!further (!record Sub) [!bind (!constant 0)]) (fn [x] (->Num x))
(!at (!record Num)) (fn [node _] node))]
(testing "!variant"
(is (= (->Num 3)
(match* (->Add 0 3) block)))
(is (= (->Num 5)
(match* (->Sub 5 0) block)))
(is (= (->Num 11)
(match* (->Num 11) block))))))
(testing "string patterns"
(testing "!regex"
(let [block (clauses*
(!regex #"^F (.*) (.*)$") (fn [handle name]
{:event :followed
:handle handle
:name name})
!any (fn [] :bad-event))]
(testing "captures values from a string that matches regex"
(is (= {:event :followed
:handle "@doofus"
:name "Doofus"}
(try-match* "F @doofus Doofus" block))))
(testing "doesn't match invalid strings"
(is (= :bad-event
(try-match* "F X" block))))
(testing "doesn't match non-strings"
(is (= :bad-event
(try-match* :not-even-a-string block)))))
(let [block (clauses*
(!regex #"^F [0-9]{1}$") (fn [] :match)
!any (fn [] :no-match))]
(testing "matches a string against a regex that captures nothing"
(is (= :match
(try-match* "F 7" block))))
(testing "doesn't match invalid srings"
(is (= :no-match
(try-match* "F 11" block)))))))
(testing "type-casing patterns"
(testing "!tag"
(let [block (clauses*
(!tag :some-tag) (fn [] :yes))]
(is (= :yes
(try-match* {:tag :some-tag} block)))))
(testing "!type"
(let [block (clauses*
(!and (!type :card) !bind) (fn [card] (:details card)))]
(is (= "Details"
(try-match* (with-meta {:details "Details"} {:type :card}) block)))))
(testing "!type - for class"
(let [block (clauses*
(!type String) (fn [] :string)
(!type Keyword) (fn [] :keyword)
(!type Exception) (fn [] :exception))]
(is (= :string
(try-match* "SomeString" block)))
(is (= :keyword
(try-match* :some-keyword block)))
(is (= :exception
(try-match* (RuntimeException.) block)))
(is (= clause-not-applied
(try-match* 4 block)))))))
|
30838
|
(ns akar.patterns-test
(:require [akar.patterns :refer :all]
[akar.primitives :refer :all]
[akar.combinators :refer :all]
[clojure.test :refer :all]
[akar.test-support :refer :all])
(:import [clojure.lang Keyword]
[akar.test_support Add Sub Num Node]))
(deftest patterns-test
(testing "basic patterns"
(testing "!any"
(is (= :success
(match* :random-value (clauses*
!any (fn [] :success))))))
(testing "!pfail"
(is (= clause-not-applied
(try-match* :some-value (clauses*
!fail (fn [] :success))))))
(testing "!var"
(is (= :some-value
(match* :some-value (clauses*
!bind (fn [x] x))))))
(testing "!pred"
(let [!even (!pred even?)
!odd (!pred odd?)
block (clauses*
!even (fn [] :even)
!odd (fn [] :odd))]
(is (= :odd
(match* 9 block)))
(is (= :even
(match* 8 block)))))
(testing "!constant"
(let [block (clauses*
(!constant 4) (fn [] :fier)
(!constant 5) (fn [] :fünf))]
(is (= :fier
(match* 4 block)))
(is (= :fünf
(match* 5 block)))))
(testing "!some and !nil"
(let [block (clauses*
!some (fn [] :some)
!nil (fn [] :nil))]
(is (= :some
(match* 21 block)))
(is (= :nil
(match* nil block))))))
(testing "collection patterns"
(let [block (clauses*
!empty (fn [] :empty)
!cons (fn [hd tl] {:hd hd :tl tl})
!any (fn [] :not-sequential))]
(testing "!empty"
(is (= :empty
(match* [] block))))
(testing "!cons"
(is (= {:hd 3 :tl [4 5]}
(match* [3 4 5] block))))
(testing "non-sequential data fallthrough for both !empty and !cons"
(is (= :not-sequential
(match* :some-random-data block)))))
(let [block (clauses*
(!further-many !seq [!bind !any !bind]) (fn [a b] [a b]))]
(testing "!seq"
(is (= [2 4]
(match* [2 3 4] block)))))
(let [block (clauses*
(!and (!key "k") (!optional-key :l) (!optional-key :m)) (fn [a b c] [a b c])
!any (fn [] :stuff))]
(testing "!key and !optional-key, with regular maps"
(is (= [:x :y nil]
(match* {"k" :x :l :y} block)))
(is (= :stuff
(match* [] block)))))
(let [block (clauses*
(!key :tag) (fn [tag] tag)
(!optional-key :contents) (fn [contents] contents))]
(testing "!key and !optional-key, with records"
(is (= "i"
(match* (->Node "i" "k") block)))
(is (= "c"
(match* (->Node nil "c") block)))
(is (= nil
(match* (->Node nil nil) block)))))
(let [some-map {"XBD" 112}
block (clauses*
(!look-in some-map) (fn [v] v)
!any (fn [] :not-registered))]
(testing "!look-in"
(is (= 112
(match* "XBD" block)))
(is (= :not-registered
(match* "XKD" block)))))
(let [block (clauses*
(!further (!variant :add) [(!constant 0) !bind]) (fn [y] [:num y])
(!further (!variant :sub) [!bind (!constant 0)]) (fn [x] [:num x])
(!at (!variant :num)) (fn [node _] node))]
(testing "!variant"
(is (= [:num 3]
(match* [:add 0 3] block)))
(is (= [:num 5]
(match* [:sub 5 0] block)))
(is (= [:num 11]
(match* [:num 11] block)))))
(let [block (clauses*
(!further (!record Add) [(!constant 0) !bind]) (fn [y] (->Num y))
(!further (!record Sub) [!bind (!constant 0)]) (fn [x] (->Num x))
(!at (!record Num)) (fn [node _] node))]
(testing "!variant"
(is (= (->Num 3)
(match* (->Add 0 3) block)))
(is (= (->Num 5)
(match* (->Sub 5 0) block)))
(is (= (->Num 11)
(match* (->Num 11) block))))))
(testing "string patterns"
(testing "!regex"
(let [block (clauses*
(!regex #"^F (.*) (.*)$") (fn [handle name]
{:event :followed
:handle handle
:name name})
!any (fn [] :bad-event))]
(testing "captures values from a string that matches regex"
(is (= {:event :followed
:handle "@doofus"
:name "<NAME>"}
(try-match* "F @doofus Doofus" block))))
(testing "doesn't match invalid strings"
(is (= :bad-event
(try-match* "F X" block))))
(testing "doesn't match non-strings"
(is (= :bad-event
(try-match* :not-even-a-string block)))))
(let [block (clauses*
(!regex #"^F [0-9]{1}$") (fn [] :match)
!any (fn [] :no-match))]
(testing "matches a string against a regex that captures nothing"
(is (= :match
(try-match* "F 7" block))))
(testing "doesn't match invalid srings"
(is (= :no-match
(try-match* "F 11" block)))))))
(testing "type-casing patterns"
(testing "!tag"
(let [block (clauses*
(!tag :some-tag) (fn [] :yes))]
(is (= :yes
(try-match* {:tag :some-tag} block)))))
(testing "!type"
(let [block (clauses*
(!and (!type :card) !bind) (fn [card] (:details card)))]
(is (= "Details"
(try-match* (with-meta {:details "Details"} {:type :card}) block)))))
(testing "!type - for class"
(let [block (clauses*
(!type String) (fn [] :string)
(!type Keyword) (fn [] :keyword)
(!type Exception) (fn [] :exception))]
(is (= :string
(try-match* "SomeString" block)))
(is (= :keyword
(try-match* :some-keyword block)))
(is (= :exception
(try-match* (RuntimeException.) block)))
(is (= clause-not-applied
(try-match* 4 block)))))))
| true |
(ns akar.patterns-test
(:require [akar.patterns :refer :all]
[akar.primitives :refer :all]
[akar.combinators :refer :all]
[clojure.test :refer :all]
[akar.test-support :refer :all])
(:import [clojure.lang Keyword]
[akar.test_support Add Sub Num Node]))
(deftest patterns-test
(testing "basic patterns"
(testing "!any"
(is (= :success
(match* :random-value (clauses*
!any (fn [] :success))))))
(testing "!pfail"
(is (= clause-not-applied
(try-match* :some-value (clauses*
!fail (fn [] :success))))))
(testing "!var"
(is (= :some-value
(match* :some-value (clauses*
!bind (fn [x] x))))))
(testing "!pred"
(let [!even (!pred even?)
!odd (!pred odd?)
block (clauses*
!even (fn [] :even)
!odd (fn [] :odd))]
(is (= :odd
(match* 9 block)))
(is (= :even
(match* 8 block)))))
(testing "!constant"
(let [block (clauses*
(!constant 4) (fn [] :fier)
(!constant 5) (fn [] :fünf))]
(is (= :fier
(match* 4 block)))
(is (= :fünf
(match* 5 block)))))
(testing "!some and !nil"
(let [block (clauses*
!some (fn [] :some)
!nil (fn [] :nil))]
(is (= :some
(match* 21 block)))
(is (= :nil
(match* nil block))))))
(testing "collection patterns"
(let [block (clauses*
!empty (fn [] :empty)
!cons (fn [hd tl] {:hd hd :tl tl})
!any (fn [] :not-sequential))]
(testing "!empty"
(is (= :empty
(match* [] block))))
(testing "!cons"
(is (= {:hd 3 :tl [4 5]}
(match* [3 4 5] block))))
(testing "non-sequential data fallthrough for both !empty and !cons"
(is (= :not-sequential
(match* :some-random-data block)))))
(let [block (clauses*
(!further-many !seq [!bind !any !bind]) (fn [a b] [a b]))]
(testing "!seq"
(is (= [2 4]
(match* [2 3 4] block)))))
(let [block (clauses*
(!and (!key "k") (!optional-key :l) (!optional-key :m)) (fn [a b c] [a b c])
!any (fn [] :stuff))]
(testing "!key and !optional-key, with regular maps"
(is (= [:x :y nil]
(match* {"k" :x :l :y} block)))
(is (= :stuff
(match* [] block)))))
(let [block (clauses*
(!key :tag) (fn [tag] tag)
(!optional-key :contents) (fn [contents] contents))]
(testing "!key and !optional-key, with records"
(is (= "i"
(match* (->Node "i" "k") block)))
(is (= "c"
(match* (->Node nil "c") block)))
(is (= nil
(match* (->Node nil nil) block)))))
(let [some-map {"XBD" 112}
block (clauses*
(!look-in some-map) (fn [v] v)
!any (fn [] :not-registered))]
(testing "!look-in"
(is (= 112
(match* "XBD" block)))
(is (= :not-registered
(match* "XKD" block)))))
(let [block (clauses*
(!further (!variant :add) [(!constant 0) !bind]) (fn [y] [:num y])
(!further (!variant :sub) [!bind (!constant 0)]) (fn [x] [:num x])
(!at (!variant :num)) (fn [node _] node))]
(testing "!variant"
(is (= [:num 3]
(match* [:add 0 3] block)))
(is (= [:num 5]
(match* [:sub 5 0] block)))
(is (= [:num 11]
(match* [:num 11] block)))))
(let [block (clauses*
(!further (!record Add) [(!constant 0) !bind]) (fn [y] (->Num y))
(!further (!record Sub) [!bind (!constant 0)]) (fn [x] (->Num x))
(!at (!record Num)) (fn [node _] node))]
(testing "!variant"
(is (= (->Num 3)
(match* (->Add 0 3) block)))
(is (= (->Num 5)
(match* (->Sub 5 0) block)))
(is (= (->Num 11)
(match* (->Num 11) block))))))
(testing "string patterns"
(testing "!regex"
(let [block (clauses*
(!regex #"^F (.*) (.*)$") (fn [handle name]
{:event :followed
:handle handle
:name name})
!any (fn [] :bad-event))]
(testing "captures values from a string that matches regex"
(is (= {:event :followed
:handle "@doofus"
:name "PI:NAME:<NAME>END_PI"}
(try-match* "F @doofus Doofus" block))))
(testing "doesn't match invalid strings"
(is (= :bad-event
(try-match* "F X" block))))
(testing "doesn't match non-strings"
(is (= :bad-event
(try-match* :not-even-a-string block)))))
(let [block (clauses*
(!regex #"^F [0-9]{1}$") (fn [] :match)
!any (fn [] :no-match))]
(testing "matches a string against a regex that captures nothing"
(is (= :match
(try-match* "F 7" block))))
(testing "doesn't match invalid srings"
(is (= :no-match
(try-match* "F 11" block)))))))
(testing "type-casing patterns"
(testing "!tag"
(let [block (clauses*
(!tag :some-tag) (fn [] :yes))]
(is (= :yes
(try-match* {:tag :some-tag} block)))))
(testing "!type"
(let [block (clauses*
(!and (!type :card) !bind) (fn [card] (:details card)))]
(is (= "Details"
(try-match* (with-meta {:details "Details"} {:type :card}) block)))))
(testing "!type - for class"
(let [block (clauses*
(!type String) (fn [] :string)
(!type Keyword) (fn [] :keyword)
(!type Exception) (fn [] :exception))]
(is (= :string
(try-match* "SomeString" block)))
(is (= :keyword
(try-match* :some-keyword block)))
(is (= :exception
(try-match* (RuntimeException.) block)))
(is (= clause-not-applied
(try-match* 4 block)))))))
|
[
{
"context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 28,
"score": 0.7669497132301331,
"start": 25,
"tag": "NAME",
"value": "Net"
}
] |
src/test/clojure/pigpen/functional/join_test.clj
|
magomimmo/PigPen
| 1 |
;;
;;
;; Copyright 2013 Netflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.join-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(deftest test-group-by
(let [data (pig/return [{:a 1 :b 2}
{:a 1 :b 3}
{:a 2 :b 4}])
command (pig/group-by :a data)]
(test-diff
(set (pig/dump command))
'#{[1 ({:a 1, :b 2} {:a 1, :b 3})]
[2 ({:a 2, :b 4})]})))
(deftest test-into
(let [data (pig/return [2 4 6])
command (pig/into [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(deftest test-reduce
(testing "conj"
(let [data (pig/return [2 4 6])
command (pig/reduce conj [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(testing "+"
(let [data (pig/return [2 4 6])
command (pig/reduce + data)]
(test-diff
(pig/dump command)
'[12]))))
(deftest test-fold
(let [data (pig/return [{:k :foo, :v 1}
{:k :foo, :v 2}
{:k :foo, :v 3}
{:k :bar, :v 4}
{:k :bar, :v 5}])]
(testing "inline sum"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn +
(fn [acc value]
(+ acc (:v value))))}))]
(is (= (set (pig/dump command))
'#{[:foo 6]
[:bar 9]}))))
(testing "inline count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn (fn ([] 0)
([a b] (+ a b)))
(fn [acc _] (inc acc)))}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]}))))
(testing "using fold/count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/count)}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]})))))
(testing "dual fold co-group"
(let [data0 (pig/return [{:k :foo, :a 1}
{:k :foo, :a 2}
{:k :foo, :a 3}
{:k :bar, :a 4}
{:k :bar, :a 5}])
data1 (pig/return [{:k :foo, :b 1}
{:k :foo, :b 2}
{:k :bar, :b 3}
{:k :bar, :b 4}
{:k :bar, :b 5}])
command (pig/cogroup [(data0 :on :k, :required true, :fold (->> (fold/map :a) (fold/sum)))
(data1 :on :k, :required true, :fold (->> (fold/map :b) (fold/sum)))]
vector)]
(is (= (set (pig/dump command))
'#{[:foo 6 3]
[:bar 9 12]}))))
(testing "fold all sum"
(let [data (pig/return [1 2 3 4])
command (pig/fold + data)]
(is (= (pig/dump command)
'[10]))))
(testing "fold all count"
(let [data (pig/return [1 2 3 4])
command (pig/fold (fold/count) data)]
(is (= (pig/dump command)
'[4])))))
(deftest test-cogroup
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :by :k :type :required)
(data2 :by :k :type :required)]
vector)))
'#{[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "self cogroup"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data)
(data)]
vector)]
(is (= (pig/dump command)
'[[2 (2) (2)] [0 (0) (0)] [1 (1) (1)]]))))
(testing "self cogroup with fold"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data :fold (fold/count))
(data :fold (fold/count))]
vector)]
(is (= (pig/dump command)
'[[2 1 1] [0 1 1] [1 1 1]]))))))
(deftest test-join
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner join - implicit :required"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k)
(data2 :on :k)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "inner"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "self join"
(let [data (pig/return [0 1 2])
command (pig/join [(data)
(data)]
vector)]
(is (= (pig/dump command)
[[2 2] [0 0] [1 1]]))))
(testing "key-selector defaults to identity"
(let [data1 (pig/return [1 2])
data2 (pig/return [2 3])
command (pig/join [(data1)
(data2)]
vector)]
(test-diff
(set (pig/dump command))
'#{[2 2]})))))
(deftest test-filter-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(pig/dump (pig/filter-by :k keys data))
'[{:k :i, :v 5}
{:k :i, :v 7}
{:k :i, :v 5}
{:k :i, :v 7}])))))
(deftest test-remove-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))))
|
5608
|
;;
;;
;; Copyright 2013 <NAME>flix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.join-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(deftest test-group-by
(let [data (pig/return [{:a 1 :b 2}
{:a 1 :b 3}
{:a 2 :b 4}])
command (pig/group-by :a data)]
(test-diff
(set (pig/dump command))
'#{[1 ({:a 1, :b 2} {:a 1, :b 3})]
[2 ({:a 2, :b 4})]})))
(deftest test-into
(let [data (pig/return [2 4 6])
command (pig/into [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(deftest test-reduce
(testing "conj"
(let [data (pig/return [2 4 6])
command (pig/reduce conj [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(testing "+"
(let [data (pig/return [2 4 6])
command (pig/reduce + data)]
(test-diff
(pig/dump command)
'[12]))))
(deftest test-fold
(let [data (pig/return [{:k :foo, :v 1}
{:k :foo, :v 2}
{:k :foo, :v 3}
{:k :bar, :v 4}
{:k :bar, :v 5}])]
(testing "inline sum"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn +
(fn [acc value]
(+ acc (:v value))))}))]
(is (= (set (pig/dump command))
'#{[:foo 6]
[:bar 9]}))))
(testing "inline count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn (fn ([] 0)
([a b] (+ a b)))
(fn [acc _] (inc acc)))}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]}))))
(testing "using fold/count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/count)}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]})))))
(testing "dual fold co-group"
(let [data0 (pig/return [{:k :foo, :a 1}
{:k :foo, :a 2}
{:k :foo, :a 3}
{:k :bar, :a 4}
{:k :bar, :a 5}])
data1 (pig/return [{:k :foo, :b 1}
{:k :foo, :b 2}
{:k :bar, :b 3}
{:k :bar, :b 4}
{:k :bar, :b 5}])
command (pig/cogroup [(data0 :on :k, :required true, :fold (->> (fold/map :a) (fold/sum)))
(data1 :on :k, :required true, :fold (->> (fold/map :b) (fold/sum)))]
vector)]
(is (= (set (pig/dump command))
'#{[:foo 6 3]
[:bar 9 12]}))))
(testing "fold all sum"
(let [data (pig/return [1 2 3 4])
command (pig/fold + data)]
(is (= (pig/dump command)
'[10]))))
(testing "fold all count"
(let [data (pig/return [1 2 3 4])
command (pig/fold (fold/count) data)]
(is (= (pig/dump command)
'[4])))))
(deftest test-cogroup
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :by :k :type :required)
(data2 :by :k :type :required)]
vector)))
'#{[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "self cogroup"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data)
(data)]
vector)]
(is (= (pig/dump command)
'[[2 (2) (2)] [0 (0) (0)] [1 (1) (1)]]))))
(testing "self cogroup with fold"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data :fold (fold/count))
(data :fold (fold/count))]
vector)]
(is (= (pig/dump command)
'[[2 1 1] [0 1 1] [1 1 1]]))))))
(deftest test-join
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner join - implicit :required"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k)
(data2 :on :k)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "inner"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "self join"
(let [data (pig/return [0 1 2])
command (pig/join [(data)
(data)]
vector)]
(is (= (pig/dump command)
[[2 2] [0 0] [1 1]]))))
(testing "key-selector defaults to identity"
(let [data1 (pig/return [1 2])
data2 (pig/return [2 3])
command (pig/join [(data1)
(data2)]
vector)]
(test-diff
(set (pig/dump command))
'#{[2 2]})))))
(deftest test-filter-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(pig/dump (pig/filter-by :k keys data))
'[{:k :i, :v 5}
{:k :i, :v 7}
{:k :i, :v 5}
{:k :i, :v 7}])))))
(deftest test-remove-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))))
| true |
;;
;;
;; Copyright 2013 PI:NAME:<NAME>END_PIflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.join-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(deftest test-group-by
(let [data (pig/return [{:a 1 :b 2}
{:a 1 :b 3}
{:a 2 :b 4}])
command (pig/group-by :a data)]
(test-diff
(set (pig/dump command))
'#{[1 ({:a 1, :b 2} {:a 1, :b 3})]
[2 ({:a 2, :b 4})]})))
(deftest test-into
(let [data (pig/return [2 4 6])
command (pig/into [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(deftest test-reduce
(testing "conj"
(let [data (pig/return [2 4 6])
command (pig/reduce conj [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(testing "+"
(let [data (pig/return [2 4 6])
command (pig/reduce + data)]
(test-diff
(pig/dump command)
'[12]))))
(deftest test-fold
(let [data (pig/return [{:k :foo, :v 1}
{:k :foo, :v 2}
{:k :foo, :v 3}
{:k :bar, :v 4}
{:k :bar, :v 5}])]
(testing "inline sum"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn +
(fn [acc value]
(+ acc (:v value))))}))]
(is (= (set (pig/dump command))
'#{[:foo 6]
[:bar 9]}))))
(testing "inline count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn (fn ([] 0)
([a b] (+ a b)))
(fn [acc _] (inc acc)))}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]}))))
(testing "using fold/count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/count)}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]})))))
(testing "dual fold co-group"
(let [data0 (pig/return [{:k :foo, :a 1}
{:k :foo, :a 2}
{:k :foo, :a 3}
{:k :bar, :a 4}
{:k :bar, :a 5}])
data1 (pig/return [{:k :foo, :b 1}
{:k :foo, :b 2}
{:k :bar, :b 3}
{:k :bar, :b 4}
{:k :bar, :b 5}])
command (pig/cogroup [(data0 :on :k, :required true, :fold (->> (fold/map :a) (fold/sum)))
(data1 :on :k, :required true, :fold (->> (fold/map :b) (fold/sum)))]
vector)]
(is (= (set (pig/dump command))
'#{[:foo 6 3]
[:bar 9 12]}))))
(testing "fold all sum"
(let [data (pig/return [1 2 3 4])
command (pig/fold + data)]
(is (= (pig/dump command)
'[10]))))
(testing "fold all count"
(let [data (pig/return [1 2 3 4])
command (pig/fold (fold/count) data)]
(is (= (pig/dump command)
'[4])))))
(deftest test-cogroup
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :by :k :type :required)
(data2 :by :k :type :required)]
vector)))
'#{[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "self cogroup"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data)
(data)]
vector)]
(is (= (pig/dump command)
'[[2 (2) (2)] [0 (0) (0)] [1 (1) (1)]]))))
(testing "self cogroup with fold"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data :fold (fold/count))
(data :fold (fold/count))]
vector)]
(is (= (pig/dump command)
'[[2 1 1] [0 1 1] [1 1 1]]))))))
(deftest test-join
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner join - implicit :required"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k)
(data2 :on :k)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "inner"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "self join"
(let [data (pig/return [0 1 2])
command (pig/join [(data)
(data)]
vector)]
(is (= (pig/dump command)
[[2 2] [0 0] [1 1]]))))
(testing "key-selector defaults to identity"
(let [data1 (pig/return [1 2])
data2 (pig/return [2 3])
command (pig/join [(data1)
(data2)]
vector)]
(test-diff
(set (pig/dump command))
'#{[2 2]})))))
(deftest test-filter-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(pig/dump (pig/filter-by :k keys data))
'[{:k :i, :v 5}
{:k :i, :v 7}
{:k :i, :v 5}
{:k :i, :v 7}])))))
(deftest test-remove-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))))
|
[
{
"context": "irect back\r\n to the login page.\"\r\n [{{username \"user-name\" password \"password\"} :multipart-params\r\n sess",
"end": 622,
"score": 0.9996725916862488,
"start": 613,
"tag": "USERNAME",
"value": "user-name"
},
{
"context": "login page.\"\r\n [{{username \"user-name\" password \"password\"} :multipart-params\r\n session ",
"end": 642,
"score": 0.9977691173553467,
"start": 634,
"tag": "PASSWORD",
"value": "password"
}
] |
src/clj/cwiki/routes/login.clj
|
clartaq/cwiki
| 3 |
;;;
;;; Routes for login, logout, etc.
;;;
(ns cwiki.routes.login
(:require [compojure.core :refer :all]
[cwiki.models.wiki-db :as db]
[cwiki.layouts.login :as login-layout]
[cwiki.util.req-info :as ri]
[ring.util.response :refer [redirect]]))
(defn get-login
"Gather user credentials for login."
[req]
(login-layout/login-page))
(defn post-login
"Check that the user name and password match credentials in the database.
If so, add the identity to the current session, otherwise redirect back
to the login page."
[{{username "user-name" password "password"} :multipart-params
session :session :as req}]
(if-let [user (db/get-user-by-username-and-password username password)]
; If authenticated
(let [identity (dissoc user :user_password)
new-session (assoc (redirect "/")
:session (assoc session :identity identity))]
(ri/save-session-info new-session)
new-session)
; Otherwise
(redirect "/login")))
(defn get-logout
"Ask the user to verify that they want to log out."
[req]
(login-layout/view-logout-page req))
(defn post-logout
"Log out the current user."
[{session :session}]
(let [new-session (assoc (redirect "/login")
:session (dissoc session :identity))]
(ri/save-session-info new-session)
new-session))
(defroutes login-routes
(GET "/login" [] get-login)
(POST "/login" [] post-login)
(GET "/logout" [] get-logout)
(POST "/logout" [] post-logout))
|
97629
|
;;;
;;; Routes for login, logout, etc.
;;;
(ns cwiki.routes.login
(:require [compojure.core :refer :all]
[cwiki.models.wiki-db :as db]
[cwiki.layouts.login :as login-layout]
[cwiki.util.req-info :as ri]
[ring.util.response :refer [redirect]]))
(defn get-login
"Gather user credentials for login."
[req]
(login-layout/login-page))
(defn post-login
"Check that the user name and password match credentials in the database.
If so, add the identity to the current session, otherwise redirect back
to the login page."
[{{username "user-name" password "<PASSWORD>"} :multipart-params
session :session :as req}]
(if-let [user (db/get-user-by-username-and-password username password)]
; If authenticated
(let [identity (dissoc user :user_password)
new-session (assoc (redirect "/")
:session (assoc session :identity identity))]
(ri/save-session-info new-session)
new-session)
; Otherwise
(redirect "/login")))
(defn get-logout
"Ask the user to verify that they want to log out."
[req]
(login-layout/view-logout-page req))
(defn post-logout
"Log out the current user."
[{session :session}]
(let [new-session (assoc (redirect "/login")
:session (dissoc session :identity))]
(ri/save-session-info new-session)
new-session))
(defroutes login-routes
(GET "/login" [] get-login)
(POST "/login" [] post-login)
(GET "/logout" [] get-logout)
(POST "/logout" [] post-logout))
| true |
;;;
;;; Routes for login, logout, etc.
;;;
(ns cwiki.routes.login
(:require [compojure.core :refer :all]
[cwiki.models.wiki-db :as db]
[cwiki.layouts.login :as login-layout]
[cwiki.util.req-info :as ri]
[ring.util.response :refer [redirect]]))
(defn get-login
"Gather user credentials for login."
[req]
(login-layout/login-page))
(defn post-login
"Check that the user name and password match credentials in the database.
If so, add the identity to the current session, otherwise redirect back
to the login page."
[{{username "user-name" password "PI:PASSWORD:<PASSWORD>END_PI"} :multipart-params
session :session :as req}]
(if-let [user (db/get-user-by-username-and-password username password)]
; If authenticated
(let [identity (dissoc user :user_password)
new-session (assoc (redirect "/")
:session (assoc session :identity identity))]
(ri/save-session-info new-session)
new-session)
; Otherwise
(redirect "/login")))
(defn get-logout
"Ask the user to verify that they want to log out."
[req]
(login-layout/view-logout-page req))
(defn post-logout
"Log out the current user."
[{session :session}]
(let [new-session (assoc (redirect "/login")
:session (dissoc session :identity))]
(ri/save-session-info new-session)
new-session))
(defroutes login-routes
(GET "/login" [] get-login)
(POST "/login" [] post-login)
(GET "/logout" [] get-logout)
(POST "/logout" [] post-logout))
|
[
{
"context": "hronosConnection\n {:url url\n :user user\n :password password}))\n",
"end": 705,
"score": 0.992661714553833,
"start": 701,
"tag": "USERNAME",
"value": "user"
},
{
"context": " {:url url\n :user user\n :password password}))\n",
"end": 729,
"score": 0.9932609796524048,
"start": 721,
"tag": "PASSWORD",
"value": "password"
}
] |
src/de/otto/machroput/chronos/connection.clj
|
otto-de/machroput
| 7 |
(ns de.otto.machroput.chronos.connection
(:require
[de.otto.machroput.utils.http-utils :refer :all]
[clojure.data.json :as json]))
(defn has-parent-dependency? [json]
(not (nil? (:parents json))))
(defprotocol ChronosApi
(create-new-app [self json]))
(defrecord ChronosConnection [url user password ]
ChronosApi
(create-new-app [self json]
(let [json-str (json/write-str json)]
(if (has-parent-dependency? json)
(a-json-request self POST "/scheduler/dependency" json-str)
(a-json-request self POST "/scheduler/iso8601" json-str)))))
(defn new-chronos-connection [{:keys [url user password]} ]
(map->ChronosConnection
{:url url
:user user
:password password}))
|
113803
|
(ns de.otto.machroput.chronos.connection
(:require
[de.otto.machroput.utils.http-utils :refer :all]
[clojure.data.json :as json]))
(defn has-parent-dependency? [json]
(not (nil? (:parents json))))
(defprotocol ChronosApi
(create-new-app [self json]))
(defrecord ChronosConnection [url user password ]
ChronosApi
(create-new-app [self json]
(let [json-str (json/write-str json)]
(if (has-parent-dependency? json)
(a-json-request self POST "/scheduler/dependency" json-str)
(a-json-request self POST "/scheduler/iso8601" json-str)))))
(defn new-chronos-connection [{:keys [url user password]} ]
(map->ChronosConnection
{:url url
:user user
:password <PASSWORD>}))
| true |
(ns de.otto.machroput.chronos.connection
(:require
[de.otto.machroput.utils.http-utils :refer :all]
[clojure.data.json :as json]))
(defn has-parent-dependency? [json]
(not (nil? (:parents json))))
(defprotocol ChronosApi
(create-new-app [self json]))
(defrecord ChronosConnection [url user password ]
ChronosApi
(create-new-app [self json]
(let [json-str (json/write-str json)]
(if (has-parent-dependency? json)
(a-json-request self POST "/scheduler/dependency" json-str)
(a-json-request self POST "/scheduler/iso8601" json-str)))))
(defn new-chronos-connection [{:keys [url user password]} ]
(map->ChronosConnection
{:url url
:user user
:password PI:PASSWORD:<PASSWORD>END_PI}))
|
[
{
"context": "21-riemann-by-stream/\n\n(def email (mailer {:from \"[email protected]\"\n :host \"mail.foo.com\"\n ",
"end": 398,
"score": 0.9999185800552368,
"start": 385,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :user \"foo\"\n :password \"bar\"}))\n",
"end": 507,
"score": 0.9994214773178101,
"start": 504,
"tag": "PASSWORD",
"value": "bar"
}
] |
mycorp/output/email.clj
|
mcorbin/riemann-configuration-example
| 1 |
(ns mycorp.output.email
"send email"
(:require [riemann.config :refer :all]
[riemann.streams :refer :all]
[riemann.test :refer :all]
[riemann.email :refer :all]
[clojure.tools.logging :refer :all]))
;; this stream can be used to send email
;; cf http://localhost:3000/posts/2017-05-21-riemann-by-stream/
(def email (mailer {:from "[email protected]"
:host "mail.foo.com"
:user "foo"
:password "bar"}))
|
110159
|
(ns mycorp.output.email
"send email"
(:require [riemann.config :refer :all]
[riemann.streams :refer :all]
[riemann.test :refer :all]
[riemann.email :refer :all]
[clojure.tools.logging :refer :all]))
;; this stream can be used to send email
;; cf http://localhost:3000/posts/2017-05-21-riemann-by-stream/
(def email (mailer {:from "<EMAIL>"
:host "mail.foo.com"
:user "foo"
:password "<PASSWORD>"}))
| true |
(ns mycorp.output.email
"send email"
(:require [riemann.config :refer :all]
[riemann.streams :refer :all]
[riemann.test :refer :all]
[riemann.email :refer :all]
[clojure.tools.logging :refer :all]))
;; this stream can be used to send email
;; cf http://localhost:3000/posts/2017-05-21-riemann-by-stream/
(def email (mailer {:from "PI:EMAIL:<EMAIL>END_PI"
:host "mail.foo.com"
:user "foo"
:password "PI:PASSWORD:<PASSWORD>END_PI"}))
|
[
{
"context": "-number port\n :database-name db\n :username username\n :password password}))\n\n(defstate db\n :start",
"end": 577,
"score": 0.9955787658691406,
"start": 569,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ase-name db\n :username username\n :password password}))\n\n(defstate db\n :start (let [{database-url :da",
"end": 601,
"score": 0.998691201210022,
"start": 593,
"tag": "PASSWORD",
"value": "password"
}
] |
src/rocket_link/db.clj
|
Seryiza/rocket-link
| 2 |
(ns rocket-link.db
(:require [mount.core :refer [defstate]]
[hikari-cp.core :as cp]
[rocket-link.config :refer [config]]
[clojure.string :as str]))
(defn url->opts [database-url]
(let [uri (java.net.URI. database-url)
path (.getPath uri)
host (.getHost uri)
port (.getPort uri)
[_ db] (re-find #"\/(.+)" path)
[username password] (str/split (.getUserInfo uri) #"\:")]
{:adapter "postgresql"
:server-name host
:port-number port
:database-name db
:username username
:password password}))
(defstate db
:start (let [{database-url :database-url} config
pool-opts (url->opts database-url)
datasource (cp/make-datasource pool-opts)]
{:datasource datasource})
:stop (-> db :datasource cp/close-datasource))
|
108641
|
(ns rocket-link.db
(:require [mount.core :refer [defstate]]
[hikari-cp.core :as cp]
[rocket-link.config :refer [config]]
[clojure.string :as str]))
(defn url->opts [database-url]
(let [uri (java.net.URI. database-url)
path (.getPath uri)
host (.getHost uri)
port (.getPort uri)
[_ db] (re-find #"\/(.+)" path)
[username password] (str/split (.getUserInfo uri) #"\:")]
{:adapter "postgresql"
:server-name host
:port-number port
:database-name db
:username username
:password <PASSWORD>}))
(defstate db
:start (let [{database-url :database-url} config
pool-opts (url->opts database-url)
datasource (cp/make-datasource pool-opts)]
{:datasource datasource})
:stop (-> db :datasource cp/close-datasource))
| true |
(ns rocket-link.db
(:require [mount.core :refer [defstate]]
[hikari-cp.core :as cp]
[rocket-link.config :refer [config]]
[clojure.string :as str]))
(defn url->opts [database-url]
(let [uri (java.net.URI. database-url)
path (.getPath uri)
host (.getHost uri)
port (.getPort uri)
[_ db] (re-find #"\/(.+)" path)
[username password] (str/split (.getUserInfo uri) #"\:")]
{:adapter "postgresql"
:server-name host
:port-number port
:database-name db
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}))
(defstate db
:start (let [{database-url :database-url} config
pool-opts (url->opts database-url)
datasource (cp/make-datasource pool-opts)]
{:datasource datasource})
:stop (-> db :datasource cp/close-datasource))
|
[
{
"context": "s metadata)}]\n [:meta {:name \"author\", :content \"Nurullah Akkaya\"}]\n [:link {:rel \"icon\", \n\t :href \"/images/favi",
"end": 368,
"score": 0.9998831152915955,
"start": 353,
"tag": "NAME",
"value": "Nurullah Akkaya"
},
{
"context": "py; 2018\" \n [:a {:href \"http://nakkaya.com\"} \" Nurullah Akkaya\"]]]]\n ;;\n ;;\n (if (= (:type metadata) :post) \n",
"end": 3247,
"score": 0.9998891949653625,
"start": 3232,
"tag": "NAME",
"value": "Nurullah Akkaya"
}
] |
resources/templates/default.clj
|
nakkaya/nakkaya.com
| 29 |
;;(doctype :xhtml-transitional)
[:html
{:xmlns "http://www.w3.org/1999/xhtml", :lang "en", :xml:lang "en"}
[:head
[:meta
{:http-equiv "content-type", :content "text/html; charset=UTF-8"}]
[:meta {:name "description", :content (:description metadata)}]
[:meta {:name "keywords", :content (:tags metadata)}]
[:meta {:name "author", :content "Nurullah Akkaya"}]
[:link {:rel "icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "shortcut icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "stylesheet", :type "text/css", :href "/default.css"}]
[:link
{:rel "alternate", :type "application/rss+xml",
:title (:site-title (static.config/config)), :href "/rss-feed"}]
(if (= (:type metadata) :post)
[:link {:rel "canonical"
:href (str "http://nakkaya.com" (:url metadata))}])
[:script {:src "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
:type "text/javascript"}]
[:title (:title metadata)]]
[:body
[:div
{:id "wrap"}
[:div
{:id "header"}
[:h1
[:a
{:href "/"}
"nakkaya"
[:span {:class "fade-small"} "dot"]
[:span {:class "fade"} "com"]]]
[:div
{:class "pages"}
[:a {:href "/", :class "page"} "Home"] " | "
[:a {:href "/projects.html", :class "page"} "Projects"] " | "
[:a {:href "/archives.html", :class "page"} "Archives"] " | "
[:a {:href "/tags/", :class "page"} "Tags"] " | "
[:a {:href "/contact.html", :class "page" :rel "author"} "About"]
[:form {:method "get"
:action "http://www.google.com/search" :id "searchform"}
[:div
[:input {:type "text" :name "q" :class "box" :id "s"}]
[:input {:type "hidden" :name "sitesearch"
:value "nakkaya.com"}]]]]]
[:div
{:id "content"}
[:div
{:id "post"}
(if (or (= (:type metadata) :post)
(= (:type metadata) :site))
[:h2 {:class "page-title"} (:title metadata)])
content
(if (= (:type metadata) :post)
(reduce
(fn[h v]
(conj h [:a {:href (str "/tags/#" v)} (str v " ")]))
[:div {:class "post-tags"} "Tags: "]
(.split (:tags metadata) " ")))]
(if (= (:type metadata) :post)
[:div
{:id "related"}
[:h3 {:class "random-posts"} "Random Posts"]
[:ul
{:class "posts"}
(map
#(let [f %
url (static.core/post-url f)
[metadata _] (static.io/read-doc f)
date (static.core/parse-date
"yyyy-MM-dd" "dd MMM yyyy"
(re-find #"\d*-\d*-\d*" (str f)))]
[:li [:span date] [:a {:href url} (:title metadata)]])
(take 5 (shuffle (static.io/list-files :posts))))]])
[:div {:id "disqus"}
(if (= (:type metadata) :post)
"<div id=\"disqus_thread\"></div><script type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/embed.js\"></script><noscript><a href=\"//disqus.com/forums/nakkaya/?url=ref\">View the discussion thread.</a></noscript><a href=\"//disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>")]]
[:div
{:id "footer"}
[:a {:href "/rss-feed"} " RSS Feed"]
[:p "© 2018"
[:a {:href "http://nakkaya.com"} " Nurullah Akkaya"]]]]
;;
;;
(if (= (:type metadata) :post)
"<script type=\"text/javascript\">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/get_num_replies.js' + query + '\"></' + 'script>');
})();
//]]>
</script>")]]
|
68244
|
;;(doctype :xhtml-transitional)
[:html
{:xmlns "http://www.w3.org/1999/xhtml", :lang "en", :xml:lang "en"}
[:head
[:meta
{:http-equiv "content-type", :content "text/html; charset=UTF-8"}]
[:meta {:name "description", :content (:description metadata)}]
[:meta {:name "keywords", :content (:tags metadata)}]
[:meta {:name "author", :content "<NAME>"}]
[:link {:rel "icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "shortcut icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "stylesheet", :type "text/css", :href "/default.css"}]
[:link
{:rel "alternate", :type "application/rss+xml",
:title (:site-title (static.config/config)), :href "/rss-feed"}]
(if (= (:type metadata) :post)
[:link {:rel "canonical"
:href (str "http://nakkaya.com" (:url metadata))}])
[:script {:src "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
:type "text/javascript"}]
[:title (:title metadata)]]
[:body
[:div
{:id "wrap"}
[:div
{:id "header"}
[:h1
[:a
{:href "/"}
"nakkaya"
[:span {:class "fade-small"} "dot"]
[:span {:class "fade"} "com"]]]
[:div
{:class "pages"}
[:a {:href "/", :class "page"} "Home"] " | "
[:a {:href "/projects.html", :class "page"} "Projects"] " | "
[:a {:href "/archives.html", :class "page"} "Archives"] " | "
[:a {:href "/tags/", :class "page"} "Tags"] " | "
[:a {:href "/contact.html", :class "page" :rel "author"} "About"]
[:form {:method "get"
:action "http://www.google.com/search" :id "searchform"}
[:div
[:input {:type "text" :name "q" :class "box" :id "s"}]
[:input {:type "hidden" :name "sitesearch"
:value "nakkaya.com"}]]]]]
[:div
{:id "content"}
[:div
{:id "post"}
(if (or (= (:type metadata) :post)
(= (:type metadata) :site))
[:h2 {:class "page-title"} (:title metadata)])
content
(if (= (:type metadata) :post)
(reduce
(fn[h v]
(conj h [:a {:href (str "/tags/#" v)} (str v " ")]))
[:div {:class "post-tags"} "Tags: "]
(.split (:tags metadata) " ")))]
(if (= (:type metadata) :post)
[:div
{:id "related"}
[:h3 {:class "random-posts"} "Random Posts"]
[:ul
{:class "posts"}
(map
#(let [f %
url (static.core/post-url f)
[metadata _] (static.io/read-doc f)
date (static.core/parse-date
"yyyy-MM-dd" "dd MMM yyyy"
(re-find #"\d*-\d*-\d*" (str f)))]
[:li [:span date] [:a {:href url} (:title metadata)]])
(take 5 (shuffle (static.io/list-files :posts))))]])
[:div {:id "disqus"}
(if (= (:type metadata) :post)
"<div id=\"disqus_thread\"></div><script type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/embed.js\"></script><noscript><a href=\"//disqus.com/forums/nakkaya/?url=ref\">View the discussion thread.</a></noscript><a href=\"//disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>")]]
[:div
{:id "footer"}
[:a {:href "/rss-feed"} " RSS Feed"]
[:p "© 2018"
[:a {:href "http://nakkaya.com"} " <NAME>"]]]]
;;
;;
(if (= (:type metadata) :post)
"<script type=\"text/javascript\">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/get_num_replies.js' + query + '\"></' + 'script>');
})();
//]]>
</script>")]]
| true |
;;(doctype :xhtml-transitional)
[:html
{:xmlns "http://www.w3.org/1999/xhtml", :lang "en", :xml:lang "en"}
[:head
[:meta
{:http-equiv "content-type", :content "text/html; charset=UTF-8"}]
[:meta {:name "description", :content (:description metadata)}]
[:meta {:name "keywords", :content (:tags metadata)}]
[:meta {:name "author", :content "PI:NAME:<NAME>END_PI"}]
[:link {:rel "icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "shortcut icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "stylesheet", :type "text/css", :href "/default.css"}]
[:link
{:rel "alternate", :type "application/rss+xml",
:title (:site-title (static.config/config)), :href "/rss-feed"}]
(if (= (:type metadata) :post)
[:link {:rel "canonical"
:href (str "http://nakkaya.com" (:url metadata))}])
[:script {:src "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
:type "text/javascript"}]
[:title (:title metadata)]]
[:body
[:div
{:id "wrap"}
[:div
{:id "header"}
[:h1
[:a
{:href "/"}
"nakkaya"
[:span {:class "fade-small"} "dot"]
[:span {:class "fade"} "com"]]]
[:div
{:class "pages"}
[:a {:href "/", :class "page"} "Home"] " | "
[:a {:href "/projects.html", :class "page"} "Projects"] " | "
[:a {:href "/archives.html", :class "page"} "Archives"] " | "
[:a {:href "/tags/", :class "page"} "Tags"] " | "
[:a {:href "/contact.html", :class "page" :rel "author"} "About"]
[:form {:method "get"
:action "http://www.google.com/search" :id "searchform"}
[:div
[:input {:type "text" :name "q" :class "box" :id "s"}]
[:input {:type "hidden" :name "sitesearch"
:value "nakkaya.com"}]]]]]
[:div
{:id "content"}
[:div
{:id "post"}
(if (or (= (:type metadata) :post)
(= (:type metadata) :site))
[:h2 {:class "page-title"} (:title metadata)])
content
(if (= (:type metadata) :post)
(reduce
(fn[h v]
(conj h [:a {:href (str "/tags/#" v)} (str v " ")]))
[:div {:class "post-tags"} "Tags: "]
(.split (:tags metadata) " ")))]
(if (= (:type metadata) :post)
[:div
{:id "related"}
[:h3 {:class "random-posts"} "Random Posts"]
[:ul
{:class "posts"}
(map
#(let [f %
url (static.core/post-url f)
[metadata _] (static.io/read-doc f)
date (static.core/parse-date
"yyyy-MM-dd" "dd MMM yyyy"
(re-find #"\d*-\d*-\d*" (str f)))]
[:li [:span date] [:a {:href url} (:title metadata)]])
(take 5 (shuffle (static.io/list-files :posts))))]])
[:div {:id "disqus"}
(if (= (:type metadata) :post)
"<div id=\"disqus_thread\"></div><script type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/embed.js\"></script><noscript><a href=\"//disqus.com/forums/nakkaya/?url=ref\">View the discussion thread.</a></noscript><a href=\"//disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>")]]
[:div
{:id "footer"}
[:a {:href "/rss-feed"} " RSS Feed"]
[:p "© 2018"
[:a {:href "http://nakkaya.com"} " PI:NAME:<NAME>END_PI"]]]]
;;
;;
(if (= (:type metadata) :post)
"<script type=\"text/javascript\">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/get_num_replies.js' + query + '\"></' + 'script>');
})();
//]]>
</script>")]]
|
[
{
"context": "[[eval]] which does\n all the job.\"\n\n {:author \"Adam Helinski\"}\n\n (:import (convex.core Block\n ",
"end": 1352,
"score": 0.9989499449729919,
"start": 1339,
"tag": "NAME",
"value": "Adam Helinski"
}
] |
project/cvm/src/clj/main/convex/cvm.clj
|
rosejn/convex.cljc
| 30 |
(ns convex.cvm
"Code execution in the CVM, altering state, and gaining insights.
Central entities of this namespaces are contextes and they can be created using [[ctx]].
All other functions revolve around them. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), old context must be discarded and only returned
one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of following steps:
| Step | Function | Does |
|---|---|---|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (eg. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "Adam Helinski"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl ErrorValue))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]))
(set! *warn-on-reflection*
true)
(declare juice-set
state-set)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates a \"fake\" context. Ideal for testing and repl'ing around.
An optional map of options may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.cvm/address` | Address of the executing account | Reserved address (an actor) |
| `:convex.cvm/state` | Genesis state | Initial state with Convex actors and libraries |
| `:convex.peer/key | Account key for the initial peer (see [[convex.cell/account-key]]) | Fake key, all 0's |"
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState [(or (:convex.peer/key option+)
($.cell/key ($.cell/blob (byte-array 32))))]))
(or (:convex.cvm/address option+)
Init/RESERVED_ADDRESS))))
(defn fork
"Duplicates the given [[ctx]] (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a `ctx` looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Like [[fork]] but switches the executing account.
Note: CVM log is lost."
^Context
[^Context ctx address]
(.forkWithAddress ctx
address))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
Returns the current exception or nil if `ctx` is not in such a state meaning that [[result]]
can be safely used.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
([^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
([^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn juice
"Returns the remaining amount of juice available for the executing account.
Also see [[juice-set]]."
[^Context ctx]
(.getJuice ctx))
(defn key
"Returns the key of the given `address` (or the address associated with `ctx`)."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx` (a CVM vector of size 2 vectors containing a logging address
and a logged value)."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp (Unix epoch in milliseconds as CVM long) assigned to the state in the given `ctx`.
Also see [[timestamp-set]]."
^CVMLong
[^Context ctx]
(-> ctx
state
.getTimeStamp))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `CVM symbol` -> `CVM value`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env [^ACell sym ^ACell value]]
(.assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
code))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Refills juice to maximum.
Also see [[juice-set]]."
^Context
[^Context ctx]
(juice-set ctx
Long/MAX_VALUE))
(defn juice-set
"Sets the juice of the given `ctx` to the requested `amount`.
Also see [[juice]], [[juice-refill]]."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
state
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/key ($.cell/blob (byte-array 32)))
($.cell/vector [])))
.getState)))
(defn undef
"Like calling `(undef sym)` in Convex Lisp, either in the current account or the given one, repeatedly
on any CVM symbol in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx object]
(.expand ctx
object)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Chains [[expand]] and [[compile]] in a slightly more efficient fashion than calling both separately."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx object]
(.expandCompile ctx
object)))
;;;;;;;;;; Pahse 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell`, going efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating explicitley).
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of CVM objects. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
|
74829
|
(ns convex.cvm
"Code execution in the CVM, altering state, and gaining insights.
Central entities of this namespaces are contextes and they can be created using [[ctx]].
All other functions revolve around them. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), old context must be discarded and only returned
one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of following steps:
| Step | Function | Does |
|---|---|---|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (eg. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "<NAME>"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl ErrorValue))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]))
(set! *warn-on-reflection*
true)
(declare juice-set
state-set)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates a \"fake\" context. Ideal for testing and repl'ing around.
An optional map of options may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.cvm/address` | Address of the executing account | Reserved address (an actor) |
| `:convex.cvm/state` | Genesis state | Initial state with Convex actors and libraries |
| `:convex.peer/key | Account key for the initial peer (see [[convex.cell/account-key]]) | Fake key, all 0's |"
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState [(or (:convex.peer/key option+)
($.cell/key ($.cell/blob (byte-array 32))))]))
(or (:convex.cvm/address option+)
Init/RESERVED_ADDRESS))))
(defn fork
"Duplicates the given [[ctx]] (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a `ctx` looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Like [[fork]] but switches the executing account.
Note: CVM log is lost."
^Context
[^Context ctx address]
(.forkWithAddress ctx
address))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
Returns the current exception or nil if `ctx` is not in such a state meaning that [[result]]
can be safely used.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
([^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
([^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn juice
"Returns the remaining amount of juice available for the executing account.
Also see [[juice-set]]."
[^Context ctx]
(.getJuice ctx))
(defn key
"Returns the key of the given `address` (or the address associated with `ctx`)."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx` (a CVM vector of size 2 vectors containing a logging address
and a logged value)."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp (Unix epoch in milliseconds as CVM long) assigned to the state in the given `ctx`.
Also see [[timestamp-set]]."
^CVMLong
[^Context ctx]
(-> ctx
state
.getTimeStamp))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `CVM symbol` -> `CVM value`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env [^ACell sym ^ACell value]]
(.assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
code))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Refills juice to maximum.
Also see [[juice-set]]."
^Context
[^Context ctx]
(juice-set ctx
Long/MAX_VALUE))
(defn juice-set
"Sets the juice of the given `ctx` to the requested `amount`.
Also see [[juice]], [[juice-refill]]."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
state
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/key ($.cell/blob (byte-array 32)))
($.cell/vector [])))
.getState)))
(defn undef
"Like calling `(undef sym)` in Convex Lisp, either in the current account or the given one, repeatedly
on any CVM symbol in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx object]
(.expand ctx
object)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Chains [[expand]] and [[compile]] in a slightly more efficient fashion than calling both separately."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx object]
(.expandCompile ctx
object)))
;;;;;;;;;; Pahse 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell`, going efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating explicitley).
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of CVM objects. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
| true |
(ns convex.cvm
"Code execution in the CVM, altering state, and gaining insights.
Central entities of this namespaces are contextes and they can be created using [[ctx]].
All other functions revolve around them. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), old context must be discarded and only returned
one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of following steps:
| Step | Function | Does |
|---|---|---|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (eg. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "PI:NAME:<NAME>END_PI"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl ErrorValue))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]))
(set! *warn-on-reflection*
true)
(declare juice-set
state-set)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates a \"fake\" context. Ideal for testing and repl'ing around.
An optional map of options may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.cvm/address` | Address of the executing account | Reserved address (an actor) |
| `:convex.cvm/state` | Genesis state | Initial state with Convex actors and libraries |
| `:convex.peer/key | Account key for the initial peer (see [[convex.cell/account-key]]) | Fake key, all 0's |"
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState [(or (:convex.peer/key option+)
($.cell/key ($.cell/blob (byte-array 32))))]))
(or (:convex.cvm/address option+)
Init/RESERVED_ADDRESS))))
(defn fork
"Duplicates the given [[ctx]] (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a `ctx` looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Like [[fork]] but switches the executing account.
Note: CVM log is lost."
^Context
[^Context ctx address]
(.forkWithAddress ctx
address))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
Returns the current exception or nil if `ctx` is not in such a state meaning that [[result]]
can be safely used.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
([^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
([^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn juice
"Returns the remaining amount of juice available for the executing account.
Also see [[juice-set]]."
[^Context ctx]
(.getJuice ctx))
(defn key
"Returns the key of the given `address` (or the address associated with `ctx`)."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx` (a CVM vector of size 2 vectors containing a logging address
and a logged value)."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp (Unix epoch in milliseconds as CVM long) assigned to the state in the given `ctx`.
Also see [[timestamp-set]]."
^CVMLong
[^Context ctx]
(-> ctx
state
.getTimeStamp))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `CVM symbol` -> `CVM value`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env [^ACell sym ^ACell value]]
(.assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
code))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Refills juice to maximum.
Also see [[juice-set]]."
^Context
[^Context ctx]
(juice-set ctx
Long/MAX_VALUE))
(defn juice-set
"Sets the juice of the given `ctx` to the requested `amount`.
Also see [[juice]], [[juice-refill]]."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
state
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/key ($.cell/blob (byte-array 32)))
($.cell/vector [])))
.getState)))
(defn undef
"Like calling `(undef sym)` in Convex Lisp, either in the current account or the given one, repeatedly
on any CVM symbol in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx object]
(.expand ctx
object)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Chains [[expand]] and [[compile]] in a slightly more efficient fashion than calling both separately."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx object]
(.expandCompile ctx
object)))
;;;;;;;;;; Pahse 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell`, going efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating explicitley).
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of CVM objects. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
|
[
{
"context": "ntext sub/spring-root server-key)\n {:keys [engine-version map-name maps mod-name mods]} (fx/sub-ctx context",
"end": 1883,
"score": 0.8053358197212219,
"start": 1869,
"tag": "KEY",
"value": "engine-version"
}
] |
src/clj/skylobby/fx/host_battle.clj
|
badosu/skylobby
| 7 |
(ns skylobby.fx.host-battle
(:require
[cljfx.api :as fx]
clojure.set
skylobby.fx
[skylobby.fx.sub :as sub]
[skylobby.fx.engines :refer [engines-view]]
[skylobby.fx.maps :refer [maps-view]]
[skylobby.fx.mods :refer [mods-view]]
[skylobby.util :as u]
[taoensso.tufte :as tufte]))
(set! *warn-on-reflection* true)
(def host-battle-window-width 700)
(def host-battle-window-height 400)
(def host-battle-window-keys
[:battle-password :battle-port :battle-title :by-server :by-spring-root :css :engine-filter :engine-version
:map-input-prefix :map-name :mod-filter :mod-name :selected-server-tab :servers
:show-host-battle-window :spring-isolation-dir])
(defn nat-cell [nat-type]
{:text (str nat-type ": " (case (int nat-type)
0 "none"
1 "Hole punching"
2 "Fixed source ports"
nil))})
(defn host-battle-window-impl
[{:fx/keys [context]
:keys [screen-bounds]}]
(let [
battle-password (fx/sub-val context :battle-password)
battle-port (fx/sub-val context :battle-port)
battle-nat-type (or (fx/sub-val context :battle-nat-type) 0)
battle-title (fx/sub-val context :battle-title)
engine-filter (fx/sub-val context :engine-filter)
map-input-prefix (fx/sub-val context :map-input-prefix)
mod-filter (fx/sub-val context :mod-filter)
server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub)
client-data (fx/sub-val context get-in [:by-server server-key :client-data])
scripttags (fx/sub-val context get-in [:by-server server-key :scripttags])
show-host-battle-window (fx/sub-val context :show-host-battle-window)
spring-root (fx/sub-ctx context sub/spring-root server-key)
{:keys [engine-version map-name maps mod-name mods]} (fx/sub-ctx context sub/spring-resources spring-root)
host-battle-action {:event/type :spring-lobby/host-battle
:host-battle-state
{:host-port battle-port
:title battle-title
:nat-type battle-nat-type
:battle-password battle-password
:engine-version engine-version
:map-name map-name
:mod-name mod-name
:mod-hash -1
:map-hash -1}
:client-data client-data
:scripttags scripttags
:use-git-mod-version (fx/sub-val context :use-git-mod-version)}]
{:fx/type :stage
:showing (boolean (and client-data show-host-battle-window))
:title (str u/app-name " Host Battle")
:icons skylobby.fx/icons
:on-close-request {:event/type :spring-lobby/dissoc
:key :show-host-battle-window}
:x (skylobby.fx/fitx screen-bounds)
:y (skylobby.fx/fity screen-bounds)
:width (skylobby.fx/fitwidth screen-bounds host-battle-window-width)
:height (skylobby.fx/fitheight screen-bounds host-battle-window-height)
:scene
{:fx/type :scene
:stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub)
:root
(if show-host-battle-window
{:fx/type :v-box
:style {:-fx-font-size 16}
:children
[
{:fx/type :label
:text (str " Spring root for this server: " spring-root)}
{:fx/type :label
:text " Battle Name: "}
{:fx/type :text-field
:text (str battle-title)
:prompt-text "Battle Title"
:on-action host-battle-action
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-title}}
{:fx/type :label
:text " Battle Password: "}
{:fx/type :text-field
:text (str battle-password)
:prompt-text "Battle Password"
:on-action host-battle-action
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-password}}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :label
:text " Port: "}
{:fx/type :text-field
:text (str battle-port)
:prompt-text "8452"
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-port}
:text-formatter
{:fx/type :text-formatter
:value-converter :integer
:value (int (or (u/to-number battle-port) 8452))}}]}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :label
:text " NAT Type: "}
{:fx/type :combo-box
:value battle-nat-type
:items [0 1 2]
:on-value-changed {:event/type :spring-lobby/assoc
:key :battle-nat-type}
:button-cell nat-cell
:cell-factory
{:fx/cell-type :list-cell
:describe nat-cell}}]}
{:fx/type engines-view
:engine-filter engine-filter
:engine-version engine-version
:flow false
:spring-isolation-dir spring-root}
{:fx/type mods-view
:flow false
:mod-filter mod-filter
:mod-name mod-name
:mods mods
:spring-isolation-dir spring-root}
{:fx/type maps-view
:flow false
:map-name map-name
:maps maps
:map-input-prefix map-input-prefix
:on-value-changed {:event/type :spring-lobby/assoc
:key :map-name}
:spring-isolation-dir spring-root}
{:fx/type :pane
:v-box/vgrow :always}
{:fx/type :button
:text "Host Battle"
:on-action host-battle-action}]}
{:fx/type :pane})}}))
(defn host-battle-window [state]
(tufte/profile {:dynamic? true
:id :skylobby/ui}
(tufte/p :host-battle-window
(host-battle-window-impl state))))
|
23794
|
(ns skylobby.fx.host-battle
(:require
[cljfx.api :as fx]
clojure.set
skylobby.fx
[skylobby.fx.sub :as sub]
[skylobby.fx.engines :refer [engines-view]]
[skylobby.fx.maps :refer [maps-view]]
[skylobby.fx.mods :refer [mods-view]]
[skylobby.util :as u]
[taoensso.tufte :as tufte]))
(set! *warn-on-reflection* true)
(def host-battle-window-width 700)
(def host-battle-window-height 400)
(def host-battle-window-keys
[:battle-password :battle-port :battle-title :by-server :by-spring-root :css :engine-filter :engine-version
:map-input-prefix :map-name :mod-filter :mod-name :selected-server-tab :servers
:show-host-battle-window :spring-isolation-dir])
(defn nat-cell [nat-type]
{:text (str nat-type ": " (case (int nat-type)
0 "none"
1 "Hole punching"
2 "Fixed source ports"
nil))})
(defn host-battle-window-impl
[{:fx/keys [context]
:keys [screen-bounds]}]
(let [
battle-password (fx/sub-val context :battle-password)
battle-port (fx/sub-val context :battle-port)
battle-nat-type (or (fx/sub-val context :battle-nat-type) 0)
battle-title (fx/sub-val context :battle-title)
engine-filter (fx/sub-val context :engine-filter)
map-input-prefix (fx/sub-val context :map-input-prefix)
mod-filter (fx/sub-val context :mod-filter)
server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub)
client-data (fx/sub-val context get-in [:by-server server-key :client-data])
scripttags (fx/sub-val context get-in [:by-server server-key :scripttags])
show-host-battle-window (fx/sub-val context :show-host-battle-window)
spring-root (fx/sub-ctx context sub/spring-root server-key)
{:keys [<KEY> map-name maps mod-name mods]} (fx/sub-ctx context sub/spring-resources spring-root)
host-battle-action {:event/type :spring-lobby/host-battle
:host-battle-state
{:host-port battle-port
:title battle-title
:nat-type battle-nat-type
:battle-password battle-password
:engine-version engine-version
:map-name map-name
:mod-name mod-name
:mod-hash -1
:map-hash -1}
:client-data client-data
:scripttags scripttags
:use-git-mod-version (fx/sub-val context :use-git-mod-version)}]
{:fx/type :stage
:showing (boolean (and client-data show-host-battle-window))
:title (str u/app-name " Host Battle")
:icons skylobby.fx/icons
:on-close-request {:event/type :spring-lobby/dissoc
:key :show-host-battle-window}
:x (skylobby.fx/fitx screen-bounds)
:y (skylobby.fx/fity screen-bounds)
:width (skylobby.fx/fitwidth screen-bounds host-battle-window-width)
:height (skylobby.fx/fitheight screen-bounds host-battle-window-height)
:scene
{:fx/type :scene
:stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub)
:root
(if show-host-battle-window
{:fx/type :v-box
:style {:-fx-font-size 16}
:children
[
{:fx/type :label
:text (str " Spring root for this server: " spring-root)}
{:fx/type :label
:text " Battle Name: "}
{:fx/type :text-field
:text (str battle-title)
:prompt-text "Battle Title"
:on-action host-battle-action
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-title}}
{:fx/type :label
:text " Battle Password: "}
{:fx/type :text-field
:text (str battle-password)
:prompt-text "Battle Password"
:on-action host-battle-action
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-password}}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :label
:text " Port: "}
{:fx/type :text-field
:text (str battle-port)
:prompt-text "8452"
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-port}
:text-formatter
{:fx/type :text-formatter
:value-converter :integer
:value (int (or (u/to-number battle-port) 8452))}}]}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :label
:text " NAT Type: "}
{:fx/type :combo-box
:value battle-nat-type
:items [0 1 2]
:on-value-changed {:event/type :spring-lobby/assoc
:key :battle-nat-type}
:button-cell nat-cell
:cell-factory
{:fx/cell-type :list-cell
:describe nat-cell}}]}
{:fx/type engines-view
:engine-filter engine-filter
:engine-version engine-version
:flow false
:spring-isolation-dir spring-root}
{:fx/type mods-view
:flow false
:mod-filter mod-filter
:mod-name mod-name
:mods mods
:spring-isolation-dir spring-root}
{:fx/type maps-view
:flow false
:map-name map-name
:maps maps
:map-input-prefix map-input-prefix
:on-value-changed {:event/type :spring-lobby/assoc
:key :map-name}
:spring-isolation-dir spring-root}
{:fx/type :pane
:v-box/vgrow :always}
{:fx/type :button
:text "Host Battle"
:on-action host-battle-action}]}
{:fx/type :pane})}}))
(defn host-battle-window [state]
(tufte/profile {:dynamic? true
:id :skylobby/ui}
(tufte/p :host-battle-window
(host-battle-window-impl state))))
| true |
(ns skylobby.fx.host-battle
(:require
[cljfx.api :as fx]
clojure.set
skylobby.fx
[skylobby.fx.sub :as sub]
[skylobby.fx.engines :refer [engines-view]]
[skylobby.fx.maps :refer [maps-view]]
[skylobby.fx.mods :refer [mods-view]]
[skylobby.util :as u]
[taoensso.tufte :as tufte]))
(set! *warn-on-reflection* true)
(def host-battle-window-width 700)
(def host-battle-window-height 400)
(def host-battle-window-keys
[:battle-password :battle-port :battle-title :by-server :by-spring-root :css :engine-filter :engine-version
:map-input-prefix :map-name :mod-filter :mod-name :selected-server-tab :servers
:show-host-battle-window :spring-isolation-dir])
(defn nat-cell [nat-type]
{:text (str nat-type ": " (case (int nat-type)
0 "none"
1 "Hole punching"
2 "Fixed source ports"
nil))})
(defn host-battle-window-impl
[{:fx/keys [context]
:keys [screen-bounds]}]
(let [
battle-password (fx/sub-val context :battle-password)
battle-port (fx/sub-val context :battle-port)
battle-nat-type (or (fx/sub-val context :battle-nat-type) 0)
battle-title (fx/sub-val context :battle-title)
engine-filter (fx/sub-val context :engine-filter)
map-input-prefix (fx/sub-val context :map-input-prefix)
mod-filter (fx/sub-val context :mod-filter)
server-key (fx/sub-ctx context skylobby.fx/selected-tab-server-key-sub)
client-data (fx/sub-val context get-in [:by-server server-key :client-data])
scripttags (fx/sub-val context get-in [:by-server server-key :scripttags])
show-host-battle-window (fx/sub-val context :show-host-battle-window)
spring-root (fx/sub-ctx context sub/spring-root server-key)
{:keys [PI:KEY:<KEY>END_PI map-name maps mod-name mods]} (fx/sub-ctx context sub/spring-resources spring-root)
host-battle-action {:event/type :spring-lobby/host-battle
:host-battle-state
{:host-port battle-port
:title battle-title
:nat-type battle-nat-type
:battle-password battle-password
:engine-version engine-version
:map-name map-name
:mod-name mod-name
:mod-hash -1
:map-hash -1}
:client-data client-data
:scripttags scripttags
:use-git-mod-version (fx/sub-val context :use-git-mod-version)}]
{:fx/type :stage
:showing (boolean (and client-data show-host-battle-window))
:title (str u/app-name " Host Battle")
:icons skylobby.fx/icons
:on-close-request {:event/type :spring-lobby/dissoc
:key :show-host-battle-window}
:x (skylobby.fx/fitx screen-bounds)
:y (skylobby.fx/fity screen-bounds)
:width (skylobby.fx/fitwidth screen-bounds host-battle-window-width)
:height (skylobby.fx/fitheight screen-bounds host-battle-window-height)
:scene
{:fx/type :scene
:stylesheets (fx/sub-ctx context skylobby.fx/stylesheet-urls-sub)
:root
(if show-host-battle-window
{:fx/type :v-box
:style {:-fx-font-size 16}
:children
[
{:fx/type :label
:text (str " Spring root for this server: " spring-root)}
{:fx/type :label
:text " Battle Name: "}
{:fx/type :text-field
:text (str battle-title)
:prompt-text "Battle Title"
:on-action host-battle-action
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-title}}
{:fx/type :label
:text " Battle Password: "}
{:fx/type :text-field
:text (str battle-password)
:prompt-text "Battle Password"
:on-action host-battle-action
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-password}}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :label
:text " Port: "}
{:fx/type :text-field
:text (str battle-port)
:prompt-text "8452"
:on-text-changed {:event/type :spring-lobby/assoc
:key :battle-port}
:text-formatter
{:fx/type :text-formatter
:value-converter :integer
:value (int (or (u/to-number battle-port) 8452))}}]}
{:fx/type :h-box
:alignment :center-left
:children
[
{:fx/type :label
:text " NAT Type: "}
{:fx/type :combo-box
:value battle-nat-type
:items [0 1 2]
:on-value-changed {:event/type :spring-lobby/assoc
:key :battle-nat-type}
:button-cell nat-cell
:cell-factory
{:fx/cell-type :list-cell
:describe nat-cell}}]}
{:fx/type engines-view
:engine-filter engine-filter
:engine-version engine-version
:flow false
:spring-isolation-dir spring-root}
{:fx/type mods-view
:flow false
:mod-filter mod-filter
:mod-name mod-name
:mods mods
:spring-isolation-dir spring-root}
{:fx/type maps-view
:flow false
:map-name map-name
:maps maps
:map-input-prefix map-input-prefix
:on-value-changed {:event/type :spring-lobby/assoc
:key :map-name}
:spring-isolation-dir spring-root}
{:fx/type :pane
:v-box/vgrow :always}
{:fx/type :button
:text "Host Battle"
:on-action host-battle-action}]}
{:fx/type :pane})}}))
(defn host-battle-window [state]
(tufte/profile {:dynamic? true
:id :skylobby/ui}
(tufte/p :host-battle-window
(host-battle-window-impl state))))
|
[
{
"context": ":\" port \"/\" path)\n :user user\n :password pass}))\n ([dsn]\n (create-db-spec dsn default-driver",
"end": 1595,
"score": 0.9981655478477478,
"start": 1591,
"tag": "PASSWORD",
"value": "pass"
}
] |
src/poky/kv/jdbc/util.clj
|
drsnyder/poky
| 2 |
(ns poky.kv.jdbc.util
(:require (poky [util :as util])
[clojure.java.jdbc :as sql]
[clojure.string :as string]
[clojure.tools.logging :refer [warn infof errorf]]
[environ.core :refer [env]])
(:import com.mchange.v2.c3p0.ComboPooledDataSource
[java.sql SQLException Timestamp]))
(def ^:private default-min-pool-size 3)
(def ^:private default-max-pool-size 15)
(def ^:private default-driver "org.postgresql.Driver")
(def ^:private poky-column-types
{:bucket "text"
:key "text"
:data "text"
:created_at "timestamptz"
:modified_at "timestamptz"})
; when partitioning, the bucket names will be used to create tables so we need
; to ensure that they are valid table names. currently limiting them to words
; and _
(def ^:private valid-partitioned-bucket-regex #"^[^\d][\w_]+")
(defn wrap-join [b d a coll] (str b (string/join d coll) a))
(defn pg-array [coll] (wrap-join "ARRAY[" \, \] coll))
(defn pg-mget-param [k m]
(str \( k \, m ")::mget_param_row"))
(defn create-db-spec
"Given a dsn and optionally a driver create a db spec that can be used with pool to
create a connection pool."
([dsn driver]
(let [uri (java.net.URI. dsn)
host (.getHost uri)
scheme (.getScheme uri)
[user pass] (clojure.string/split (.getUserInfo uri) #":")
port (.getPort uri)
port (if (= port -1) 5432 port)
path (.substring (.getPath uri) 1)]
{:classname driver
:subprotocol scheme
:subname (str "//" host ":" port "/" path)
:user user
:password pass}))
([dsn]
(create-db-spec dsn default-driver)))
(defn pool
"Create a connection pool."
[spec &{:keys [min-pool-size max-pool-size]
:or {min-pool-size default-min-pool-size max-pool-size default-max-pool-size}}]
(infof "Creating pool with min %d and max %d connections." min-pool-size max-pool-size)
(let [cpds (doto (ComboPooledDataSource.)
(.setDriverClass (:classname spec))
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec)))
(.setUser (:user spec))
(.setPassword (:password spec))
(.setMinPoolSize min-pool-size)
(.setMaxPoolSize max-pool-size)
(.setMaxIdleTimeExcessConnections (* 30 60))
(.setMaxIdleTime (* 3 60 60)))]
{:datasource cpds}))
(defn create-connection
"Create a connection and delay it."
[dsn]
(delay (pool (create-db-spec dsn) :max-pool-size (util/parse-int (env :max-pool-size default-max-pool-size)))))
(defn close-connection
"Close the connection of a JdbcKeyValue object."
[connection-object]
(.close (:datasource connection-object)))
(defn format-sql-exception
"Formats the contents of an SQLException and return string.
Similar to clojure.java.jdbc/print-sql-exception, but doesn't write to *out*"
[^SQLException exception]
(let [^Class exception-class (class exception)]
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName exception-class)
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception))))
(defn warn-sql-exception
"Outputs a formatted SQLException to log warn"
[^SQLException e]
(doall (map #(warn (format-sql-exception %))
(iterator-seq (.iterator e)))))
(defmacro with-logged-connection [conn & body]
`(try
(sql/with-connection ~conn
~@body)
(catch SQLException e#
(warn-sql-exception e#))))
(defn purge-bucket
"Should only be used in testing."
[conn b]
(with-logged-connection conn
(sql/with-query-results results ["SELECT purge_bucket(?) AS result" b]
(first results))))
(defn child-tables-exist?
"Returns true if child tables exist."
[conn]
(with-logged-connection conn
(sql/with-query-results results ["SELECT c.relname AS child
FROM pg_inherits
JOIN pg_class AS c ON (inhrelid=c.oid)
JOIN pg_class as p ON (inhparent=p.oid)
WHERE p.relname = 'poky'"]
(pos? (count results)))))
(defn valid-bucket-name?
"Returns truthy if the bucket name is valid."
[bucket]
(re-matches valid-partitioned-bucket-regex bucket))
(defn using-partitioning?
"Determine if partitining is being used."
[conn]
(or (env :poky-partitioned) (child-tables-exist? conn)))
(defn create-bucket
"Creates a bucket if partitioning is being used. A noop in a flat structure.
When partitioning is being used, returns truthy on success and nil on error."
[conn b]
(when (using-partitioning? conn)
(if (valid-bucket-name? b)
(with-logged-connection conn
(sql/with-query-results results ["SELECT create_bucket_partition(?) AS result" b]
(first results)))
(errorf "Error, bucket name '%s' is not a valid partitioned bucket name. Must match letters and underscores only." b))))
(defn jdbc-get
"Get the tuple at bucket b and key k. Returns a map with the attributes of the table."
[conn b k]
(with-logged-connection conn
(sql/with-query-results
results
["SELECT * FROM poky WHERE bucket=? AND key=?" b k]
(first results))))
(defn jdbc-set
"Set a bucket b and key k to value v. Returns a map with key :result upon success.
The value at result will be one of \"inserted\", \"updated\" or \"rejected\"."
([conn b k v modified]
(with-logged-connection conn
(sql/with-query-results results ["SELECT upsert_kv_data(?, ?, ?, ?) AS result" b k v modified]
(first results))))
([conn b k v]
(with-logged-connection conn
(sql/with-query-results results ["SELECT upsert_kv_data(?, ?, ?) AS result" b k v]
(first results)))))
(defn jdbc-delete
"Delete the value at bucket b and key k. Returns true on success and false if the
tuple does not exist."
[conn b k]
(with-logged-connection conn
(sql/with-query-results results ["SELECT delete_kv_data(?, ?) AS result" b k]
(list (get (first results) :result)))))
;; ======== MULTI
(defn mget-sproc-conds
"Returns tuple of [cond-sql cond-params] for conditions
cond-sql is a string representation of PG array for sproc's 3rd argument"
[conds]
(let [param-pairs (repeat (count conds) (pg-mget-param \? \?))
value-pairs (map (juxt :key :modified_at) conds)]
[param-pairs value-pairs]))
(defn mget-sproc
"Returns the SQL params vector (ie [sql & params]) for the stored procedure,
mget(bucket::text, (key::text, ts::timestamp)[])
Example:
(mget-sproc 'b' [{:key 'key1'} {:key 'key2'}) =>
['SELECT * FROM mget(?, ARRAY[(?, ?)::mget_param_row, (?, ?)::mget_param_row])' 'b' 'key1' 'modified_at1' 'key2' 'modified_at2']"
[bucket conds]
(when (not (empty? conds))
(let [[cond-sql cond-params] (mget-sproc-conds conds)
sql (wrap-join "SELECT * FROM mget(" \, \)
["?"
(pg-array cond-sql)])]
(apply vector sql bucket (flatten cond-params )))))
(defn jdbc-mget
[conn bucket conds]
(when-let [q (mget-sproc bucket conds)]
(with-logged-connection conn
(sql/with-query-results results q
(doall results)))))
(defn jdbc-mset
"Upserts multiple records in data. Records are hashmaps with following fields:
:bucket (required)
:key (required)
:data (required)
:modified_at (optional)
"
[conn data]
; doing these individually may not be an efficient use of the connection, but
; it should avoid deadlock by doing each set individually
(doall
(map (fn [{b :bucket k :key v :data t :modified_at}]
(if t
(jdbc-set conn b k v t)
(jdbc-set conn b k v))) data)))
|
38884
|
(ns poky.kv.jdbc.util
(:require (poky [util :as util])
[clojure.java.jdbc :as sql]
[clojure.string :as string]
[clojure.tools.logging :refer [warn infof errorf]]
[environ.core :refer [env]])
(:import com.mchange.v2.c3p0.ComboPooledDataSource
[java.sql SQLException Timestamp]))
(def ^:private default-min-pool-size 3)
(def ^:private default-max-pool-size 15)
(def ^:private default-driver "org.postgresql.Driver")
(def ^:private poky-column-types
{:bucket "text"
:key "text"
:data "text"
:created_at "timestamptz"
:modified_at "timestamptz"})
; when partitioning, the bucket names will be used to create tables so we need
; to ensure that they are valid table names. currently limiting them to words
; and _
(def ^:private valid-partitioned-bucket-regex #"^[^\d][\w_]+")
(defn wrap-join [b d a coll] (str b (string/join d coll) a))
(defn pg-array [coll] (wrap-join "ARRAY[" \, \] coll))
(defn pg-mget-param [k m]
(str \( k \, m ")::mget_param_row"))
(defn create-db-spec
"Given a dsn and optionally a driver create a db spec that can be used with pool to
create a connection pool."
([dsn driver]
(let [uri (java.net.URI. dsn)
host (.getHost uri)
scheme (.getScheme uri)
[user pass] (clojure.string/split (.getUserInfo uri) #":")
port (.getPort uri)
port (if (= port -1) 5432 port)
path (.substring (.getPath uri) 1)]
{:classname driver
:subprotocol scheme
:subname (str "//" host ":" port "/" path)
:user user
:password <PASSWORD>}))
([dsn]
(create-db-spec dsn default-driver)))
(defn pool
"Create a connection pool."
[spec &{:keys [min-pool-size max-pool-size]
:or {min-pool-size default-min-pool-size max-pool-size default-max-pool-size}}]
(infof "Creating pool with min %d and max %d connections." min-pool-size max-pool-size)
(let [cpds (doto (ComboPooledDataSource.)
(.setDriverClass (:classname spec))
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec)))
(.setUser (:user spec))
(.setPassword (:password spec))
(.setMinPoolSize min-pool-size)
(.setMaxPoolSize max-pool-size)
(.setMaxIdleTimeExcessConnections (* 30 60))
(.setMaxIdleTime (* 3 60 60)))]
{:datasource cpds}))
(defn create-connection
"Create a connection and delay it."
[dsn]
(delay (pool (create-db-spec dsn) :max-pool-size (util/parse-int (env :max-pool-size default-max-pool-size)))))
(defn close-connection
"Close the connection of a JdbcKeyValue object."
[connection-object]
(.close (:datasource connection-object)))
(defn format-sql-exception
"Formats the contents of an SQLException and return string.
Similar to clojure.java.jdbc/print-sql-exception, but doesn't write to *out*"
[^SQLException exception]
(let [^Class exception-class (class exception)]
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName exception-class)
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception))))
(defn warn-sql-exception
"Outputs a formatted SQLException to log warn"
[^SQLException e]
(doall (map #(warn (format-sql-exception %))
(iterator-seq (.iterator e)))))
(defmacro with-logged-connection [conn & body]
`(try
(sql/with-connection ~conn
~@body)
(catch SQLException e#
(warn-sql-exception e#))))
(defn purge-bucket
"Should only be used in testing."
[conn b]
(with-logged-connection conn
(sql/with-query-results results ["SELECT purge_bucket(?) AS result" b]
(first results))))
(defn child-tables-exist?
"Returns true if child tables exist."
[conn]
(with-logged-connection conn
(sql/with-query-results results ["SELECT c.relname AS child
FROM pg_inherits
JOIN pg_class AS c ON (inhrelid=c.oid)
JOIN pg_class as p ON (inhparent=p.oid)
WHERE p.relname = 'poky'"]
(pos? (count results)))))
(defn valid-bucket-name?
"Returns truthy if the bucket name is valid."
[bucket]
(re-matches valid-partitioned-bucket-regex bucket))
(defn using-partitioning?
"Determine if partitining is being used."
[conn]
(or (env :poky-partitioned) (child-tables-exist? conn)))
(defn create-bucket
"Creates a bucket if partitioning is being used. A noop in a flat structure.
When partitioning is being used, returns truthy on success and nil on error."
[conn b]
(when (using-partitioning? conn)
(if (valid-bucket-name? b)
(with-logged-connection conn
(sql/with-query-results results ["SELECT create_bucket_partition(?) AS result" b]
(first results)))
(errorf "Error, bucket name '%s' is not a valid partitioned bucket name. Must match letters and underscores only." b))))
(defn jdbc-get
"Get the tuple at bucket b and key k. Returns a map with the attributes of the table."
[conn b k]
(with-logged-connection conn
(sql/with-query-results
results
["SELECT * FROM poky WHERE bucket=? AND key=?" b k]
(first results))))
(defn jdbc-set
"Set a bucket b and key k to value v. Returns a map with key :result upon success.
The value at result will be one of \"inserted\", \"updated\" or \"rejected\"."
([conn b k v modified]
(with-logged-connection conn
(sql/with-query-results results ["SELECT upsert_kv_data(?, ?, ?, ?) AS result" b k v modified]
(first results))))
([conn b k v]
(with-logged-connection conn
(sql/with-query-results results ["SELECT upsert_kv_data(?, ?, ?) AS result" b k v]
(first results)))))
(defn jdbc-delete
"Delete the value at bucket b and key k. Returns true on success and false if the
tuple does not exist."
[conn b k]
(with-logged-connection conn
(sql/with-query-results results ["SELECT delete_kv_data(?, ?) AS result" b k]
(list (get (first results) :result)))))
;; ======== MULTI
(defn mget-sproc-conds
"Returns tuple of [cond-sql cond-params] for conditions
cond-sql is a string representation of PG array for sproc's 3rd argument"
[conds]
(let [param-pairs (repeat (count conds) (pg-mget-param \? \?))
value-pairs (map (juxt :key :modified_at) conds)]
[param-pairs value-pairs]))
(defn mget-sproc
"Returns the SQL params vector (ie [sql & params]) for the stored procedure,
mget(bucket::text, (key::text, ts::timestamp)[])
Example:
(mget-sproc 'b' [{:key 'key1'} {:key 'key2'}) =>
['SELECT * FROM mget(?, ARRAY[(?, ?)::mget_param_row, (?, ?)::mget_param_row])' 'b' 'key1' 'modified_at1' 'key2' 'modified_at2']"
[bucket conds]
(when (not (empty? conds))
(let [[cond-sql cond-params] (mget-sproc-conds conds)
sql (wrap-join "SELECT * FROM mget(" \, \)
["?"
(pg-array cond-sql)])]
(apply vector sql bucket (flatten cond-params )))))
(defn jdbc-mget
[conn bucket conds]
(when-let [q (mget-sproc bucket conds)]
(with-logged-connection conn
(sql/with-query-results results q
(doall results)))))
(defn jdbc-mset
"Upserts multiple records in data. Records are hashmaps with following fields:
:bucket (required)
:key (required)
:data (required)
:modified_at (optional)
"
[conn data]
; doing these individually may not be an efficient use of the connection, but
; it should avoid deadlock by doing each set individually
(doall
(map (fn [{b :bucket k :key v :data t :modified_at}]
(if t
(jdbc-set conn b k v t)
(jdbc-set conn b k v))) data)))
| true |
(ns poky.kv.jdbc.util
(:require (poky [util :as util])
[clojure.java.jdbc :as sql]
[clojure.string :as string]
[clojure.tools.logging :refer [warn infof errorf]]
[environ.core :refer [env]])
(:import com.mchange.v2.c3p0.ComboPooledDataSource
[java.sql SQLException Timestamp]))
(def ^:private default-min-pool-size 3)
(def ^:private default-max-pool-size 15)
(def ^:private default-driver "org.postgresql.Driver")
(def ^:private poky-column-types
{:bucket "text"
:key "text"
:data "text"
:created_at "timestamptz"
:modified_at "timestamptz"})
; when partitioning, the bucket names will be used to create tables so we need
; to ensure that they are valid table names. currently limiting them to words
; and _
(def ^:private valid-partitioned-bucket-regex #"^[^\d][\w_]+")
(defn wrap-join [b d a coll] (str b (string/join d coll) a))
(defn pg-array [coll] (wrap-join "ARRAY[" \, \] coll))
(defn pg-mget-param [k m]
(str \( k \, m ")::mget_param_row"))
(defn create-db-spec
"Given a dsn and optionally a driver create a db spec that can be used with pool to
create a connection pool."
([dsn driver]
(let [uri (java.net.URI. dsn)
host (.getHost uri)
scheme (.getScheme uri)
[user pass] (clojure.string/split (.getUserInfo uri) #":")
port (.getPort uri)
port (if (= port -1) 5432 port)
path (.substring (.getPath uri) 1)]
{:classname driver
:subprotocol scheme
:subname (str "//" host ":" port "/" path)
:user user
:password PI:PASSWORD:<PASSWORD>END_PI}))
([dsn]
(create-db-spec dsn default-driver)))
(defn pool
"Create a connection pool."
[spec &{:keys [min-pool-size max-pool-size]
:or {min-pool-size default-min-pool-size max-pool-size default-max-pool-size}}]
(infof "Creating pool with min %d and max %d connections." min-pool-size max-pool-size)
(let [cpds (doto (ComboPooledDataSource.)
(.setDriverClass (:classname spec))
(.setJdbcUrl (str "jdbc:" (:subprotocol spec) ":" (:subname spec)))
(.setUser (:user spec))
(.setPassword (:password spec))
(.setMinPoolSize min-pool-size)
(.setMaxPoolSize max-pool-size)
(.setMaxIdleTimeExcessConnections (* 30 60))
(.setMaxIdleTime (* 3 60 60)))]
{:datasource cpds}))
(defn create-connection
"Create a connection and delay it."
[dsn]
(delay (pool (create-db-spec dsn) :max-pool-size (util/parse-int (env :max-pool-size default-max-pool-size)))))
(defn close-connection
"Close the connection of a JdbcKeyValue object."
[connection-object]
(.close (:datasource connection-object)))
(defn format-sql-exception
"Formats the contents of an SQLException and return string.
Similar to clojure.java.jdbc/print-sql-exception, but doesn't write to *out*"
[^SQLException exception]
(let [^Class exception-class (class exception)]
(format (str "%s:" \newline
" Message: %s" \newline
" SQLState: %s" \newline
" Error Code: %d")
(.getSimpleName exception-class)
(.getMessage exception)
(.getSQLState exception)
(.getErrorCode exception))))
(defn warn-sql-exception
"Outputs a formatted SQLException to log warn"
[^SQLException e]
(doall (map #(warn (format-sql-exception %))
(iterator-seq (.iterator e)))))
(defmacro with-logged-connection [conn & body]
`(try
(sql/with-connection ~conn
~@body)
(catch SQLException e#
(warn-sql-exception e#))))
(defn purge-bucket
"Should only be used in testing."
[conn b]
(with-logged-connection conn
(sql/with-query-results results ["SELECT purge_bucket(?) AS result" b]
(first results))))
(defn child-tables-exist?
"Returns true if child tables exist."
[conn]
(with-logged-connection conn
(sql/with-query-results results ["SELECT c.relname AS child
FROM pg_inherits
JOIN pg_class AS c ON (inhrelid=c.oid)
JOIN pg_class as p ON (inhparent=p.oid)
WHERE p.relname = 'poky'"]
(pos? (count results)))))
(defn valid-bucket-name?
"Returns truthy if the bucket name is valid."
[bucket]
(re-matches valid-partitioned-bucket-regex bucket))
(defn using-partitioning?
"Determine if partitining is being used."
[conn]
(or (env :poky-partitioned) (child-tables-exist? conn)))
(defn create-bucket
"Creates a bucket if partitioning is being used. A noop in a flat structure.
When partitioning is being used, returns truthy on success and nil on error."
[conn b]
(when (using-partitioning? conn)
(if (valid-bucket-name? b)
(with-logged-connection conn
(sql/with-query-results results ["SELECT create_bucket_partition(?) AS result" b]
(first results)))
(errorf "Error, bucket name '%s' is not a valid partitioned bucket name. Must match letters and underscores only." b))))
(defn jdbc-get
"Get the tuple at bucket b and key k. Returns a map with the attributes of the table."
[conn b k]
(with-logged-connection conn
(sql/with-query-results
results
["SELECT * FROM poky WHERE bucket=? AND key=?" b k]
(first results))))
(defn jdbc-set
"Set a bucket b and key k to value v. Returns a map with key :result upon success.
The value at result will be one of \"inserted\", \"updated\" or \"rejected\"."
([conn b k v modified]
(with-logged-connection conn
(sql/with-query-results results ["SELECT upsert_kv_data(?, ?, ?, ?) AS result" b k v modified]
(first results))))
([conn b k v]
(with-logged-connection conn
(sql/with-query-results results ["SELECT upsert_kv_data(?, ?, ?) AS result" b k v]
(first results)))))
(defn jdbc-delete
"Delete the value at bucket b and key k. Returns true on success and false if the
tuple does not exist."
[conn b k]
(with-logged-connection conn
(sql/with-query-results results ["SELECT delete_kv_data(?, ?) AS result" b k]
(list (get (first results) :result)))))
;; ======== MULTI
(defn mget-sproc-conds
"Returns tuple of [cond-sql cond-params] for conditions
cond-sql is a string representation of PG array for sproc's 3rd argument"
[conds]
(let [param-pairs (repeat (count conds) (pg-mget-param \? \?))
value-pairs (map (juxt :key :modified_at) conds)]
[param-pairs value-pairs]))
(defn mget-sproc
"Returns the SQL params vector (ie [sql & params]) for the stored procedure,
mget(bucket::text, (key::text, ts::timestamp)[])
Example:
(mget-sproc 'b' [{:key 'key1'} {:key 'key2'}) =>
['SELECT * FROM mget(?, ARRAY[(?, ?)::mget_param_row, (?, ?)::mget_param_row])' 'b' 'key1' 'modified_at1' 'key2' 'modified_at2']"
[bucket conds]
(when (not (empty? conds))
(let [[cond-sql cond-params] (mget-sproc-conds conds)
sql (wrap-join "SELECT * FROM mget(" \, \)
["?"
(pg-array cond-sql)])]
(apply vector sql bucket (flatten cond-params )))))
(defn jdbc-mget
[conn bucket conds]
(when-let [q (mget-sproc bucket conds)]
(with-logged-connection conn
(sql/with-query-results results q
(doall results)))))
(defn jdbc-mset
"Upserts multiple records in data. Records are hashmaps with following fields:
:bucket (required)
:key (required)
:data (required)
:modified_at (optional)
"
[conn data]
; doing these individually may not be an efficient use of the connection, but
; it should avoid deadlock by doing each set individually
(doall
(map (fn [{b :bucket k :key v :data t :modified_at}]
(if t
(jdbc-set conn b k v t)
(jdbc-set conn b k v))) data)))
|
[
{
"context": ": Apache Storm, Apache Kafka, Redis\n;;\n;; @author Stefan Schadwinkel <[email protected]>\n;; @copyright Cop",
"end": 147,
"score": 0.9998884797096252,
"start": 129,
"tag": "NAME",
"value": "Stefan Schadwinkel"
},
{
"context": "e Kafka, Redis\n;;\n;; @author Stefan Schadwinkel <[email protected]>\n;; @copyright Copyright (c) 2013 DECK36 GmbH & ",
"end": 177,
"score": 0.9999306797981262,
"start": 149,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
project.clj
|
DECK36/deck36-storm-idempotent-counter
| 2 |
;;
;; Leiningen project file to build the Idempotent Counter Example
;; Uses: Apache Storm, Apache Kafka, Redis
;;
;; @author Stefan Schadwinkel <[email protected]>
;; @copyright Copyright (c) 2013 DECK36 GmbH & Co. KG (http://www.deck36.de)
;;
;; For the full copyright and license information, please view the LICENSE
;; file that was distributed with this source code.
;;
(defproject deck36-idempotent-counter "0.0.1-SNAPSHOT"
:source-paths ["src/clj"]
:java-source-paths ["src/jvm"]
:aot :all
:plugins [[lein-git-deps "0.0.1-SNAPSHOT"] [lein-idea "1.0.1"]]
:resource-paths [
"resources/nodejs/"
]
:git-dependencies [
["https://github.com/DECK36/incubator-storm.git" "storm-kafka-spout-with-offset"]
]
:dependencies [
[commons-collections/commons-collections "3.2.1"]
[com.googlecode.json-simple/json-simple "1.1"]
[redis.clients/jedis "2.5.2"]
[com.jayway.jsonpath/json-path "0.9.1"]
[com.google.code.gson/gson "2.2.4"]
[org.apache.kafka/kafka_2.9.2 "0.8.1.1"]
[org.apache.zookeeper/zookeeper "3.4.5"]
[org.apache.storm/storm-kafka "0.9.2-incubating"]
]
:exclusions [org.slf4j/slf4j-log4j12 log4j/log4j]
:profiles {:provided
{:dependencies
[[org.apache.storm/storm-core "0.9.2-incubating"]]}}
:min-lein-version "2.0.0"
)
|
101746
|
;;
;; Leiningen project file to build the Idempotent Counter Example
;; Uses: Apache Storm, Apache Kafka, Redis
;;
;; @author <NAME> <<EMAIL>>
;; @copyright Copyright (c) 2013 DECK36 GmbH & Co. KG (http://www.deck36.de)
;;
;; For the full copyright and license information, please view the LICENSE
;; file that was distributed with this source code.
;;
(defproject deck36-idempotent-counter "0.0.1-SNAPSHOT"
:source-paths ["src/clj"]
:java-source-paths ["src/jvm"]
:aot :all
:plugins [[lein-git-deps "0.0.1-SNAPSHOT"] [lein-idea "1.0.1"]]
:resource-paths [
"resources/nodejs/"
]
:git-dependencies [
["https://github.com/DECK36/incubator-storm.git" "storm-kafka-spout-with-offset"]
]
:dependencies [
[commons-collections/commons-collections "3.2.1"]
[com.googlecode.json-simple/json-simple "1.1"]
[redis.clients/jedis "2.5.2"]
[com.jayway.jsonpath/json-path "0.9.1"]
[com.google.code.gson/gson "2.2.4"]
[org.apache.kafka/kafka_2.9.2 "0.8.1.1"]
[org.apache.zookeeper/zookeeper "3.4.5"]
[org.apache.storm/storm-kafka "0.9.2-incubating"]
]
:exclusions [org.slf4j/slf4j-log4j12 log4j/log4j]
:profiles {:provided
{:dependencies
[[org.apache.storm/storm-core "0.9.2-incubating"]]}}
:min-lein-version "2.0.0"
)
| true |
;;
;; Leiningen project file to build the Idempotent Counter Example
;; Uses: Apache Storm, Apache Kafka, Redis
;;
;; @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; @copyright Copyright (c) 2013 DECK36 GmbH & Co. KG (http://www.deck36.de)
;;
;; For the full copyright and license information, please view the LICENSE
;; file that was distributed with this source code.
;;
(defproject deck36-idempotent-counter "0.0.1-SNAPSHOT"
:source-paths ["src/clj"]
:java-source-paths ["src/jvm"]
:aot :all
:plugins [[lein-git-deps "0.0.1-SNAPSHOT"] [lein-idea "1.0.1"]]
:resource-paths [
"resources/nodejs/"
]
:git-dependencies [
["https://github.com/DECK36/incubator-storm.git" "storm-kafka-spout-with-offset"]
]
:dependencies [
[commons-collections/commons-collections "3.2.1"]
[com.googlecode.json-simple/json-simple "1.1"]
[redis.clients/jedis "2.5.2"]
[com.jayway.jsonpath/json-path "0.9.1"]
[com.google.code.gson/gson "2.2.4"]
[org.apache.kafka/kafka_2.9.2 "0.8.1.1"]
[org.apache.zookeeper/zookeeper "3.4.5"]
[org.apache.storm/storm-kafka "0.9.2-incubating"]
]
:exclusions [org.slf4j/slf4j-log4j12 log4j/log4j]
:profiles {:provided
{:dependencies
[[org.apache.storm/storm-core "0.9.2-incubating"]]}}
:min-lein-version "2.0.0"
)
|
[
{
"context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg",
"end": 62,
"score": 0.9997686743736267,
"start": 50,
"tag": "NAME",
"value": "Richard Hull"
}
] |
test/clustering/core/qt_test.clj
|
CharlesHD/clustering
| 17 |
;; The MIT License (MIT)
;;
;; Copyright (c) 2016 Richard Hull
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns clustering.core.qt-test
(:require
[clojure.test :refer :all]
[clustering.core.qt :refer :all]
[clustering.test-helper :refer :all]
[clj-time.core :refer [date-time]]))
(deftest check-candidate-cluster
(is (empty? (candidate-cluster distance (date-time 2013 7 15) test-dataset 0)))
(is (empty? (candidate-cluster distance (date-time 2013 7 15) nil 150)))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 1)
(hash-set (date-time 2013 7 14))))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 15)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25))))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 31)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3)))))
(deftest check-most-candidates
(is (empty? (most-candidates distance nil 31)))
(is (= (most-candidates distance test-dataset 31)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3)))))
(deftest check-cluster
(is (empty? (cluster distance nil 31 3)))
(is (empty? (cluster distance [(date-time 2016 11 3)] 31 3)))
(is (= [(hash-set (date-time 2016 11 3))]
(cluster distance [(date-time 2016 11 3)] 31 1)))
(is (= [(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3))
(hash-set
(date-time 2012 5 28)
(date-time 2012 6 2)
(date-time 2012 6 6)
(date-time 2012 6 7)
(date-time 2012 6 9))
(hash-set
(date-time 2012 12 26)
(date-time 2012 12 28)
(date-time 2013 1 16))]
(cluster distance test-dataset 31 3))))
|
44143
|
;; The MIT License (MIT)
;;
;; Copyright (c) 2016 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns clustering.core.qt-test
(:require
[clojure.test :refer :all]
[clustering.core.qt :refer :all]
[clustering.test-helper :refer :all]
[clj-time.core :refer [date-time]]))
(deftest check-candidate-cluster
(is (empty? (candidate-cluster distance (date-time 2013 7 15) test-dataset 0)))
(is (empty? (candidate-cluster distance (date-time 2013 7 15) nil 150)))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 1)
(hash-set (date-time 2013 7 14))))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 15)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25))))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 31)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3)))))
(deftest check-most-candidates
(is (empty? (most-candidates distance nil 31)))
(is (= (most-candidates distance test-dataset 31)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3)))))
(deftest check-cluster
(is (empty? (cluster distance nil 31 3)))
(is (empty? (cluster distance [(date-time 2016 11 3)] 31 3)))
(is (= [(hash-set (date-time 2016 11 3))]
(cluster distance [(date-time 2016 11 3)] 31 1)))
(is (= [(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3))
(hash-set
(date-time 2012 5 28)
(date-time 2012 6 2)
(date-time 2012 6 6)
(date-time 2012 6 7)
(date-time 2012 6 9))
(hash-set
(date-time 2012 12 26)
(date-time 2012 12 28)
(date-time 2013 1 16))]
(cluster distance test-dataset 31 3))))
| true |
;; The MIT License (MIT)
;;
;; Copyright (c) 2016 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns clustering.core.qt-test
(:require
[clojure.test :refer :all]
[clustering.core.qt :refer :all]
[clustering.test-helper :refer :all]
[clj-time.core :refer [date-time]]))
(deftest check-candidate-cluster
(is (empty? (candidate-cluster distance (date-time 2013 7 15) test-dataset 0)))
(is (empty? (candidate-cluster distance (date-time 2013 7 15) nil 150)))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 1)
(hash-set (date-time 2013 7 14))))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 15)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25))))
(is (= (candidate-cluster distance (date-time 2013 7 15) test-dataset 31)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3)))))
(deftest check-most-candidates
(is (empty? (most-candidates distance nil 31)))
(is (= (most-candidates distance test-dataset 31)
(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3)))))
(deftest check-cluster
(is (empty? (cluster distance nil 31 3)))
(is (empty? (cluster distance [(date-time 2016 11 3)] 31 3)))
(is (= [(hash-set (date-time 2016 11 3))]
(cluster distance [(date-time 2016 11 3)] 31 1)))
(is (= [(hash-set
(date-time 2013 7 1)
(date-time 2013 7 14)
(date-time 2013 7 21)
(date-time 2013 7 25)
(date-time 2013 7 31)
(date-time 2013 8 3))
(hash-set
(date-time 2012 5 28)
(date-time 2012 6 2)
(date-time 2012 6 6)
(date-time 2012 6 7)
(date-time 2012 6 9))
(hash-set
(date-time 2012 12 26)
(date-time 2012 12 28)
(date-time 2013 1 16))]
(cluster distance test-dataset 31 3))))
|
[
{
"context": "from a 'Savegame Decrypter' utility made by user\n JohnnyGuitar. You can find more info here:\n http://forum.scss",
"end": 369,
"score": 0.974270761013031,
"start": 357,
"tag": "NAME",
"value": "JohnnyGuitar"
}
] |
components/decrypt/src/ets/jobs/decrypt/core.clj
|
bshepherdson/etsjobs
| 0 |
(ns ets.jobs.decrypt.core
(:require
[clojure.java.io :as io])
(:import
[java.io ByteArrayInputStream ByteArrayOutputStream]
[java.nio ByteBuffer ByteOrder]
[javax.crypto Cipher]
[javax.crypto.spec IvParameterSpec SecretKeySpec]))
(def ^:private sii-key-bytes
"This key was taken from a 'Savegame Decrypter' utility made by user
JohnnyGuitar. You can find more info here:
http://forum.scssoft.com/viewtopic.php?f=34&t=164103#p280580"
(byte-array
[0x2a 0x5f 0xcb 0x17 0x91 0xd2 0x2f 0xb6
0x02 0x45 0xb3 0xd8 0x36 0x9e 0xd0 0xb2
0xc2 0x73 0x71 0x56 0x3f 0xbf 0x1f 0x3c
0x9e 0xdf 0x6b 0x11 0x82 0x5a 0x5d 0x0a]))
(def ^:private sii-key (SecretKeySpec. sii-key-bytes "AES"))
(def ^:private sii-encrypted-signature
"ScsC"
0x43736353)
(def ^:private sii-normal-signature
"SiiN"
0x4e696953)
; The SIIHeader is a struct like this:
; signature u32, one of the above values.
; HMAC byte[32]
; InitVector byte[16]
; DataSize u32
;
; This is AES with a 256-bit key and using CBC mode with the initial vector
; stored in the header.
;
; TODO I'm not sure what the padding type is, nor the actual inner format.
(defn- signature [buf]
(.getInt buf 0))
(defn encrypted? [buf]
(= sii-encrypted-signature (signature buf)))
(defn- read-header [buf]
(let [sig (signature buf)
iv-bytes (byte-array 16)]
(.get buf 36 iv-bytes)
[sig (IvParameterSpec. iv-bytes) (.getInt buf 52)]))
(defn- read-body [buf]
(let [out (byte-array (- (.limit buf) 56))]
(.get buf 56 out)
out))
(defn binary-slurp [path]
(with-open [in (io/input-stream (io/file path))]
(let [out (ByteArrayOutputStream.)]
(io/copy in out)
(-> (.toByteArray out)
(ByteBuffer/wrap)
(.order ByteOrder/LITTLE_ENDIAN)))))
(defn binary-spit [path content]
(with-open [out (io/output-stream (io/file path))]
(let [in (ByteArrayInputStream. (.array content))]
(io/copy in out))))
(defn decrypt [buf]
(let [[sig iv size] (read-header buf)
body (read-body buf)
cipher (Cipher/getInstance "AES/CBC/PKCS5Padding")]
(.init cipher Cipher/DECRYPT_MODE sii-key iv)
(.doFinal cipher body)))
(defn inflate [ba]
(let [is (java.util.zip.InflaterInputStream. (ByteArrayInputStream. ba))
os (ByteArrayOutputStream.)]
(io/copy is os)
(.toByteArray os)))
(defn decode [filename]
(-> filename
binary-slurp
decrypt
inflate
(ByteBuffer/wrap)
(.order ByteOrder/LITTLE_ENDIAN)))
; Header:
; signature u32, one of the above values.
; HMAC byte[32]
; InitVector byte[16]
; DataSize u32
;
; In the below that's:
; Signature: 53637343 = ScsC
; HMAC: b404 953d 51ac 2745 ddad c203 8670 9f0a
; 7a0d 0f5e 7ce4 3d05 6bbd 4dde f133 85d5
; IV: afdd 0318 fac8 95aa 8997 6a64 5caf 2b7c
; Datasize: 51c3 2100
;
; 0x21c351 = 2,212,689 - this is the unzipped size I guess.
|
91663
|
(ns ets.jobs.decrypt.core
(:require
[clojure.java.io :as io])
(:import
[java.io ByteArrayInputStream ByteArrayOutputStream]
[java.nio ByteBuffer ByteOrder]
[javax.crypto Cipher]
[javax.crypto.spec IvParameterSpec SecretKeySpec]))
(def ^:private sii-key-bytes
"This key was taken from a 'Savegame Decrypter' utility made by user
<NAME>. You can find more info here:
http://forum.scssoft.com/viewtopic.php?f=34&t=164103#p280580"
(byte-array
[0x2a 0x5f 0xcb 0x17 0x91 0xd2 0x2f 0xb6
0x02 0x45 0xb3 0xd8 0x36 0x9e 0xd0 0xb2
0xc2 0x73 0x71 0x56 0x3f 0xbf 0x1f 0x3c
0x9e 0xdf 0x6b 0x11 0x82 0x5a 0x5d 0x0a]))
(def ^:private sii-key (SecretKeySpec. sii-key-bytes "AES"))
(def ^:private sii-encrypted-signature
"ScsC"
0x43736353)
(def ^:private sii-normal-signature
"SiiN"
0x4e696953)
; The SIIHeader is a struct like this:
; signature u32, one of the above values.
; HMAC byte[32]
; InitVector byte[16]
; DataSize u32
;
; This is AES with a 256-bit key and using CBC mode with the initial vector
; stored in the header.
;
; TODO I'm not sure what the padding type is, nor the actual inner format.
(defn- signature [buf]
(.getInt buf 0))
(defn encrypted? [buf]
(= sii-encrypted-signature (signature buf)))
(defn- read-header [buf]
(let [sig (signature buf)
iv-bytes (byte-array 16)]
(.get buf 36 iv-bytes)
[sig (IvParameterSpec. iv-bytes) (.getInt buf 52)]))
(defn- read-body [buf]
(let [out (byte-array (- (.limit buf) 56))]
(.get buf 56 out)
out))
(defn binary-slurp [path]
(with-open [in (io/input-stream (io/file path))]
(let [out (ByteArrayOutputStream.)]
(io/copy in out)
(-> (.toByteArray out)
(ByteBuffer/wrap)
(.order ByteOrder/LITTLE_ENDIAN)))))
(defn binary-spit [path content]
(with-open [out (io/output-stream (io/file path))]
(let [in (ByteArrayInputStream. (.array content))]
(io/copy in out))))
(defn decrypt [buf]
(let [[sig iv size] (read-header buf)
body (read-body buf)
cipher (Cipher/getInstance "AES/CBC/PKCS5Padding")]
(.init cipher Cipher/DECRYPT_MODE sii-key iv)
(.doFinal cipher body)))
(defn inflate [ba]
(let [is (java.util.zip.InflaterInputStream. (ByteArrayInputStream. ba))
os (ByteArrayOutputStream.)]
(io/copy is os)
(.toByteArray os)))
(defn decode [filename]
(-> filename
binary-slurp
decrypt
inflate
(ByteBuffer/wrap)
(.order ByteOrder/LITTLE_ENDIAN)))
; Header:
; signature u32, one of the above values.
; HMAC byte[32]
; InitVector byte[16]
; DataSize u32
;
; In the below that's:
; Signature: 53637343 = ScsC
; HMAC: b404 953d 51ac 2745 ddad c203 8670 9f0a
; 7a0d 0f5e 7ce4 3d05 6bbd 4dde f133 85d5
; IV: afdd 0318 fac8 95aa 8997 6a64 5caf 2b7c
; Datasize: 51c3 2100
;
; 0x21c351 = 2,212,689 - this is the unzipped size I guess.
| true |
(ns ets.jobs.decrypt.core
(:require
[clojure.java.io :as io])
(:import
[java.io ByteArrayInputStream ByteArrayOutputStream]
[java.nio ByteBuffer ByteOrder]
[javax.crypto Cipher]
[javax.crypto.spec IvParameterSpec SecretKeySpec]))
(def ^:private sii-key-bytes
"This key was taken from a 'Savegame Decrypter' utility made by user
PI:NAME:<NAME>END_PI. You can find more info here:
http://forum.scssoft.com/viewtopic.php?f=34&t=164103#p280580"
(byte-array
[0x2a 0x5f 0xcb 0x17 0x91 0xd2 0x2f 0xb6
0x02 0x45 0xb3 0xd8 0x36 0x9e 0xd0 0xb2
0xc2 0x73 0x71 0x56 0x3f 0xbf 0x1f 0x3c
0x9e 0xdf 0x6b 0x11 0x82 0x5a 0x5d 0x0a]))
(def ^:private sii-key (SecretKeySpec. sii-key-bytes "AES"))
(def ^:private sii-encrypted-signature
"ScsC"
0x43736353)
(def ^:private sii-normal-signature
"SiiN"
0x4e696953)
; The SIIHeader is a struct like this:
; signature u32, one of the above values.
; HMAC byte[32]
; InitVector byte[16]
; DataSize u32
;
; This is AES with a 256-bit key and using CBC mode with the initial vector
; stored in the header.
;
; TODO I'm not sure what the padding type is, nor the actual inner format.
(defn- signature [buf]
(.getInt buf 0))
(defn encrypted? [buf]
(= sii-encrypted-signature (signature buf)))
(defn- read-header [buf]
(let [sig (signature buf)
iv-bytes (byte-array 16)]
(.get buf 36 iv-bytes)
[sig (IvParameterSpec. iv-bytes) (.getInt buf 52)]))
(defn- read-body [buf]
(let [out (byte-array (- (.limit buf) 56))]
(.get buf 56 out)
out))
(defn binary-slurp [path]
(with-open [in (io/input-stream (io/file path))]
(let [out (ByteArrayOutputStream.)]
(io/copy in out)
(-> (.toByteArray out)
(ByteBuffer/wrap)
(.order ByteOrder/LITTLE_ENDIAN)))))
(defn binary-spit [path content]
(with-open [out (io/output-stream (io/file path))]
(let [in (ByteArrayInputStream. (.array content))]
(io/copy in out))))
(defn decrypt [buf]
(let [[sig iv size] (read-header buf)
body (read-body buf)
cipher (Cipher/getInstance "AES/CBC/PKCS5Padding")]
(.init cipher Cipher/DECRYPT_MODE sii-key iv)
(.doFinal cipher body)))
(defn inflate [ba]
(let [is (java.util.zip.InflaterInputStream. (ByteArrayInputStream. ba))
os (ByteArrayOutputStream.)]
(io/copy is os)
(.toByteArray os)))
(defn decode [filename]
(-> filename
binary-slurp
decrypt
inflate
(ByteBuffer/wrap)
(.order ByteOrder/LITTLE_ENDIAN)))
; Header:
; signature u32, one of the above values.
; HMAC byte[32]
; InitVector byte[16]
; DataSize u32
;
; In the below that's:
; Signature: 53637343 = ScsC
; HMAC: b404 953d 51ac 2745 ddad c203 8670 9f0a
; 7a0d 0f5e 7ce4 3d05 6bbd 4dde f133 85d5
; IV: afdd 0318 fac8 95aa 8997 6a64 5caf 2b7c
; Datasize: 51c3 2100
;
; 0x21c351 = 2,212,689 - this is the unzipped size I guess.
|
[
{
"context": "rson-id :people/id})\n (where {:people/name \\\"John Doe\\\"})\n fetch!)\n ```\"\n [query op r-source cla",
"end": 8026,
"score": 0.9997807145118713,
"start": 8018,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ongs-to) :type val)))\n rel-keys (keys rels)\n initial-select (when (or (not-empty em",
"end": 18733,
"score": 0.5021703243255615,
"start": 18732,
"tag": "KEY",
"value": "s"
}
] |
src/norm/sql.clj
|
kurbatov/norm
| 4 |
(ns norm.sql
(:refer-clojure :exclude [find update remove])
(:require [clojure.string :as str]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[next.jdbc.protocols :refer [Sourceable]]
[next.jdbc.date-time]
[camel-snake-kebab.core :refer [->kebab-case-keyword ->kebab-case-string]]
[clojure.spec.test.alpha :as st]
[norm.core :as core :refer [where create-repository]]
[norm.sql.format :as f]
[norm.sql.jdbc :refer [as-entity-maps]]
[norm.util :refer [flatten-map meta?]])
(:import [norm.core Command Query]))
(def default-jdbc-opts
{:return-keys true
:label-fn ->kebab-case-string
:builder-fn rs/as-unqualified-modified-maps})
(defmulti generate-sql-command
"Generates SQL command depending on its type."
:type)
(defmethod generate-sql-command :insert [{:keys [target values]}]
(let [batch (vector? values)
fields (if batch (first values) (keys values))
values (if batch (rest values) [(vals values)])]
(str "INSERT INTO " (f/format-target target) " "
(f/group ", " (map f/format-field fields))
" VALUES " (->> values (map #(->> % (map f/format-field) (f/group ", "))) (str/join ", ")))))
(defmethod generate-sql-command :update [{:keys [target values where]}]
(str "UPDATE " (f/format-target target)
" SET " (->> values
(map #(str (f/format-field (key %)) " = " (f/format-field (val %))))
(str/join ", "))
(when where (str " WHERE " (f/format-clause where)))))
(defmethod generate-sql-command :delete [{:keys [target where]}]
(str "DELETE FROM " (f/format-target target)
(when where (str " WHERE " (f/format-clause where)))))
(defmethod generate-sql-command :default [x] (str x))
(defn- execute-sql-command [command]
(let [{:keys [type values where]} command
db (:db (meta command))
params (if (vector? values) (flatten (rest values)) (and values (f/extract-values values)))
params (if where (concat params (f/extract-values where)) params)
command (apply vector (generate-sql-command command) params)]
(jdbc/execute-one! db command (when (= :insert type) default-jdbc-opts))))
(declare sql-command-meta)
(defn transaction
"Constructs chain of commands that will be executed in a transaction."
^Command
[db & commands]
(if (vector? (first commands))
(into (first commands) (rest commands))
(with-meta (into [] commands) (assoc sql-command-meta :db db))))
(defn- execute-transaction [tx transaction]
(loop [results []
commands transaction
tx-result nil]
(if (not-empty commands)
(let [command (-> (first commands) (vary-meta assoc :db tx))
command (if (fn? command)
(-> (command results) (vary-meta merge (meta command)))
command)
result (core/execute! command)]
(recur (conj results result) (rest commands) (if (:tx-result (meta command)) result tx-result)))
(if-let [tx-result-fn (:tx-result-fn (meta transaction))]
(tx-result-fn results)
(if tx-result
tx-result
results)))))
(def sql-command-meta
"Implementation of `Command` protocol."
{`core/execute! (fn execute-command [command]
(let [{:keys [db entity relation]} (meta command)
default-result (cond-> (:values command)
(:pk entity) (select-keys [(:pk entity)]))
result (if (vector? command)
(if (:tx-propagation (meta command))
(execute-transaction db command)
(jdbc/with-transaction [tx db] (execute-transaction tx command)))
(or (execute-sql-command command) default-result))]
(cond-> result
(and (meta? result) entity) (vary-meta assoc :entity entity)
(and (meta? result) relation) (vary-meta assoc :relation relation)
(#{:update :delete} (:type command)) :next.jdbc/update-count)))
`core/then (fn then [command next-command]
(if next-command
(transaction (:db (meta command)) command next-command)
command))})
(defn insert
"Constructs an insert command."
^Command
[db target values]
(-> {:type :insert :target target :values values}
(with-meta (assoc sql-command-meta :db db))))
(defn update
"Constructs an update command."
^Command
[db target values where]
(-> {:type :update :target target :values values :where where}
(with-meta (assoc sql-command-meta :db db))))
(defn delete
"Constructs a delete command."
^Command
[db target where]
(-> {:type :delete :target target :where where}
(with-meta (assoc sql-command-meta :db db))))
;; Query builder
(defrecord SQLQuery [source fields where order offset limit jdbc-opts]
core/Command
(execute! [this]
(let [values (f/extract-values [this])
query (apply vector (str this) values)
{:keys [db transform]} (meta this)]
(cond->> (jdbc/execute! db query (merge default-jdbc-opts jdbc-opts))
transform (mapv transform))))
(then [this next-command] (transaction (:db (meta this)) this next-command))
core/Query
(where [this clauses]
(let [exact (:exact (meta clauses))
entity (:entity (meta this))
clauses (if (and (not exact) entity)
(f/ensure-prefixed (:name entity) clauses)
clauses)]
(assoc this :where (f/conjunct-clauses where clauses))))
(order [this order]
(let [exact (:exact (meta order))
entity (:entity (meta this))
order (if (and (not exact) entity)
(f/ensure-prefixed (:name entity) order)
order)]
(assoc this :order order)))
(skip [this amount] (assoc this :offset amount))
(limit [this amount] (assoc this :limit amount))
(fetch! [this] (core/execute! this))
(fetch! [this fields] (core/fetch! (assoc this :fields fields)))
(fetch-count! [this]
(-> this
(assoc :fields [['(count :*) :count]]
:order nil
:offset nil
:limit nil)
core/fetch!
first
:count))
Object
(toString [this]
(cond-> (str "SELECT " (->> (or fields [:*])
(map #(if (and (keyword? %) (not= "*" (name %))) [% %] %))
(map f/format-field)
(str/join ", ")))
source (str " FROM " (f/format-source source))
(seq where) (str " WHERE " (f/format-clause where))
(:group-by this) (str " GROUP BY " (->> (:group-by this) (map f/format-field) (str/join ", ")))
(:having this) (str " HAVING " (f/format-clause (:having this)))
(seq order) (str " ORDER BY " (f/format-order order))
limit (str " LIMIT ?")
offset (str " OFFSET ?"))))
(defn select
"Constructs a query."
^SQLQuery
([db source] (select db source nil))
([db source fields] (select db source fields nil))
([db source fields where] (select db source fields where nil))
([db source fields where order] (select db source fields where order nil))
([db source fields where order offset] (select db source fields where order offset nil))
([db source fields where order offset limit] (select db source fields where order offset limit nil))
([db source fields where order offset limit jdbc-opts]
(-> (->SQLQuery source fields where order offset limit jdbc-opts)
(with-meta (merge jdbc-opts {:db db})))))
(defn join
"Adds `source` to the query joining it with specified `op`eration.
Example:
```
(-> users-query
(join :left-join :people {:users/person-id :people/id})
(where {:people/name \"John Doe\"})
fetch!)
```"
[query op r-source clause] (assoc query :source [(:source query) op r-source clause]))
;; Relational entity
(defn- build-source [entity ks]
(let [{:keys [table name pk rels]} entity
repository @(or (:repository (meta entity)) (delay {}))]
(->> rels
(filter (comp (partial contains? repository) :entity val))
(map (fn [[k v]] [(f/prefix name k) v]))
(filter #(some (partial f/prefixed? (first %)) ks))
(reduce (fn source-reduction [l-source [k v]]
(let [r-entity ((:entity v) repository)
clause (condp = (:type v)
:has-one {(f/prefix name pk) (f/prefix k (:fk v))}
:belongs-to {(f/prefix name (:fk v)) (f/prefix k (:pk r-entity))}
(-> (str "Filtering and eager fetching a property of " k " is not supported.\n"
"It is supported for :has-one and :belongs-to rels only.")
IllegalArgumentException.
throw))
restrictions (f/conjunct-clauses
(f/ensure-prefixed k (:filter r-entity))
(f/ensure-prefixed k (:filter v)))
r-source (build-source
(assoc r-entity :name k)
(->> (flatten-map restrictions) (filter keyword?) (concat ks)))]
[l-source :left-join r-source (f/conjunct-clauses clause restrictions)]))
[table name]))))
(defn- build-query [entity where with-eager-fetch]
(let [{:keys [name transform]} entity
repository @(or (:repository (meta entity)) (delay {}))
eager (when with-eager-fetch
(->> (:rels entity)
(filter (comp (partial contains? repository) :entity val))
(filter (comp :eager val))
(filter (comp #{:has-one :belongs-to} :type val))))
fields (reduce (fn fields-reduction [result [k v]]
(->> (:fields ((:entity v) repository))
(map (partial f/prefix (f/prefix name k)))
(into result)))
(f/ensure-prefixed name (:fields entity))
eager)
where (f/conjunct-clauses
(f/ensure-prefixed name (:filter entity))
(f/ensure-prefixed name where))
ks (->> (flatten-map where) (concat fields) flatten (filter keyword?))
source (build-source entity ks)
opts (cond-> {:builder-fn as-entity-maps :entity entity}
transform (assoc :transform transform))]
(select (:db (meta entity)) source fields where (:order entity) nil nil opts)))
(defn- filtered-by-rel
"Determines if the `clause` map contains a keyword prefixed by one of `rel-keys`."
[clause rel-keys]
(->> (flatten-map clause)
(filter keyword?)
(some (fn [x] (some #(f/prefixed? % x) rel-keys)))))
(defrecord RelationalEntity [name table pk fields rels]
core/Entity
(create [this data]
(let [prepare (:prepare this identity)
data (prepare data)
{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
embedded-rels (filter (comp (partial contains? data) key) rels)
instance (apply dissoc data (map key embedded-rels))
dependencies (filter (comp (partial = :belongs-to) :type val) embedded-rels)
dependents (->> embedded-rels
(filter (comp #{:has-one :has-many} :type val))
(filter (complement (comp :join-table val))))
into-creation (fn into-creation [[k v]]
(-> (core/create ((:entity v) repository) (k data))
(vary-meta assoc :relation v)))
create-dependencies (->> dependencies
(map into-creation)
(map #(vary-meta % assoc :tx-propagation true))
(into [])
(#(with-meta % (assoc sql-command-meta :db db :entity this))))
owner-idx (count dependencies)
create-this (if (zero? owner-idx)
(insert db table instance)
(fn creating-entity [results]
(->> results
(map #(let [relation (:relation (meta %))
entity ((:entity relation) repository)]
[(:fk relation) ((:pk entity) %)]))
(into instance)
(insert db table))))
create-this (cond-> (vary-meta create-this assoc :entity this)
(not-empty embedded-rels) (vary-meta assoc :tx-result true))
create-dependents (->> dependents
(map (juxt (comp repository :entity val) (comp :fk val) (comp data key)))
(mapcat (fn [[entity fk instance :as v]]
(if (vector? instance)
(for [i instance] [entity fk i])
[v])))
(map (fn [[entity fk instance]]
(if (pk data)
(core/create entity (assoc instance fk (pk data)))
(fn create-dependent [results]
(->> (nth results owner-idx)
pk
(assoc instance fk)
(core/create entity))))))
(map #(vary-meta % assoc :tx-propagation true)))
create-cross-dependencies (->> embedded-rels
(filter (comp #{:has-many} :type val))
(filter (comp :join-table val))
(map (juxt (comp repository :entity val) key (comp data key)))
(mapcat (fn [[entity rel-key instances]] (for [i instances] [entity rel-key i])))
(mapcat (fn [[entity rel-key instance]]
(let [rfk-key (:pk entity)
rfk (rfk-key instance)
fk (pk data)]
(if (and fk rfk)
[(core/create-relation this fk rel-key rfk)]
[(when-not rfk (core/create entity instance))
(fn create-relation [results]
(let [fk (or fk (pk (nth results owner-idx)))
rfk (or rfk (rfk-key (last results)))]
(core/create-relation this fk rel-key rfk)))]))))
(filter some?)
(map #(vary-meta % assoc :tx-propagation true)))]
(if (empty? embedded-rels)
create-this
(-> create-dependencies
(core/then create-this)
(into create-dependents)
(into create-cross-dependencies)))))
(fetch-by-id! [this id] (-> (core/find! this {(or pk :id) id}) first))
(find [this] (core/find this nil))
(find [this where] (build-query this where true))
(find [this fields where] (build-query (assoc this :fields fields) where false))
(find-related [this relation-key where]
(let [relation (or (relation-key rels)
(-> (str "Relation " relation-key " does not exist in " name ". Try one of the following " (keys rels))
IllegalArgumentException.
throw))
repository @(:repository (meta this) (delay {}))
alias (f/prefix name relation-key)
entity ((:entity relation) repository)
transform (fn [instance] (vary-meta instance assoc :entity entity))
entity (-> entity
(assoc :name alias)
(clojure.core/update :transform #(if % (comp % transform) transform)))
where (f/ensure-prefixed name where)
r-where (->> where
(filter (comp (partial f/prefixed? alias) key))
(into {})
not-empty)
where (->> (keys r-where)
(apply dissoc where)
not-empty
(f/conjunct-clauses (f/ensure-prefixed name (:filter this))))
relation-query (build-query entity (f/conjunct-clauses (:filter relation) r-where) true)
base-query (build-query this where false)
join-table (:join-table relation)
clause (condp = (:type relation)
:has-one {(f/prefix name pk) (f/prefix alias (:fk relation))}
:belongs-to {(f/prefix name (:fk relation)) (f/prefix alias (:pk entity))}
:has-many (if join-table
{(f/prefix alias (:pk entity)) (f/prefix join-table (:rfk relation))}
{(f/prefix name pk) (f/prefix alias (:fk relation))}))
r-source (if join-table
[(:source base-query) :left-join join-table {(f/prefix name pk) (f/prefix join-table (:fk relation))}]
(:source base-query))]
(-> relation-query
(assoc :source [(:source relation-query) (if join-table :right-join :left-join) r-source clause])
(assoc :where (f/conjunct-clauses (:where relation-query) (:where base-query))))))
(update [this patch where]
(let [prepare (:prepare this identity)
patch (prepare patch)
{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
present-keys (set (keys patch))
embedded-rels (->> rels (filter (comp present-keys key)))
belongs-to-rels (->> embedded-rels (filter (comp (partial = :belongs-to) :type val)))
rel-keys (keys rels)
initial-select (when (or (not-empty embedded-rels)
(filtered-by-rel (:filter this) rel-keys)
(filtered-by-rel where rel-keys))
(->> belongs-to-rels
(map (comp :fk val))
(into [pk])
(#(core/find this % where))))
dependencies (->> belongs-to-rels
(map (fn [[k v]]
(let [entity ((:entity v) repository)
pk (:pk entity)
patch (dissoc (k patch) pk)
fk (:fk v)]
(fn [results]
(let [ids (->> (first results) (map fk) set)
ids (if (= 1 (count ids)) (first ids) (into [] ids))]
(core/update entity patch {pk ids}))))))
(map #(vary-meta % assoc :tx-propagation true)))
dependents (->> embedded-rels
(filter (comp #{:has-one :has-many} :type val))
(filter (complement (comp :join-table val)))
(map (juxt (comp repository :entity val) (comp :fk val) (comp patch key)))
(mapcat (fn [[entity fk patch :as v]]
(if (vector? patch)
(for [i patch] [entity fk i])
[v])))
(map (fn [[entity fk patch]]
(let [patch-id ((:pk entity) patch)
patch (dissoc patch (:pk entity))]
(fn [results]
(let [ids (->> (first results) (map pk) set)
ids (if (= 1 (count ids)) (first ids) (into [] ids))
clause (cond-> {fk ids}
patch-id (assoc (:pk entity) patch-id))]
(core/update entity patch clause))))))
(map #(vary-meta % assoc :tx-propagation true)))
instance (apply dissoc patch (keys embedded-rels))
base-command (when (not-empty instance)
(if initial-select
#(update db table instance {pk (->> (first %) (mapv pk))})
(update db table instance (f/conjunct-clauses (:filter this) where))))]
(if initial-select
(cond-> [initial-select]
true (with-meta (assoc sql-command-meta :db db :entity this :tx-result-fn (comp (partial reduce +) (partial drop 1))))
(not-empty dependencies) (into dependencies)
(some? base-command) (conj base-command)
(not-empty dependents) (into dependents))
base-command)))
(delete [this where]
(let [db (:db (meta this))
rel-keys (keys rels)
initial-select (when (or (filtered-by-rel (:filter this) rel-keys)
(filtered-by-rel where rel-keys))
(core/find this [pk] where))
base-command (if initial-select
(fn [results]
(let [ids (->> (first results) (mapv pk))]
(delete db table (f/conjunct-clauses (:filter this) {pk ids}))))
(delete db table (f/conjunct-clauses (:filter this) where)))]
(if initial-select
(transaction db initial-select (vary-meta base-command assoc :tx-result true))
base-command)))
(create-relation [this id rel-key rel-id]
(let [{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
relation (rel-key rels)
{:keys [type fk rfk join-table]} relation
entity ((:entity relation) repository)]
(cond
(= :belongs-to type) (core/update this {fk rel-id} {pk id})
(and (#{:has-one :has-many} type)
(not join-table)) (core/update entity {fk id} {(:pk entity) rel-id})
(and (= :has-many type)
join-table) (insert db join-table {fk id, rfk rel-id}))))
(delete-relation [this id rel-key rel-id]
(let [{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
relation (rel-key rels)
{:keys [type fk rfk join-table]} relation
entity ((:entity relation) repository)]
(cond
(= :belongs-to type) (core/update this {fk nil} {pk id, fk rel-id})
(and (#{:has-one :has-many} type)
(not join-table)) (core/update entity {fk nil} {(:pk entity) rel-id, fk id})
(and (= :has-many type)
join-table) (delete db join-table {fk id, rfk rel-id}))))
(with-filter [this where]
(clojure.core/update this :filter f/conjunct-clauses where))
(with-rels [this rels]
(clojure.core/update this :rels merge rels))
(with-eager [this rel-keys]
(let [rel-keys (if (sequential? rel-keys) rel-keys [rel-keys])
unknown-rels (complement (set (keys rels)))]
(when (some unknown-rels rel-keys)
(-> (str "Following rels are not defined for " (clojure.core/name name) ": "
(->> rel-keys (filter unknown-rels) (str/join ", ")))
IllegalArgumentException.
throw))
(clojure.core/update this :rels (partial reduce #(clojure.core/update %1 %2 assoc :eager true)) rel-keys))))
;; SQL repository
(def sql-repository-meta
{`core/transaction
(fn [this]
(transaction (:db (meta this))))
`core/add-entity
(fn add-entity [this entity]
(let [r (promise)]
(->> (assoc this (:name entity) entity)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))
`core/except
(fn except [this entity-names]
(let [r (promise)
entity-names (if (coll? entity-names)
entity-names
[entity-names])]
(->> (apply dissoc this entity-names)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))
`core/only
(fn only [this entity-names]
(let [r (promise)
entity-names (if (coll? entity-names)
entity-names
[entity-names])]
(->> (select-keys this entity-names)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))})
(defn create-entity [entity-meta entity]
(let [table (:table entity)
schema (or (namespace table) (:schema entity-meta) "public")
table (if (namespace table) (keyword (name table)) table)
fields (or
(:fields entity)
(->> (select (:db entity-meta)
:information-schema/columns
[:column-name]
{:table-schema [:ilike schema]
:table-name [:ilike (f/format-target table)]})
core/fetch!
(mapv (comp ->kebab-case-keyword :column-name))))]
(-> entity
(assoc :pk (:pk entity :id))
(assoc :fields fields)
map->RelationalEntity
(with-meta entity-meta))))
(defn get-db-meta
"Returns meta-data object for `Connectable` or `Connection`."
^java.sql.DatabaseMetaData
[db]
(if (satisfies? Sourceable db)
(with-open [con (jdbc/get-connection db)]
(.getMetaData con))
(.getMetaData db)))
(defmethod create-repository (.-name *ns*) [_ entities & [opts]]
(let [db (:db opts)
db-meta (get-db-meta db)
schema (or (:schema opts)
(->> (select db nil [['(current-schema) :current-schema]])
core/fetch!
first
:current-schema))
entity-meta (assoc opts
:db-type (.getDatabaseProductName db-meta)
:schema schema
:repository (promise))
build-entity (partial create-entity entity-meta)]
(->> entities
(map (fn [[k v]] [k (build-entity (assoc v :name k))]))
(into {})
(#(with-meta % (merge sql-repository-meta opts)))
(deliver (:repository entity-meta))
deref)))
(st/instrument `create-entity)
|
112917
|
(ns norm.sql
(:refer-clojure :exclude [find update remove])
(:require [clojure.string :as str]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[next.jdbc.protocols :refer [Sourceable]]
[next.jdbc.date-time]
[camel-snake-kebab.core :refer [->kebab-case-keyword ->kebab-case-string]]
[clojure.spec.test.alpha :as st]
[norm.core :as core :refer [where create-repository]]
[norm.sql.format :as f]
[norm.sql.jdbc :refer [as-entity-maps]]
[norm.util :refer [flatten-map meta?]])
(:import [norm.core Command Query]))
(def default-jdbc-opts
{:return-keys true
:label-fn ->kebab-case-string
:builder-fn rs/as-unqualified-modified-maps})
(defmulti generate-sql-command
"Generates SQL command depending on its type."
:type)
(defmethod generate-sql-command :insert [{:keys [target values]}]
(let [batch (vector? values)
fields (if batch (first values) (keys values))
values (if batch (rest values) [(vals values)])]
(str "INSERT INTO " (f/format-target target) " "
(f/group ", " (map f/format-field fields))
" VALUES " (->> values (map #(->> % (map f/format-field) (f/group ", "))) (str/join ", ")))))
(defmethod generate-sql-command :update [{:keys [target values where]}]
(str "UPDATE " (f/format-target target)
" SET " (->> values
(map #(str (f/format-field (key %)) " = " (f/format-field (val %))))
(str/join ", "))
(when where (str " WHERE " (f/format-clause where)))))
(defmethod generate-sql-command :delete [{:keys [target where]}]
(str "DELETE FROM " (f/format-target target)
(when where (str " WHERE " (f/format-clause where)))))
(defmethod generate-sql-command :default [x] (str x))
(defn- execute-sql-command [command]
(let [{:keys [type values where]} command
db (:db (meta command))
params (if (vector? values) (flatten (rest values)) (and values (f/extract-values values)))
params (if where (concat params (f/extract-values where)) params)
command (apply vector (generate-sql-command command) params)]
(jdbc/execute-one! db command (when (= :insert type) default-jdbc-opts))))
(declare sql-command-meta)
(defn transaction
"Constructs chain of commands that will be executed in a transaction."
^Command
[db & commands]
(if (vector? (first commands))
(into (first commands) (rest commands))
(with-meta (into [] commands) (assoc sql-command-meta :db db))))
(defn- execute-transaction [tx transaction]
(loop [results []
commands transaction
tx-result nil]
(if (not-empty commands)
(let [command (-> (first commands) (vary-meta assoc :db tx))
command (if (fn? command)
(-> (command results) (vary-meta merge (meta command)))
command)
result (core/execute! command)]
(recur (conj results result) (rest commands) (if (:tx-result (meta command)) result tx-result)))
(if-let [tx-result-fn (:tx-result-fn (meta transaction))]
(tx-result-fn results)
(if tx-result
tx-result
results)))))
(def sql-command-meta
"Implementation of `Command` protocol."
{`core/execute! (fn execute-command [command]
(let [{:keys [db entity relation]} (meta command)
default-result (cond-> (:values command)
(:pk entity) (select-keys [(:pk entity)]))
result (if (vector? command)
(if (:tx-propagation (meta command))
(execute-transaction db command)
(jdbc/with-transaction [tx db] (execute-transaction tx command)))
(or (execute-sql-command command) default-result))]
(cond-> result
(and (meta? result) entity) (vary-meta assoc :entity entity)
(and (meta? result) relation) (vary-meta assoc :relation relation)
(#{:update :delete} (:type command)) :next.jdbc/update-count)))
`core/then (fn then [command next-command]
(if next-command
(transaction (:db (meta command)) command next-command)
command))})
(defn insert
"Constructs an insert command."
^Command
[db target values]
(-> {:type :insert :target target :values values}
(with-meta (assoc sql-command-meta :db db))))
(defn update
"Constructs an update command."
^Command
[db target values where]
(-> {:type :update :target target :values values :where where}
(with-meta (assoc sql-command-meta :db db))))
(defn delete
"Constructs a delete command."
^Command
[db target where]
(-> {:type :delete :target target :where where}
(with-meta (assoc sql-command-meta :db db))))
;; Query builder
(defrecord SQLQuery [source fields where order offset limit jdbc-opts]
core/Command
(execute! [this]
(let [values (f/extract-values [this])
query (apply vector (str this) values)
{:keys [db transform]} (meta this)]
(cond->> (jdbc/execute! db query (merge default-jdbc-opts jdbc-opts))
transform (mapv transform))))
(then [this next-command] (transaction (:db (meta this)) this next-command))
core/Query
(where [this clauses]
(let [exact (:exact (meta clauses))
entity (:entity (meta this))
clauses (if (and (not exact) entity)
(f/ensure-prefixed (:name entity) clauses)
clauses)]
(assoc this :where (f/conjunct-clauses where clauses))))
(order [this order]
(let [exact (:exact (meta order))
entity (:entity (meta this))
order (if (and (not exact) entity)
(f/ensure-prefixed (:name entity) order)
order)]
(assoc this :order order)))
(skip [this amount] (assoc this :offset amount))
(limit [this amount] (assoc this :limit amount))
(fetch! [this] (core/execute! this))
(fetch! [this fields] (core/fetch! (assoc this :fields fields)))
(fetch-count! [this]
(-> this
(assoc :fields [['(count :*) :count]]
:order nil
:offset nil
:limit nil)
core/fetch!
first
:count))
Object
(toString [this]
(cond-> (str "SELECT " (->> (or fields [:*])
(map #(if (and (keyword? %) (not= "*" (name %))) [% %] %))
(map f/format-field)
(str/join ", ")))
source (str " FROM " (f/format-source source))
(seq where) (str " WHERE " (f/format-clause where))
(:group-by this) (str " GROUP BY " (->> (:group-by this) (map f/format-field) (str/join ", ")))
(:having this) (str " HAVING " (f/format-clause (:having this)))
(seq order) (str " ORDER BY " (f/format-order order))
limit (str " LIMIT ?")
offset (str " OFFSET ?"))))
(defn select
"Constructs a query."
^SQLQuery
([db source] (select db source nil))
([db source fields] (select db source fields nil))
([db source fields where] (select db source fields where nil))
([db source fields where order] (select db source fields where order nil))
([db source fields where order offset] (select db source fields where order offset nil))
([db source fields where order offset limit] (select db source fields where order offset limit nil))
([db source fields where order offset limit jdbc-opts]
(-> (->SQLQuery source fields where order offset limit jdbc-opts)
(with-meta (merge jdbc-opts {:db db})))))
(defn join
"Adds `source` to the query joining it with specified `op`eration.
Example:
```
(-> users-query
(join :left-join :people {:users/person-id :people/id})
(where {:people/name \"<NAME>\"})
fetch!)
```"
[query op r-source clause] (assoc query :source [(:source query) op r-source clause]))
;; Relational entity
(defn- build-source [entity ks]
(let [{:keys [table name pk rels]} entity
repository @(or (:repository (meta entity)) (delay {}))]
(->> rels
(filter (comp (partial contains? repository) :entity val))
(map (fn [[k v]] [(f/prefix name k) v]))
(filter #(some (partial f/prefixed? (first %)) ks))
(reduce (fn source-reduction [l-source [k v]]
(let [r-entity ((:entity v) repository)
clause (condp = (:type v)
:has-one {(f/prefix name pk) (f/prefix k (:fk v))}
:belongs-to {(f/prefix name (:fk v)) (f/prefix k (:pk r-entity))}
(-> (str "Filtering and eager fetching a property of " k " is not supported.\n"
"It is supported for :has-one and :belongs-to rels only.")
IllegalArgumentException.
throw))
restrictions (f/conjunct-clauses
(f/ensure-prefixed k (:filter r-entity))
(f/ensure-prefixed k (:filter v)))
r-source (build-source
(assoc r-entity :name k)
(->> (flatten-map restrictions) (filter keyword?) (concat ks)))]
[l-source :left-join r-source (f/conjunct-clauses clause restrictions)]))
[table name]))))
(defn- build-query [entity where with-eager-fetch]
(let [{:keys [name transform]} entity
repository @(or (:repository (meta entity)) (delay {}))
eager (when with-eager-fetch
(->> (:rels entity)
(filter (comp (partial contains? repository) :entity val))
(filter (comp :eager val))
(filter (comp #{:has-one :belongs-to} :type val))))
fields (reduce (fn fields-reduction [result [k v]]
(->> (:fields ((:entity v) repository))
(map (partial f/prefix (f/prefix name k)))
(into result)))
(f/ensure-prefixed name (:fields entity))
eager)
where (f/conjunct-clauses
(f/ensure-prefixed name (:filter entity))
(f/ensure-prefixed name where))
ks (->> (flatten-map where) (concat fields) flatten (filter keyword?))
source (build-source entity ks)
opts (cond-> {:builder-fn as-entity-maps :entity entity}
transform (assoc :transform transform))]
(select (:db (meta entity)) source fields where (:order entity) nil nil opts)))
(defn- filtered-by-rel
"Determines if the `clause` map contains a keyword prefixed by one of `rel-keys`."
[clause rel-keys]
(->> (flatten-map clause)
(filter keyword?)
(some (fn [x] (some #(f/prefixed? % x) rel-keys)))))
(defrecord RelationalEntity [name table pk fields rels]
core/Entity
(create [this data]
(let [prepare (:prepare this identity)
data (prepare data)
{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
embedded-rels (filter (comp (partial contains? data) key) rels)
instance (apply dissoc data (map key embedded-rels))
dependencies (filter (comp (partial = :belongs-to) :type val) embedded-rels)
dependents (->> embedded-rels
(filter (comp #{:has-one :has-many} :type val))
(filter (complement (comp :join-table val))))
into-creation (fn into-creation [[k v]]
(-> (core/create ((:entity v) repository) (k data))
(vary-meta assoc :relation v)))
create-dependencies (->> dependencies
(map into-creation)
(map #(vary-meta % assoc :tx-propagation true))
(into [])
(#(with-meta % (assoc sql-command-meta :db db :entity this))))
owner-idx (count dependencies)
create-this (if (zero? owner-idx)
(insert db table instance)
(fn creating-entity [results]
(->> results
(map #(let [relation (:relation (meta %))
entity ((:entity relation) repository)]
[(:fk relation) ((:pk entity) %)]))
(into instance)
(insert db table))))
create-this (cond-> (vary-meta create-this assoc :entity this)
(not-empty embedded-rels) (vary-meta assoc :tx-result true))
create-dependents (->> dependents
(map (juxt (comp repository :entity val) (comp :fk val) (comp data key)))
(mapcat (fn [[entity fk instance :as v]]
(if (vector? instance)
(for [i instance] [entity fk i])
[v])))
(map (fn [[entity fk instance]]
(if (pk data)
(core/create entity (assoc instance fk (pk data)))
(fn create-dependent [results]
(->> (nth results owner-idx)
pk
(assoc instance fk)
(core/create entity))))))
(map #(vary-meta % assoc :tx-propagation true)))
create-cross-dependencies (->> embedded-rels
(filter (comp #{:has-many} :type val))
(filter (comp :join-table val))
(map (juxt (comp repository :entity val) key (comp data key)))
(mapcat (fn [[entity rel-key instances]] (for [i instances] [entity rel-key i])))
(mapcat (fn [[entity rel-key instance]]
(let [rfk-key (:pk entity)
rfk (rfk-key instance)
fk (pk data)]
(if (and fk rfk)
[(core/create-relation this fk rel-key rfk)]
[(when-not rfk (core/create entity instance))
(fn create-relation [results]
(let [fk (or fk (pk (nth results owner-idx)))
rfk (or rfk (rfk-key (last results)))]
(core/create-relation this fk rel-key rfk)))]))))
(filter some?)
(map #(vary-meta % assoc :tx-propagation true)))]
(if (empty? embedded-rels)
create-this
(-> create-dependencies
(core/then create-this)
(into create-dependents)
(into create-cross-dependencies)))))
(fetch-by-id! [this id] (-> (core/find! this {(or pk :id) id}) first))
(find [this] (core/find this nil))
(find [this where] (build-query this where true))
(find [this fields where] (build-query (assoc this :fields fields) where false))
(find-related [this relation-key where]
(let [relation (or (relation-key rels)
(-> (str "Relation " relation-key " does not exist in " name ". Try one of the following " (keys rels))
IllegalArgumentException.
throw))
repository @(:repository (meta this) (delay {}))
alias (f/prefix name relation-key)
entity ((:entity relation) repository)
transform (fn [instance] (vary-meta instance assoc :entity entity))
entity (-> entity
(assoc :name alias)
(clojure.core/update :transform #(if % (comp % transform) transform)))
where (f/ensure-prefixed name where)
r-where (->> where
(filter (comp (partial f/prefixed? alias) key))
(into {})
not-empty)
where (->> (keys r-where)
(apply dissoc where)
not-empty
(f/conjunct-clauses (f/ensure-prefixed name (:filter this))))
relation-query (build-query entity (f/conjunct-clauses (:filter relation) r-where) true)
base-query (build-query this where false)
join-table (:join-table relation)
clause (condp = (:type relation)
:has-one {(f/prefix name pk) (f/prefix alias (:fk relation))}
:belongs-to {(f/prefix name (:fk relation)) (f/prefix alias (:pk entity))}
:has-many (if join-table
{(f/prefix alias (:pk entity)) (f/prefix join-table (:rfk relation))}
{(f/prefix name pk) (f/prefix alias (:fk relation))}))
r-source (if join-table
[(:source base-query) :left-join join-table {(f/prefix name pk) (f/prefix join-table (:fk relation))}]
(:source base-query))]
(-> relation-query
(assoc :source [(:source relation-query) (if join-table :right-join :left-join) r-source clause])
(assoc :where (f/conjunct-clauses (:where relation-query) (:where base-query))))))
(update [this patch where]
(let [prepare (:prepare this identity)
patch (prepare patch)
{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
present-keys (set (keys patch))
embedded-rels (->> rels (filter (comp present-keys key)))
belongs-to-rels (->> embedded-rels (filter (comp (partial = :belongs-to) :type val)))
rel-keys (keys rel<KEY>)
initial-select (when (or (not-empty embedded-rels)
(filtered-by-rel (:filter this) rel-keys)
(filtered-by-rel where rel-keys))
(->> belongs-to-rels
(map (comp :fk val))
(into [pk])
(#(core/find this % where))))
dependencies (->> belongs-to-rels
(map (fn [[k v]]
(let [entity ((:entity v) repository)
pk (:pk entity)
patch (dissoc (k patch) pk)
fk (:fk v)]
(fn [results]
(let [ids (->> (first results) (map fk) set)
ids (if (= 1 (count ids)) (first ids) (into [] ids))]
(core/update entity patch {pk ids}))))))
(map #(vary-meta % assoc :tx-propagation true)))
dependents (->> embedded-rels
(filter (comp #{:has-one :has-many} :type val))
(filter (complement (comp :join-table val)))
(map (juxt (comp repository :entity val) (comp :fk val) (comp patch key)))
(mapcat (fn [[entity fk patch :as v]]
(if (vector? patch)
(for [i patch] [entity fk i])
[v])))
(map (fn [[entity fk patch]]
(let [patch-id ((:pk entity) patch)
patch (dissoc patch (:pk entity))]
(fn [results]
(let [ids (->> (first results) (map pk) set)
ids (if (= 1 (count ids)) (first ids) (into [] ids))
clause (cond-> {fk ids}
patch-id (assoc (:pk entity) patch-id))]
(core/update entity patch clause))))))
(map #(vary-meta % assoc :tx-propagation true)))
instance (apply dissoc patch (keys embedded-rels))
base-command (when (not-empty instance)
(if initial-select
#(update db table instance {pk (->> (first %) (mapv pk))})
(update db table instance (f/conjunct-clauses (:filter this) where))))]
(if initial-select
(cond-> [initial-select]
true (with-meta (assoc sql-command-meta :db db :entity this :tx-result-fn (comp (partial reduce +) (partial drop 1))))
(not-empty dependencies) (into dependencies)
(some? base-command) (conj base-command)
(not-empty dependents) (into dependents))
base-command)))
(delete [this where]
(let [db (:db (meta this))
rel-keys (keys rels)
initial-select (when (or (filtered-by-rel (:filter this) rel-keys)
(filtered-by-rel where rel-keys))
(core/find this [pk] where))
base-command (if initial-select
(fn [results]
(let [ids (->> (first results) (mapv pk))]
(delete db table (f/conjunct-clauses (:filter this) {pk ids}))))
(delete db table (f/conjunct-clauses (:filter this) where)))]
(if initial-select
(transaction db initial-select (vary-meta base-command assoc :tx-result true))
base-command)))
(create-relation [this id rel-key rel-id]
(let [{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
relation (rel-key rels)
{:keys [type fk rfk join-table]} relation
entity ((:entity relation) repository)]
(cond
(= :belongs-to type) (core/update this {fk rel-id} {pk id})
(and (#{:has-one :has-many} type)
(not join-table)) (core/update entity {fk id} {(:pk entity) rel-id})
(and (= :has-many type)
join-table) (insert db join-table {fk id, rfk rel-id}))))
(delete-relation [this id rel-key rel-id]
(let [{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
relation (rel-key rels)
{:keys [type fk rfk join-table]} relation
entity ((:entity relation) repository)]
(cond
(= :belongs-to type) (core/update this {fk nil} {pk id, fk rel-id})
(and (#{:has-one :has-many} type)
(not join-table)) (core/update entity {fk nil} {(:pk entity) rel-id, fk id})
(and (= :has-many type)
join-table) (delete db join-table {fk id, rfk rel-id}))))
(with-filter [this where]
(clojure.core/update this :filter f/conjunct-clauses where))
(with-rels [this rels]
(clojure.core/update this :rels merge rels))
(with-eager [this rel-keys]
(let [rel-keys (if (sequential? rel-keys) rel-keys [rel-keys])
unknown-rels (complement (set (keys rels)))]
(when (some unknown-rels rel-keys)
(-> (str "Following rels are not defined for " (clojure.core/name name) ": "
(->> rel-keys (filter unknown-rels) (str/join ", ")))
IllegalArgumentException.
throw))
(clojure.core/update this :rels (partial reduce #(clojure.core/update %1 %2 assoc :eager true)) rel-keys))))
;; SQL repository
(def sql-repository-meta
{`core/transaction
(fn [this]
(transaction (:db (meta this))))
`core/add-entity
(fn add-entity [this entity]
(let [r (promise)]
(->> (assoc this (:name entity) entity)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))
`core/except
(fn except [this entity-names]
(let [r (promise)
entity-names (if (coll? entity-names)
entity-names
[entity-names])]
(->> (apply dissoc this entity-names)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))
`core/only
(fn only [this entity-names]
(let [r (promise)
entity-names (if (coll? entity-names)
entity-names
[entity-names])]
(->> (select-keys this entity-names)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))})
(defn create-entity [entity-meta entity]
(let [table (:table entity)
schema (or (namespace table) (:schema entity-meta) "public")
table (if (namespace table) (keyword (name table)) table)
fields (or
(:fields entity)
(->> (select (:db entity-meta)
:information-schema/columns
[:column-name]
{:table-schema [:ilike schema]
:table-name [:ilike (f/format-target table)]})
core/fetch!
(mapv (comp ->kebab-case-keyword :column-name))))]
(-> entity
(assoc :pk (:pk entity :id))
(assoc :fields fields)
map->RelationalEntity
(with-meta entity-meta))))
(defn get-db-meta
"Returns meta-data object for `Connectable` or `Connection`."
^java.sql.DatabaseMetaData
[db]
(if (satisfies? Sourceable db)
(with-open [con (jdbc/get-connection db)]
(.getMetaData con))
(.getMetaData db)))
(defmethod create-repository (.-name *ns*) [_ entities & [opts]]
(let [db (:db opts)
db-meta (get-db-meta db)
schema (or (:schema opts)
(->> (select db nil [['(current-schema) :current-schema]])
core/fetch!
first
:current-schema))
entity-meta (assoc opts
:db-type (.getDatabaseProductName db-meta)
:schema schema
:repository (promise))
build-entity (partial create-entity entity-meta)]
(->> entities
(map (fn [[k v]] [k (build-entity (assoc v :name k))]))
(into {})
(#(with-meta % (merge sql-repository-meta opts)))
(deliver (:repository entity-meta))
deref)))
(st/instrument `create-entity)
| true |
(ns norm.sql
(:refer-clojure :exclude [find update remove])
(:require [clojure.string :as str]
[next.jdbc :as jdbc]
[next.jdbc.result-set :as rs]
[next.jdbc.protocols :refer [Sourceable]]
[next.jdbc.date-time]
[camel-snake-kebab.core :refer [->kebab-case-keyword ->kebab-case-string]]
[clojure.spec.test.alpha :as st]
[norm.core :as core :refer [where create-repository]]
[norm.sql.format :as f]
[norm.sql.jdbc :refer [as-entity-maps]]
[norm.util :refer [flatten-map meta?]])
(:import [norm.core Command Query]))
(def default-jdbc-opts
{:return-keys true
:label-fn ->kebab-case-string
:builder-fn rs/as-unqualified-modified-maps})
(defmulti generate-sql-command
"Generates SQL command depending on its type."
:type)
(defmethod generate-sql-command :insert [{:keys [target values]}]
(let [batch (vector? values)
fields (if batch (first values) (keys values))
values (if batch (rest values) [(vals values)])]
(str "INSERT INTO " (f/format-target target) " "
(f/group ", " (map f/format-field fields))
" VALUES " (->> values (map #(->> % (map f/format-field) (f/group ", "))) (str/join ", ")))))
(defmethod generate-sql-command :update [{:keys [target values where]}]
(str "UPDATE " (f/format-target target)
" SET " (->> values
(map #(str (f/format-field (key %)) " = " (f/format-field (val %))))
(str/join ", "))
(when where (str " WHERE " (f/format-clause where)))))
(defmethod generate-sql-command :delete [{:keys [target where]}]
(str "DELETE FROM " (f/format-target target)
(when where (str " WHERE " (f/format-clause where)))))
(defmethod generate-sql-command :default [x] (str x))
(defn- execute-sql-command [command]
(let [{:keys [type values where]} command
db (:db (meta command))
params (if (vector? values) (flatten (rest values)) (and values (f/extract-values values)))
params (if where (concat params (f/extract-values where)) params)
command (apply vector (generate-sql-command command) params)]
(jdbc/execute-one! db command (when (= :insert type) default-jdbc-opts))))
(declare sql-command-meta)
(defn transaction
"Constructs chain of commands that will be executed in a transaction."
^Command
[db & commands]
(if (vector? (first commands))
(into (first commands) (rest commands))
(with-meta (into [] commands) (assoc sql-command-meta :db db))))
(defn- execute-transaction [tx transaction]
(loop [results []
commands transaction
tx-result nil]
(if (not-empty commands)
(let [command (-> (first commands) (vary-meta assoc :db tx))
command (if (fn? command)
(-> (command results) (vary-meta merge (meta command)))
command)
result (core/execute! command)]
(recur (conj results result) (rest commands) (if (:tx-result (meta command)) result tx-result)))
(if-let [tx-result-fn (:tx-result-fn (meta transaction))]
(tx-result-fn results)
(if tx-result
tx-result
results)))))
(def sql-command-meta
"Implementation of `Command` protocol."
{`core/execute! (fn execute-command [command]
(let [{:keys [db entity relation]} (meta command)
default-result (cond-> (:values command)
(:pk entity) (select-keys [(:pk entity)]))
result (if (vector? command)
(if (:tx-propagation (meta command))
(execute-transaction db command)
(jdbc/with-transaction [tx db] (execute-transaction tx command)))
(or (execute-sql-command command) default-result))]
(cond-> result
(and (meta? result) entity) (vary-meta assoc :entity entity)
(and (meta? result) relation) (vary-meta assoc :relation relation)
(#{:update :delete} (:type command)) :next.jdbc/update-count)))
`core/then (fn then [command next-command]
(if next-command
(transaction (:db (meta command)) command next-command)
command))})
(defn insert
"Constructs an insert command."
^Command
[db target values]
(-> {:type :insert :target target :values values}
(with-meta (assoc sql-command-meta :db db))))
(defn update
"Constructs an update command."
^Command
[db target values where]
(-> {:type :update :target target :values values :where where}
(with-meta (assoc sql-command-meta :db db))))
(defn delete
"Constructs a delete command."
^Command
[db target where]
(-> {:type :delete :target target :where where}
(with-meta (assoc sql-command-meta :db db))))
;; Query builder
(defrecord SQLQuery [source fields where order offset limit jdbc-opts]
core/Command
(execute! [this]
(let [values (f/extract-values [this])
query (apply vector (str this) values)
{:keys [db transform]} (meta this)]
(cond->> (jdbc/execute! db query (merge default-jdbc-opts jdbc-opts))
transform (mapv transform))))
(then [this next-command] (transaction (:db (meta this)) this next-command))
core/Query
(where [this clauses]
(let [exact (:exact (meta clauses))
entity (:entity (meta this))
clauses (if (and (not exact) entity)
(f/ensure-prefixed (:name entity) clauses)
clauses)]
(assoc this :where (f/conjunct-clauses where clauses))))
(order [this order]
(let [exact (:exact (meta order))
entity (:entity (meta this))
order (if (and (not exact) entity)
(f/ensure-prefixed (:name entity) order)
order)]
(assoc this :order order)))
(skip [this amount] (assoc this :offset amount))
(limit [this amount] (assoc this :limit amount))
(fetch! [this] (core/execute! this))
(fetch! [this fields] (core/fetch! (assoc this :fields fields)))
(fetch-count! [this]
(-> this
(assoc :fields [['(count :*) :count]]
:order nil
:offset nil
:limit nil)
core/fetch!
first
:count))
Object
(toString [this]
(cond-> (str "SELECT " (->> (or fields [:*])
(map #(if (and (keyword? %) (not= "*" (name %))) [% %] %))
(map f/format-field)
(str/join ", ")))
source (str " FROM " (f/format-source source))
(seq where) (str " WHERE " (f/format-clause where))
(:group-by this) (str " GROUP BY " (->> (:group-by this) (map f/format-field) (str/join ", ")))
(:having this) (str " HAVING " (f/format-clause (:having this)))
(seq order) (str " ORDER BY " (f/format-order order))
limit (str " LIMIT ?")
offset (str " OFFSET ?"))))
(defn select
"Constructs a query."
^SQLQuery
([db source] (select db source nil))
([db source fields] (select db source fields nil))
([db source fields where] (select db source fields where nil))
([db source fields where order] (select db source fields where order nil))
([db source fields where order offset] (select db source fields where order offset nil))
([db source fields where order offset limit] (select db source fields where order offset limit nil))
([db source fields where order offset limit jdbc-opts]
(-> (->SQLQuery source fields where order offset limit jdbc-opts)
(with-meta (merge jdbc-opts {:db db})))))
(defn join
"Adds `source` to the query joining it with specified `op`eration.
Example:
```
(-> users-query
(join :left-join :people {:users/person-id :people/id})
(where {:people/name \"PI:NAME:<NAME>END_PI\"})
fetch!)
```"
[query op r-source clause] (assoc query :source [(:source query) op r-source clause]))
;; Relational entity
(defn- build-source [entity ks]
(let [{:keys [table name pk rels]} entity
repository @(or (:repository (meta entity)) (delay {}))]
(->> rels
(filter (comp (partial contains? repository) :entity val))
(map (fn [[k v]] [(f/prefix name k) v]))
(filter #(some (partial f/prefixed? (first %)) ks))
(reduce (fn source-reduction [l-source [k v]]
(let [r-entity ((:entity v) repository)
clause (condp = (:type v)
:has-one {(f/prefix name pk) (f/prefix k (:fk v))}
:belongs-to {(f/prefix name (:fk v)) (f/prefix k (:pk r-entity))}
(-> (str "Filtering and eager fetching a property of " k " is not supported.\n"
"It is supported for :has-one and :belongs-to rels only.")
IllegalArgumentException.
throw))
restrictions (f/conjunct-clauses
(f/ensure-prefixed k (:filter r-entity))
(f/ensure-prefixed k (:filter v)))
r-source (build-source
(assoc r-entity :name k)
(->> (flatten-map restrictions) (filter keyword?) (concat ks)))]
[l-source :left-join r-source (f/conjunct-clauses clause restrictions)]))
[table name]))))
(defn- build-query [entity where with-eager-fetch]
(let [{:keys [name transform]} entity
repository @(or (:repository (meta entity)) (delay {}))
eager (when with-eager-fetch
(->> (:rels entity)
(filter (comp (partial contains? repository) :entity val))
(filter (comp :eager val))
(filter (comp #{:has-one :belongs-to} :type val))))
fields (reduce (fn fields-reduction [result [k v]]
(->> (:fields ((:entity v) repository))
(map (partial f/prefix (f/prefix name k)))
(into result)))
(f/ensure-prefixed name (:fields entity))
eager)
where (f/conjunct-clauses
(f/ensure-prefixed name (:filter entity))
(f/ensure-prefixed name where))
ks (->> (flatten-map where) (concat fields) flatten (filter keyword?))
source (build-source entity ks)
opts (cond-> {:builder-fn as-entity-maps :entity entity}
transform (assoc :transform transform))]
(select (:db (meta entity)) source fields where (:order entity) nil nil opts)))
(defn- filtered-by-rel
"Determines if the `clause` map contains a keyword prefixed by one of `rel-keys`."
[clause rel-keys]
(->> (flatten-map clause)
(filter keyword?)
(some (fn [x] (some #(f/prefixed? % x) rel-keys)))))
(defrecord RelationalEntity [name table pk fields rels]
core/Entity
(create [this data]
(let [prepare (:prepare this identity)
data (prepare data)
{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
embedded-rels (filter (comp (partial contains? data) key) rels)
instance (apply dissoc data (map key embedded-rels))
dependencies (filter (comp (partial = :belongs-to) :type val) embedded-rels)
dependents (->> embedded-rels
(filter (comp #{:has-one :has-many} :type val))
(filter (complement (comp :join-table val))))
into-creation (fn into-creation [[k v]]
(-> (core/create ((:entity v) repository) (k data))
(vary-meta assoc :relation v)))
create-dependencies (->> dependencies
(map into-creation)
(map #(vary-meta % assoc :tx-propagation true))
(into [])
(#(with-meta % (assoc sql-command-meta :db db :entity this))))
owner-idx (count dependencies)
create-this (if (zero? owner-idx)
(insert db table instance)
(fn creating-entity [results]
(->> results
(map #(let [relation (:relation (meta %))
entity ((:entity relation) repository)]
[(:fk relation) ((:pk entity) %)]))
(into instance)
(insert db table))))
create-this (cond-> (vary-meta create-this assoc :entity this)
(not-empty embedded-rels) (vary-meta assoc :tx-result true))
create-dependents (->> dependents
(map (juxt (comp repository :entity val) (comp :fk val) (comp data key)))
(mapcat (fn [[entity fk instance :as v]]
(if (vector? instance)
(for [i instance] [entity fk i])
[v])))
(map (fn [[entity fk instance]]
(if (pk data)
(core/create entity (assoc instance fk (pk data)))
(fn create-dependent [results]
(->> (nth results owner-idx)
pk
(assoc instance fk)
(core/create entity))))))
(map #(vary-meta % assoc :tx-propagation true)))
create-cross-dependencies (->> embedded-rels
(filter (comp #{:has-many} :type val))
(filter (comp :join-table val))
(map (juxt (comp repository :entity val) key (comp data key)))
(mapcat (fn [[entity rel-key instances]] (for [i instances] [entity rel-key i])))
(mapcat (fn [[entity rel-key instance]]
(let [rfk-key (:pk entity)
rfk (rfk-key instance)
fk (pk data)]
(if (and fk rfk)
[(core/create-relation this fk rel-key rfk)]
[(when-not rfk (core/create entity instance))
(fn create-relation [results]
(let [fk (or fk (pk (nth results owner-idx)))
rfk (or rfk (rfk-key (last results)))]
(core/create-relation this fk rel-key rfk)))]))))
(filter some?)
(map #(vary-meta % assoc :tx-propagation true)))]
(if (empty? embedded-rels)
create-this
(-> create-dependencies
(core/then create-this)
(into create-dependents)
(into create-cross-dependencies)))))
(fetch-by-id! [this id] (-> (core/find! this {(or pk :id) id}) first))
(find [this] (core/find this nil))
(find [this where] (build-query this where true))
(find [this fields where] (build-query (assoc this :fields fields) where false))
(find-related [this relation-key where]
(let [relation (or (relation-key rels)
(-> (str "Relation " relation-key " does not exist in " name ". Try one of the following " (keys rels))
IllegalArgumentException.
throw))
repository @(:repository (meta this) (delay {}))
alias (f/prefix name relation-key)
entity ((:entity relation) repository)
transform (fn [instance] (vary-meta instance assoc :entity entity))
entity (-> entity
(assoc :name alias)
(clojure.core/update :transform #(if % (comp % transform) transform)))
where (f/ensure-prefixed name where)
r-where (->> where
(filter (comp (partial f/prefixed? alias) key))
(into {})
not-empty)
where (->> (keys r-where)
(apply dissoc where)
not-empty
(f/conjunct-clauses (f/ensure-prefixed name (:filter this))))
relation-query (build-query entity (f/conjunct-clauses (:filter relation) r-where) true)
base-query (build-query this where false)
join-table (:join-table relation)
clause (condp = (:type relation)
:has-one {(f/prefix name pk) (f/prefix alias (:fk relation))}
:belongs-to {(f/prefix name (:fk relation)) (f/prefix alias (:pk entity))}
:has-many (if join-table
{(f/prefix alias (:pk entity)) (f/prefix join-table (:rfk relation))}
{(f/prefix name pk) (f/prefix alias (:fk relation))}))
r-source (if join-table
[(:source base-query) :left-join join-table {(f/prefix name pk) (f/prefix join-table (:fk relation))}]
(:source base-query))]
(-> relation-query
(assoc :source [(:source relation-query) (if join-table :right-join :left-join) r-source clause])
(assoc :where (f/conjunct-clauses (:where relation-query) (:where base-query))))))
(update [this patch where]
(let [prepare (:prepare this identity)
patch (prepare patch)
{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
present-keys (set (keys patch))
embedded-rels (->> rels (filter (comp present-keys key)))
belongs-to-rels (->> embedded-rels (filter (comp (partial = :belongs-to) :type val)))
rel-keys (keys relPI:KEY:<KEY>END_PI)
initial-select (when (or (not-empty embedded-rels)
(filtered-by-rel (:filter this) rel-keys)
(filtered-by-rel where rel-keys))
(->> belongs-to-rels
(map (comp :fk val))
(into [pk])
(#(core/find this % where))))
dependencies (->> belongs-to-rels
(map (fn [[k v]]
(let [entity ((:entity v) repository)
pk (:pk entity)
patch (dissoc (k patch) pk)
fk (:fk v)]
(fn [results]
(let [ids (->> (first results) (map fk) set)
ids (if (= 1 (count ids)) (first ids) (into [] ids))]
(core/update entity patch {pk ids}))))))
(map #(vary-meta % assoc :tx-propagation true)))
dependents (->> embedded-rels
(filter (comp #{:has-one :has-many} :type val))
(filter (complement (comp :join-table val)))
(map (juxt (comp repository :entity val) (comp :fk val) (comp patch key)))
(mapcat (fn [[entity fk patch :as v]]
(if (vector? patch)
(for [i patch] [entity fk i])
[v])))
(map (fn [[entity fk patch]]
(let [patch-id ((:pk entity) patch)
patch (dissoc patch (:pk entity))]
(fn [results]
(let [ids (->> (first results) (map pk) set)
ids (if (= 1 (count ids)) (first ids) (into [] ids))
clause (cond-> {fk ids}
patch-id (assoc (:pk entity) patch-id))]
(core/update entity patch clause))))))
(map #(vary-meta % assoc :tx-propagation true)))
instance (apply dissoc patch (keys embedded-rels))
base-command (when (not-empty instance)
(if initial-select
#(update db table instance {pk (->> (first %) (mapv pk))})
(update db table instance (f/conjunct-clauses (:filter this) where))))]
(if initial-select
(cond-> [initial-select]
true (with-meta (assoc sql-command-meta :db db :entity this :tx-result-fn (comp (partial reduce +) (partial drop 1))))
(not-empty dependencies) (into dependencies)
(some? base-command) (conj base-command)
(not-empty dependents) (into dependents))
base-command)))
(delete [this where]
(let [db (:db (meta this))
rel-keys (keys rels)
initial-select (when (or (filtered-by-rel (:filter this) rel-keys)
(filtered-by-rel where rel-keys))
(core/find this [pk] where))
base-command (if initial-select
(fn [results]
(let [ids (->> (first results) (mapv pk))]
(delete db table (f/conjunct-clauses (:filter this) {pk ids}))))
(delete db table (f/conjunct-clauses (:filter this) where)))]
(if initial-select
(transaction db initial-select (vary-meta base-command assoc :tx-result true))
base-command)))
(create-relation [this id rel-key rel-id]
(let [{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
relation (rel-key rels)
{:keys [type fk rfk join-table]} relation
entity ((:entity relation) repository)]
(cond
(= :belongs-to type) (core/update this {fk rel-id} {pk id})
(and (#{:has-one :has-many} type)
(not join-table)) (core/update entity {fk id} {(:pk entity) rel-id})
(and (= :has-many type)
join-table) (insert db join-table {fk id, rfk rel-id}))))
(delete-relation [this id rel-key rel-id]
(let [{:keys [db repository]} (meta this)
repository @(or repository (delay {}))
relation (rel-key rels)
{:keys [type fk rfk join-table]} relation
entity ((:entity relation) repository)]
(cond
(= :belongs-to type) (core/update this {fk nil} {pk id, fk rel-id})
(and (#{:has-one :has-many} type)
(not join-table)) (core/update entity {fk nil} {(:pk entity) rel-id, fk id})
(and (= :has-many type)
join-table) (delete db join-table {fk id, rfk rel-id}))))
(with-filter [this where]
(clojure.core/update this :filter f/conjunct-clauses where))
(with-rels [this rels]
(clojure.core/update this :rels merge rels))
(with-eager [this rel-keys]
(let [rel-keys (if (sequential? rel-keys) rel-keys [rel-keys])
unknown-rels (complement (set (keys rels)))]
(when (some unknown-rels rel-keys)
(-> (str "Following rels are not defined for " (clojure.core/name name) ": "
(->> rel-keys (filter unknown-rels) (str/join ", ")))
IllegalArgumentException.
throw))
(clojure.core/update this :rels (partial reduce #(clojure.core/update %1 %2 assoc :eager true)) rel-keys))))
;; SQL repository
(def sql-repository-meta
{`core/transaction
(fn [this]
(transaction (:db (meta this))))
`core/add-entity
(fn add-entity [this entity]
(let [r (promise)]
(->> (assoc this (:name entity) entity)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))
`core/except
(fn except [this entity-names]
(let [r (promise)
entity-names (if (coll? entity-names)
entity-names
[entity-names])]
(->> (apply dissoc this entity-names)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))
`core/only
(fn only [this entity-names]
(let [r (promise)
entity-names (if (coll? entity-names)
entity-names
[entity-names])]
(->> (select-keys this entity-names)
(map (fn [[k v]] [k (vary-meta v assoc :repository r)]))
(into {})
(#(with-meta % (meta this)))
(deliver r)
deref)))})
(defn create-entity [entity-meta entity]
(let [table (:table entity)
schema (or (namespace table) (:schema entity-meta) "public")
table (if (namespace table) (keyword (name table)) table)
fields (or
(:fields entity)
(->> (select (:db entity-meta)
:information-schema/columns
[:column-name]
{:table-schema [:ilike schema]
:table-name [:ilike (f/format-target table)]})
core/fetch!
(mapv (comp ->kebab-case-keyword :column-name))))]
(-> entity
(assoc :pk (:pk entity :id))
(assoc :fields fields)
map->RelationalEntity
(with-meta entity-meta))))
(defn get-db-meta
"Returns meta-data object for `Connectable` or `Connection`."
^java.sql.DatabaseMetaData
[db]
(if (satisfies? Sourceable db)
(with-open [con (jdbc/get-connection db)]
(.getMetaData con))
(.getMetaData db)))
(defmethod create-repository (.-name *ns*) [_ entities & [opts]]
(let [db (:db opts)
db-meta (get-db-meta db)
schema (or (:schema opts)
(->> (select db nil [['(current-schema) :current-schema]])
core/fetch!
first
:current-schema))
entity-meta (assoc opts
:db-type (.getDatabaseProductName db-meta)
:schema schema
:repository (promise))
build-entity (partial create-entity entity-meta)]
(->> entities
(map (fn [[k v]] [k (build-entity (assoc v :name k))]))
(into {})
(#(with-meta % (merge sql-repository-meta opts)))
(deliver (:repository entity-meta))
deref)))
(st/instrument `create-entity)
|
[
{
"context": "rieved-question (assoc stored-question :username \"UserName\"))\n\n(facts \"about creating questions\"\n (fac",
"end": 9133,
"score": 0.9989199638366699,
"start": 9125,
"tag": "USERNAME",
"value": "UserName"
},
{
"context": "str \"/users/\" USER_ID))\n(def profile-data {:name \"name\" :biog \"biography\" :user-uri user-uri})\n(def upda",
"end": 12077,
"score": 0.6488913297653198,
"start": 12073,
"tag": "NAME",
"value": "name"
},
{
"context": "eved-objective (assoc stored-objective :username \"UserName\"))\n(def invitation {:invited-by-id USER_ID\n ",
"end": 15982,
"score": 0.9992625117301941,
"start": 15974,
"tag": "USERNAME",
"value": "UserName"
},
{
"context": "this objective\")\n :writer-name \"UserName\"})\n(def writer-data {:invitation-uuid UU_ID\n ",
"end": 16196,
"score": 0.9949396252632141,
"start": 16188,
"tag": "USERNAME",
"value": "UserName"
},
{
"context": " (users/retrieve-user user-uri) => {:username \"UserName\"}\n (invitations/store-invitation! i",
"end": 16937,
"score": 0.9993358850479126,
"start": 16929,
"tag": "USERNAME",
"value": "UserName"
},
{
"context": " (users/update-user! (contains {:profile {:name \"UserName\" :biog \"This profile was automatically generated ",
"end": 17086,
"score": 0.993049681186676,
"start": 17078,
"tag": "USERNAME",
"value": "UserName"
},
{
"context": " USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-provider-user",
"end": 18434,
"score": 0.5093224048614502,
"start": 18432,
"tag": "USERNAME",
"value": "45"
},
{
"context": "tter-123456\") => {:auth-provider-user-id \"twitter-123456\"}\n (storage/pg-retrieve-entity-by-uri",
"end": 18543,
"score": 0.4979187548160553,
"start": 18542,
"tag": "USERNAME",
"value": "1"
},
{
"context": "tter-123456\") => {:auth-provider-user-id \"twitter-123456\"}\n (storage/pg-retrieve-entity-by-u",
"end": 19446,
"score": 0.6954131126403809,
"start": 19440,
"tag": "USERNAME",
"value": "123456"
},
{
"context": "ser USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-provid",
"end": 20173,
"score": 0.46131977438926697,
"start": 20168,
"tag": "USERNAME",
"value": "12345"
},
{
"context": "tter-123456\") => {:auth-provider-user-id \"twitter-123456\"}\n (storage/pg-retrieve-entity-by-",
"end": 20667,
"score": 0.5592162609100342,
"start": 20662,
"tag": "USERNAME",
"value": "12345"
},
{
"context": "ser USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-pr",
"end": 22114,
"score": 0.5592926740646362,
"start": 22113,
"tag": "USERNAME",
"value": "1"
},
{
"context": " USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-provide",
"end": 22119,
"score": 0.5305359363555908,
"start": 22116,
"tag": "USERNAME",
"value": "456"
},
{
"context": "tter-123456\") => {:auth-provider-user-id \"twitter-123456\"}))\n\n (fact \"unable to delete comment ",
"end": 22234,
"score": 0.49961990118026733,
"start": 22233,
"tag": "USERNAME",
"value": "1"
},
{
"context": "ser USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-pr",
"end": 22610,
"score": 0.5239871740341187,
"start": 22609,
"tag": "USERNAME",
"value": "1"
},
{
"context": "USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-provide",
"end": 22615,
"score": 0.5795845985412598,
"start": 22613,
"tag": "USERNAME",
"value": "56"
},
{
"context": "trieve-user USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-",
"end": 23009,
"score": 0.4290579557418823,
"start": 23002,
"tag": "USERNAME",
"value": "twitter"
},
{
"context": "ser USER_URI) => {:auth-provider-user-id \"twitter-123456\"}\n (users/get-admin-by-auth-provide",
"end": 23016,
"score": 0.6508631706237793,
"start": 23010,
"tag": "USERNAME",
"value": "123456"
}
] |
test/objective8/unit/actions_test.clj
|
d-cent/objective8
| 23 |
(ns objective8.unit.actions-test
(:require [midje.sweet :refer :all]
[objective8.config :as config]
[objective8.back-end.actions :as actions]
[objective8.back-end.domain.up-down-votes :as up-down-votes]
[objective8.back-end.domain.drafts :as drafts]
[objective8.back-end.domain.objectives :as objectives]
[objective8.back-end.domain.comments :as comments]
[objective8.back-end.domain.users :as users]
[objective8.back-end.domain.writers :as writers]
[objective8.back-end.domain.invitations :as invitations]
[objective8.back-end.domain.stars :as stars]
[objective8.back-end.domain.questions :as questions]
[objective8.back-end.domain.answers :as answers]
[objective8.back-end.domain.marks :as marks]
[objective8.back-end.domain.admin-removals :as admin-removals]
[objective8.back-end.domain.activities :as activities]
[objective8.back-end.domain.writer-notes :as writer-notes]
[objective8.back-end.storage.storage :as storage]))
(def GLOBAL_ID 6)
(def USER_ID 2)
(def USER_URI (str "/users/" USER_ID))
(def VOTE_ID 5)
(def OBJECTIVE_ID 1)
(def QUESTION_ID 2)
(def QUESTION_URI (str "/objectives/" OBJECTIVE_ID "/questions/" QUESTION_ID))
(def ANSWER_ID 3)
(def ANSWER_URI (str "/objectives/" OBJECTIVE_ID "/questions/" QUESTION_ID "/answers/" ANSWER_ID))
(def INVITATION_ID 7)
(def UU_ID "875678950430596859403-uuid")
(def DRAFT_ID 8)
(def DRAFT_URI (str "/objectives/" OBJECTIVE_ID "/drafts/" DRAFT_ID))
(def SECTION_LABEL "a84b23ca")
(def an-answer {:global-id GLOBAL_ID})
(def vote-data {:vote-on-uri :entity-uri
:created-by-id USER_ID
:vote-type :up})
(facts "about casting up-down votes"
(against-background
(actions/allowed-to-vote? anything anything) => true)
(fact "stores a vote if user has no active vote on entity"
(against-background
(up-down-votes/get-vote GLOBAL_ID USER_ID) => nil
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => an-answer)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/success
:result :the-stored-vote}
(provided
(up-down-votes/store-vote! an-answer vote-data) => :the-stored-vote))
(fact "fails if voting is not allowed on this entity"
(against-background
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => an-answer)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/forbidden}
(provided
(actions/allowed-to-vote? an-answer vote-data) => false))
(fact "reports an error when the entity to vote on cannot be found"
(against-background
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => nil)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/entity-not-found}))
(def an-objective {:entity :objective})
(facts "about allowing or disallowing voting"
(against-background
(up-down-votes/get-vote anything anything) => nil
(objectives/get-objective anything) => an-objective
(storage/pg-retrieve-entity-by-global-id :an-objective-global-id) => an-objective)
(fact "the same user cannot vote twice on the same entity"
(actions/allowed-to-vote? an-objective :vote-data) => falsey
(provided
(up-down-votes/get-vote anything anything) => :a-vote)))
(def a-draft {:entity :draft})
(def a-section {:entity :section :objective-id OBJECTIVE_ID})
(def comment-data {:comment-on-uri "/entity-uri"
:comment "A comment"
:created-by-id USER_ID})
(def COMMENT_ID)
(def section-uri (str "/objectives/" OBJECTIVE_ID "/drafts/" DRAFT_ID "/sections/" SECTION_LABEL))
(def reason-type "expand")
(def section-comment-data {:comment-on-uri section-uri :reason reason-type})
(facts "about creating comments"
(fact "can comment on an objective"
(actions/create-comment! comment-data) => {:status ::actions/success :result :the-stored-comment}
(provided
(storage/pg-retrieve-entity-by-uri "/entity-uri" :with-global-id) => an-objective
(comments/store-comment-for! an-objective comment-data) => :the-stored-comment))
(fact "can comment on a draft"
(actions/create-comment! comment-data) => {:status ::actions/success :result :the-stored-comment}
(provided
(storage/pg-retrieve-entity-by-uri "/entity-uri" :with-global-id) => a-draft
(comments/store-comment-for! a-draft comment-data) => :the-stored-comment))
(fact "can comment on a draft section with existing comments"
(actions/create-comment! section-comment-data) => {:status ::actions/success :result {:_id COMMENT_ID :reason reason-type}}
(provided
(storage/pg-retrieve-entity-by-uri section-uri :with-global-id) => a-section
(comments/store-comment-for! a-section section-comment-data) => {:_id COMMENT_ID}
(comments/store-reason! {:reason reason-type :comment-id COMMENT_ID}) => {:reason reason-type}))
(fact "can comment on a draft section with no previous comments"
(actions/create-comment! section-comment-data) => {:status ::actions/success :result {:_id COMMENT_ID :reason reason-type}}
(provided
(storage/pg-retrieve-entity-by-uri section-uri :with-global-id) => nil
(drafts/get-section-labels-for-draft-uri DRAFT_URI) => [SECTION_LABEL]
(drafts/store-section! {:entity :section :draft-id DRAFT_ID :objective-id OBJECTIVE_ID
:section-label SECTION_LABEL}) => a-section
(comments/store-comment-for! a-section section-comment-data) => {:_id COMMENT_ID}
(comments/store-reason! {:reason reason-type :comment-id COMMENT_ID}) => {:reason reason-type}))
(fact "reports an error when the entity to comment on cannot be found"
(actions/create-comment! comment-data) => {:status ::actions/entity-not-found}
(provided
(storage/pg-retrieve-entity-by-uri anything anything) => nil)))
(facts "about retrieving annotations for a draft"
(fact "annotations are retrieved with the annotated section"
(actions/get-annotations-for-draft DRAFT_URI) => {:status ::actions/success
:result [{:section :some-hiccup
:uri :section-uri
:objective-id OBJECTIVE_ID
:comments [:annotation]}]}
(provided
(drafts/get-annotated-sections-with-section-content DRAFT_URI) => [{:uri :section-uri
:objective-id OBJECTIVE_ID
:section :some-hiccup}]
(comments/get-comments :section-uri {}) => [:annotation])))
(def STAR_ID 47)
(def OBJECTIVE-URI (str "/objectives/" OBJECTIVE_ID))
(def user-uri (str "/users/" USER_ID))
(def star-data {:objective-uri OBJECTIVE-URI
:created-by-id USER_ID})
(def star-data-with-id (assoc star-data :objective-id OBJECTIVE_ID))
(facts "about toggling stars"
(fact "star is created for an objective if none already exists"
(actions/toggle-star! star-data) => {:status ::actions/success
:result :the-stored-star}
(provided
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI) => {:_id OBJECTIVE_ID}
(stars/get-star OBJECTIVE-URI user-uri) => nil
(stars/store-star! star-data-with-id) => :the-stored-star))
(fact "the state of the star is toggled if the user has already starred the objective"
(actions/toggle-star! star-data) => {:status ::actions/success
:result :the-toggled-star}
(provided
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI) => {:_id OBJECTIVE_ID}
(stars/get-star OBJECTIVE-URI user-uri) => :star
(stars/toggle-star! :star) => :the-toggled-star)))
(def mark-data {:question-uri QUESTION_URI
:created-by-uri user-uri})
(def question {:objective-id OBJECTIVE_ID :created-by-id USER_ID :uri QUESTION_URI :question "Sample question"})
(def stored-question (assoc question :_id QUESTION_ID))
(def retrieved-question (assoc stored-question :username "UserName"))
(facts "about creating questions"
(fact "A question can be created"
(actions/create-question! question) => {:status ::actions/success :result stored-question}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(writers/retrieve-writer-for-objective USER_ID OBJECTIVE_ID) => nil
(questions/store-question! question) => stored-question
(questions/get-question QUESTION_URI) => retrieved-question
(activities/store-activity! retrieved-question) => anything)))
(facts "about marking questions"
(fact "a mark is created if none already exists"
(actions/mark-question! mark-data) => {:status ::actions/success
:result :the-new-mark}
(provided
(questions/get-question QUESTION_URI) => :a-question
(marks/get-mark-for-question QUESTION_URI) => nil
(marks/store-mark! (contains (assoc mark-data :active true))) => :the-new-mark))
(fact "the state of the mark is toggled if a mark already exists for the question"
(actions/mark-question! mark-data) => {:status ::actions/success
:result :the-new-mark}
(provided
(questions/get-question QUESTION_URI) => :a-question
(marks/get-mark-for-question QUESTION_URI) => {:active true}
(marks/store-mark! (contains (assoc mark-data :active false))) => :the-new-mark))
(fact "a question with the given uri must exist in order to be marked"
(actions/mark-question! mark-data) => {:status ::actions/entity-not-found}
(provided
(questions/get-question QUESTION_URI) => nil)))
(facts "about getting users"
(fact "gets user with writer records, owned objectives and admin role if they exist"
(actions/get-user-with-roles user-uri)
=> {:status ::actions/success
:result {:entity :user
:_id USER_ID
:auth-provider-user-id "twitter-id"
:owned-objectives :stubbed-owned-objectives
:writer-records :stubbed-writer-records
:admin true}}
(provided
(users/retrieve-user user-uri) => {:entity :user :_id USER_ID :auth-provider-user-id "twitter-id"}
(users/get-admin-by-auth-provider-user-id "twitter-id") => {:auth-provider-user-id "twitter-id"}
(writers/retrieve-writers-by-user-id USER_ID) => :stubbed-writer-records
(objectives/get-objectives-owned-by-user-id USER_ID) => :stubbed-owned-objectives)))
(def user-uri (str "/users/" USER_ID))
(def profile-data {:name "name" :biog "biography" :user-uri user-uri})
(def updated-user (assoc {:entity :user :_id USER_ID} :profile (dissoc profile-data :user-uri)))
(facts "about updating a user with a writer profile"
(fact "updates a user's profile"
(actions/update-user-with-profile! profile-data) => {:status ::actions/success
:result :the-updated-user}
(provided
(users/retrieve-user user-uri) => {:entity :user :_id USER_ID}
(users/update-user! updated-user) => :the-updated-user)))
(def answer {:objective-id OBJECTIVE_ID :question-id QUESTION_ID})
(facts "about creating an answer"
(fact "succeeds when the question exists"
(actions/create-answer! answer) => {:status ::actions/success
:result :stored-answer}
(provided
(questions/get-question QUESTION_URI) => :a-question
(answers/store-answer! answer) => :stored-answer))
(fact "returns entity-not-found status when the associated question doesn't exist"
(actions/create-answer! answer) => {:status ::actions/entity-not-found}
(provided
(questions/get-question QUESTION_URI) => nil))
(fact "returns failure status when storing the answer fails"
(actions/create-answer! answer) => {:status ::actions/failure}
(provided
(questions/get-question QUESTION_URI) => :a-question
(answers/store-answer! answer) => nil)))
(def invitation {:objective-id OBJECTIVE_ID
:invited-by-id USER_ID})
(facts "about creating an invitation"
(fact "succeeds when the inviter is an existing writer"
(against-background
(objectives/get-objectives-owned-by-user-id USER_ID) => [])
(actions/create-invitation! invitation) => {:status ::actions/success
:result :stored-invitation}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id OBJECTIVE_ID}]
(invitations/store-invitation! invitation) => :stored-invitation))
(fact "succeeds when the inviter is the objective owner"
(against-background
(writers/retrieve-writers-by-user-id USER_ID) => [])
(actions/create-invitation! invitation) => {:status ::actions/success
:result :stored-invitation}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(objectives/get-objectives-owned-by-user-id USER_ID) => [{:_id OBJECTIVE_ID}]
(invitations/store-invitation! invitation) => :stored-invitation))
(fact "returns failure status when the inviter is not authorised"
(actions/create-invitation! invitation) => {:status ::actions/failure}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(objectives/get-objectives-owned-by-user-id USER_ID) => []
(writers/retrieve-writers-by-user-id USER_ID) => []))
(fact "returns a list of objective-ids a user is writer-inviter for"
(actions/authorised-objectives-for-inviter USER_ID) => '(1 2 3 4)
(provided
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id 1} {:objective-id 2}]
(objectives/get-objectives-owned-by-user-id USER_ID) => [{:_id 3} {:_id 4}])))
(def objective {:created-by-id USER_ID :title "SOME TITLE"})
(def stored-objective (assoc objective :_id OBJECTIVE_ID))
(def retrieved-objective (assoc stored-objective :username "UserName"))
(def invitation {:invited-by-id USER_ID
:objective-id OBJECTIVE_ID
:reason (str "Default writer as creator of this objective")
:writer-name "UserName"})
(def writer-data {:invitation-uuid UU_ID
:invitee-id USER_ID})
(def user-uri (str "/users/" USER_ID))
(facts "about creating an objective"
(fact "when an objective is stored the creator becomes a writer for the objective"
(actions/create-objective! objective) => {:status ::actions/success
:result stored-objective}
(provided
(objectives/store-objective! objective) => stored-objective
(objectives/get-objective OBJECTIVE_ID) => retrieved-objective
(activities/store-activity! retrieved-objective) => anything
(users/retrieve-user user-uri) => {:username "UserName"}
(invitations/store-invitation! invitation) => {:uuid UU_ID}
(users/update-user! (contains {:profile {:name "UserName" :biog "This profile was automatically generated for the creator of objective: SOME TITLE"}})) => {}
(writers/create-writer writer-data) => :writer)))
(def writer-note {:note "the note content" :created-by-id USER_ID :note-on-uri ANSWER_URI})
(def entity-to-note-on {:objective-id OBJECTIVE_ID})
(facts "about creating a note"
(fact "writers can create a note against an answer"
(actions/create-writer-note! writer-note) => {:status ::actions/success
:result :stored-note}
(provided
(writer-notes/store-note-for! entity-to-note-on writer-note) => :stored-note
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id OBJECTIVE_ID} {:objective-id 2}]
(storage/pg-retrieve-entity-by-uri ANSWER_URI :with-global-id) => entity-to-note-on
(writer-notes/retrieve-note ANSWER_URI) => [])))
(def admin-removal {:removal-uri OBJECTIVE-URI
:removed-by-uri USER_URI})
(fact "admin-removals"
(actions/create-admin-removal! admin-removal) => {:status ::actions/success
:result :stored-admin-removal}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => {:_id OBJECTIVE_ID}
(objectives/admin-remove-objective! {:_id OBJECTIVE_ID}) => {:_id OBJECTIVE_ID}
(admin-removals/store-admin-removal! admin-removal) => :stored-admin-removal))
(def promoted-objective-data {:objective-uri OBJECTIVE-URI :promoted-by USER_URI})
(facts "about promoting objectives"
(fact "does promote an existing objective when signed in as an admin"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/success
:result OBJECTIVE_ID}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => {:_id OBJECTIVE_ID}
(objectives/toggle-promoted-status! {:_id OBJECTIVE_ID}) => OBJECTIVE_ID))
(fact "unable to promote objective if user is not signed in"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => nil))
(fact "unable to promote objective if user is not an admin"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/forbidden}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => nil))
(fact "unable to promote objective if objective n'existe pas"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => nil
)))
(def COMMENT_URI (str "/comments/" COMMENT_ID))
(def removed-comment-data {:_id COMMENT_ID :removal-uri COMMENT_URI :removed-by-uri USER_URI})
(facts "about removing comments"
(fact "does remove a comment when signed in as an admin and comment exists"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/success
:result COMMENT_ID}
(provided
(comments/admin-remove-comment! removed-comment-data) => COMMENT_ID
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => removed-comment-data
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "returns forbidden if comment removal unsuccessful"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/forbidden}
(provided
(comments/admin-remove-comment! removed-comment-data) => nil
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => removed-comment-data
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "unable to delete comment if comment does not exist"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/entity-not-found}
(provided
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => nil
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "unable to delete comment if user is not an admin"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/forbidden}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => nil))
(fact "unable to delete comment if user is not signed in"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => nil)))
|
10032
|
(ns objective8.unit.actions-test
(:require [midje.sweet :refer :all]
[objective8.config :as config]
[objective8.back-end.actions :as actions]
[objective8.back-end.domain.up-down-votes :as up-down-votes]
[objective8.back-end.domain.drafts :as drafts]
[objective8.back-end.domain.objectives :as objectives]
[objective8.back-end.domain.comments :as comments]
[objective8.back-end.domain.users :as users]
[objective8.back-end.domain.writers :as writers]
[objective8.back-end.domain.invitations :as invitations]
[objective8.back-end.domain.stars :as stars]
[objective8.back-end.domain.questions :as questions]
[objective8.back-end.domain.answers :as answers]
[objective8.back-end.domain.marks :as marks]
[objective8.back-end.domain.admin-removals :as admin-removals]
[objective8.back-end.domain.activities :as activities]
[objective8.back-end.domain.writer-notes :as writer-notes]
[objective8.back-end.storage.storage :as storage]))
(def GLOBAL_ID 6)
(def USER_ID 2)
(def USER_URI (str "/users/" USER_ID))
(def VOTE_ID 5)
(def OBJECTIVE_ID 1)
(def QUESTION_ID 2)
(def QUESTION_URI (str "/objectives/" OBJECTIVE_ID "/questions/" QUESTION_ID))
(def ANSWER_ID 3)
(def ANSWER_URI (str "/objectives/" OBJECTIVE_ID "/questions/" QUESTION_ID "/answers/" ANSWER_ID))
(def INVITATION_ID 7)
(def UU_ID "875678950430596859403-uuid")
(def DRAFT_ID 8)
(def DRAFT_URI (str "/objectives/" OBJECTIVE_ID "/drafts/" DRAFT_ID))
(def SECTION_LABEL "a84b23ca")
(def an-answer {:global-id GLOBAL_ID})
(def vote-data {:vote-on-uri :entity-uri
:created-by-id USER_ID
:vote-type :up})
(facts "about casting up-down votes"
(against-background
(actions/allowed-to-vote? anything anything) => true)
(fact "stores a vote if user has no active vote on entity"
(against-background
(up-down-votes/get-vote GLOBAL_ID USER_ID) => nil
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => an-answer)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/success
:result :the-stored-vote}
(provided
(up-down-votes/store-vote! an-answer vote-data) => :the-stored-vote))
(fact "fails if voting is not allowed on this entity"
(against-background
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => an-answer)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/forbidden}
(provided
(actions/allowed-to-vote? an-answer vote-data) => false))
(fact "reports an error when the entity to vote on cannot be found"
(against-background
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => nil)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/entity-not-found}))
(def an-objective {:entity :objective})
(facts "about allowing or disallowing voting"
(against-background
(up-down-votes/get-vote anything anything) => nil
(objectives/get-objective anything) => an-objective
(storage/pg-retrieve-entity-by-global-id :an-objective-global-id) => an-objective)
(fact "the same user cannot vote twice on the same entity"
(actions/allowed-to-vote? an-objective :vote-data) => falsey
(provided
(up-down-votes/get-vote anything anything) => :a-vote)))
(def a-draft {:entity :draft})
(def a-section {:entity :section :objective-id OBJECTIVE_ID})
(def comment-data {:comment-on-uri "/entity-uri"
:comment "A comment"
:created-by-id USER_ID})
(def COMMENT_ID)
(def section-uri (str "/objectives/" OBJECTIVE_ID "/drafts/" DRAFT_ID "/sections/" SECTION_LABEL))
(def reason-type "expand")
(def section-comment-data {:comment-on-uri section-uri :reason reason-type})
(facts "about creating comments"
(fact "can comment on an objective"
(actions/create-comment! comment-data) => {:status ::actions/success :result :the-stored-comment}
(provided
(storage/pg-retrieve-entity-by-uri "/entity-uri" :with-global-id) => an-objective
(comments/store-comment-for! an-objective comment-data) => :the-stored-comment))
(fact "can comment on a draft"
(actions/create-comment! comment-data) => {:status ::actions/success :result :the-stored-comment}
(provided
(storage/pg-retrieve-entity-by-uri "/entity-uri" :with-global-id) => a-draft
(comments/store-comment-for! a-draft comment-data) => :the-stored-comment))
(fact "can comment on a draft section with existing comments"
(actions/create-comment! section-comment-data) => {:status ::actions/success :result {:_id COMMENT_ID :reason reason-type}}
(provided
(storage/pg-retrieve-entity-by-uri section-uri :with-global-id) => a-section
(comments/store-comment-for! a-section section-comment-data) => {:_id COMMENT_ID}
(comments/store-reason! {:reason reason-type :comment-id COMMENT_ID}) => {:reason reason-type}))
(fact "can comment on a draft section with no previous comments"
(actions/create-comment! section-comment-data) => {:status ::actions/success :result {:_id COMMENT_ID :reason reason-type}}
(provided
(storage/pg-retrieve-entity-by-uri section-uri :with-global-id) => nil
(drafts/get-section-labels-for-draft-uri DRAFT_URI) => [SECTION_LABEL]
(drafts/store-section! {:entity :section :draft-id DRAFT_ID :objective-id OBJECTIVE_ID
:section-label SECTION_LABEL}) => a-section
(comments/store-comment-for! a-section section-comment-data) => {:_id COMMENT_ID}
(comments/store-reason! {:reason reason-type :comment-id COMMENT_ID}) => {:reason reason-type}))
(fact "reports an error when the entity to comment on cannot be found"
(actions/create-comment! comment-data) => {:status ::actions/entity-not-found}
(provided
(storage/pg-retrieve-entity-by-uri anything anything) => nil)))
(facts "about retrieving annotations for a draft"
(fact "annotations are retrieved with the annotated section"
(actions/get-annotations-for-draft DRAFT_URI) => {:status ::actions/success
:result [{:section :some-hiccup
:uri :section-uri
:objective-id OBJECTIVE_ID
:comments [:annotation]}]}
(provided
(drafts/get-annotated-sections-with-section-content DRAFT_URI) => [{:uri :section-uri
:objective-id OBJECTIVE_ID
:section :some-hiccup}]
(comments/get-comments :section-uri {}) => [:annotation])))
(def STAR_ID 47)
(def OBJECTIVE-URI (str "/objectives/" OBJECTIVE_ID))
(def user-uri (str "/users/" USER_ID))
(def star-data {:objective-uri OBJECTIVE-URI
:created-by-id USER_ID})
(def star-data-with-id (assoc star-data :objective-id OBJECTIVE_ID))
(facts "about toggling stars"
(fact "star is created for an objective if none already exists"
(actions/toggle-star! star-data) => {:status ::actions/success
:result :the-stored-star}
(provided
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI) => {:_id OBJECTIVE_ID}
(stars/get-star OBJECTIVE-URI user-uri) => nil
(stars/store-star! star-data-with-id) => :the-stored-star))
(fact "the state of the star is toggled if the user has already starred the objective"
(actions/toggle-star! star-data) => {:status ::actions/success
:result :the-toggled-star}
(provided
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI) => {:_id OBJECTIVE_ID}
(stars/get-star OBJECTIVE-URI user-uri) => :star
(stars/toggle-star! :star) => :the-toggled-star)))
(def mark-data {:question-uri QUESTION_URI
:created-by-uri user-uri})
(def question {:objective-id OBJECTIVE_ID :created-by-id USER_ID :uri QUESTION_URI :question "Sample question"})
(def stored-question (assoc question :_id QUESTION_ID))
(def retrieved-question (assoc stored-question :username "UserName"))
(facts "about creating questions"
(fact "A question can be created"
(actions/create-question! question) => {:status ::actions/success :result stored-question}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(writers/retrieve-writer-for-objective USER_ID OBJECTIVE_ID) => nil
(questions/store-question! question) => stored-question
(questions/get-question QUESTION_URI) => retrieved-question
(activities/store-activity! retrieved-question) => anything)))
(facts "about marking questions"
(fact "a mark is created if none already exists"
(actions/mark-question! mark-data) => {:status ::actions/success
:result :the-new-mark}
(provided
(questions/get-question QUESTION_URI) => :a-question
(marks/get-mark-for-question QUESTION_URI) => nil
(marks/store-mark! (contains (assoc mark-data :active true))) => :the-new-mark))
(fact "the state of the mark is toggled if a mark already exists for the question"
(actions/mark-question! mark-data) => {:status ::actions/success
:result :the-new-mark}
(provided
(questions/get-question QUESTION_URI) => :a-question
(marks/get-mark-for-question QUESTION_URI) => {:active true}
(marks/store-mark! (contains (assoc mark-data :active false))) => :the-new-mark))
(fact "a question with the given uri must exist in order to be marked"
(actions/mark-question! mark-data) => {:status ::actions/entity-not-found}
(provided
(questions/get-question QUESTION_URI) => nil)))
(facts "about getting users"
(fact "gets user with writer records, owned objectives and admin role if they exist"
(actions/get-user-with-roles user-uri)
=> {:status ::actions/success
:result {:entity :user
:_id USER_ID
:auth-provider-user-id "twitter-id"
:owned-objectives :stubbed-owned-objectives
:writer-records :stubbed-writer-records
:admin true}}
(provided
(users/retrieve-user user-uri) => {:entity :user :_id USER_ID :auth-provider-user-id "twitter-id"}
(users/get-admin-by-auth-provider-user-id "twitter-id") => {:auth-provider-user-id "twitter-id"}
(writers/retrieve-writers-by-user-id USER_ID) => :stubbed-writer-records
(objectives/get-objectives-owned-by-user-id USER_ID) => :stubbed-owned-objectives)))
(def user-uri (str "/users/" USER_ID))
(def profile-data {:name "<NAME>" :biog "biography" :user-uri user-uri})
(def updated-user (assoc {:entity :user :_id USER_ID} :profile (dissoc profile-data :user-uri)))
(facts "about updating a user with a writer profile"
(fact "updates a user's profile"
(actions/update-user-with-profile! profile-data) => {:status ::actions/success
:result :the-updated-user}
(provided
(users/retrieve-user user-uri) => {:entity :user :_id USER_ID}
(users/update-user! updated-user) => :the-updated-user)))
(def answer {:objective-id OBJECTIVE_ID :question-id QUESTION_ID})
(facts "about creating an answer"
(fact "succeeds when the question exists"
(actions/create-answer! answer) => {:status ::actions/success
:result :stored-answer}
(provided
(questions/get-question QUESTION_URI) => :a-question
(answers/store-answer! answer) => :stored-answer))
(fact "returns entity-not-found status when the associated question doesn't exist"
(actions/create-answer! answer) => {:status ::actions/entity-not-found}
(provided
(questions/get-question QUESTION_URI) => nil))
(fact "returns failure status when storing the answer fails"
(actions/create-answer! answer) => {:status ::actions/failure}
(provided
(questions/get-question QUESTION_URI) => :a-question
(answers/store-answer! answer) => nil)))
(def invitation {:objective-id OBJECTIVE_ID
:invited-by-id USER_ID})
(facts "about creating an invitation"
(fact "succeeds when the inviter is an existing writer"
(against-background
(objectives/get-objectives-owned-by-user-id USER_ID) => [])
(actions/create-invitation! invitation) => {:status ::actions/success
:result :stored-invitation}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id OBJECTIVE_ID}]
(invitations/store-invitation! invitation) => :stored-invitation))
(fact "succeeds when the inviter is the objective owner"
(against-background
(writers/retrieve-writers-by-user-id USER_ID) => [])
(actions/create-invitation! invitation) => {:status ::actions/success
:result :stored-invitation}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(objectives/get-objectives-owned-by-user-id USER_ID) => [{:_id OBJECTIVE_ID}]
(invitations/store-invitation! invitation) => :stored-invitation))
(fact "returns failure status when the inviter is not authorised"
(actions/create-invitation! invitation) => {:status ::actions/failure}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(objectives/get-objectives-owned-by-user-id USER_ID) => []
(writers/retrieve-writers-by-user-id USER_ID) => []))
(fact "returns a list of objective-ids a user is writer-inviter for"
(actions/authorised-objectives-for-inviter USER_ID) => '(1 2 3 4)
(provided
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id 1} {:objective-id 2}]
(objectives/get-objectives-owned-by-user-id USER_ID) => [{:_id 3} {:_id 4}])))
(def objective {:created-by-id USER_ID :title "SOME TITLE"})
(def stored-objective (assoc objective :_id OBJECTIVE_ID))
(def retrieved-objective (assoc stored-objective :username "UserName"))
(def invitation {:invited-by-id USER_ID
:objective-id OBJECTIVE_ID
:reason (str "Default writer as creator of this objective")
:writer-name "UserName"})
(def writer-data {:invitation-uuid UU_ID
:invitee-id USER_ID})
(def user-uri (str "/users/" USER_ID))
(facts "about creating an objective"
(fact "when an objective is stored the creator becomes a writer for the objective"
(actions/create-objective! objective) => {:status ::actions/success
:result stored-objective}
(provided
(objectives/store-objective! objective) => stored-objective
(objectives/get-objective OBJECTIVE_ID) => retrieved-objective
(activities/store-activity! retrieved-objective) => anything
(users/retrieve-user user-uri) => {:username "UserName"}
(invitations/store-invitation! invitation) => {:uuid UU_ID}
(users/update-user! (contains {:profile {:name "UserName" :biog "This profile was automatically generated for the creator of objective: SOME TITLE"}})) => {}
(writers/create-writer writer-data) => :writer)))
(def writer-note {:note "the note content" :created-by-id USER_ID :note-on-uri ANSWER_URI})
(def entity-to-note-on {:objective-id OBJECTIVE_ID})
(facts "about creating a note"
(fact "writers can create a note against an answer"
(actions/create-writer-note! writer-note) => {:status ::actions/success
:result :stored-note}
(provided
(writer-notes/store-note-for! entity-to-note-on writer-note) => :stored-note
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id OBJECTIVE_ID} {:objective-id 2}]
(storage/pg-retrieve-entity-by-uri ANSWER_URI :with-global-id) => entity-to-note-on
(writer-notes/retrieve-note ANSWER_URI) => [])))
(def admin-removal {:removal-uri OBJECTIVE-URI
:removed-by-uri USER_URI})
(fact "admin-removals"
(actions/create-admin-removal! admin-removal) => {:status ::actions/success
:result :stored-admin-removal}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => {:_id OBJECTIVE_ID}
(objectives/admin-remove-objective! {:_id OBJECTIVE_ID}) => {:_id OBJECTIVE_ID}
(admin-removals/store-admin-removal! admin-removal) => :stored-admin-removal))
(def promoted-objective-data {:objective-uri OBJECTIVE-URI :promoted-by USER_URI})
(facts "about promoting objectives"
(fact "does promote an existing objective when signed in as an admin"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/success
:result OBJECTIVE_ID}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => {:_id OBJECTIVE_ID}
(objectives/toggle-promoted-status! {:_id OBJECTIVE_ID}) => OBJECTIVE_ID))
(fact "unable to promote objective if user is not signed in"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => nil))
(fact "unable to promote objective if user is not an admin"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/forbidden}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => nil))
(fact "unable to promote objective if objective n'existe pas"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => nil
)))
(def COMMENT_URI (str "/comments/" COMMENT_ID))
(def removed-comment-data {:_id COMMENT_ID :removal-uri COMMENT_URI :removed-by-uri USER_URI})
(facts "about removing comments"
(fact "does remove a comment when signed in as an admin and comment exists"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/success
:result COMMENT_ID}
(provided
(comments/admin-remove-comment! removed-comment-data) => COMMENT_ID
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => removed-comment-data
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "returns forbidden if comment removal unsuccessful"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/forbidden}
(provided
(comments/admin-remove-comment! removed-comment-data) => nil
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => removed-comment-data
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "unable to delete comment if comment does not exist"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/entity-not-found}
(provided
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => nil
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "unable to delete comment if user is not an admin"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/forbidden}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => nil))
(fact "unable to delete comment if user is not signed in"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => nil)))
| true |
(ns objective8.unit.actions-test
(:require [midje.sweet :refer :all]
[objective8.config :as config]
[objective8.back-end.actions :as actions]
[objective8.back-end.domain.up-down-votes :as up-down-votes]
[objective8.back-end.domain.drafts :as drafts]
[objective8.back-end.domain.objectives :as objectives]
[objective8.back-end.domain.comments :as comments]
[objective8.back-end.domain.users :as users]
[objective8.back-end.domain.writers :as writers]
[objective8.back-end.domain.invitations :as invitations]
[objective8.back-end.domain.stars :as stars]
[objective8.back-end.domain.questions :as questions]
[objective8.back-end.domain.answers :as answers]
[objective8.back-end.domain.marks :as marks]
[objective8.back-end.domain.admin-removals :as admin-removals]
[objective8.back-end.domain.activities :as activities]
[objective8.back-end.domain.writer-notes :as writer-notes]
[objective8.back-end.storage.storage :as storage]))
(def GLOBAL_ID 6)
(def USER_ID 2)
(def USER_URI (str "/users/" USER_ID))
(def VOTE_ID 5)
(def OBJECTIVE_ID 1)
(def QUESTION_ID 2)
(def QUESTION_URI (str "/objectives/" OBJECTIVE_ID "/questions/" QUESTION_ID))
(def ANSWER_ID 3)
(def ANSWER_URI (str "/objectives/" OBJECTIVE_ID "/questions/" QUESTION_ID "/answers/" ANSWER_ID))
(def INVITATION_ID 7)
(def UU_ID "875678950430596859403-uuid")
(def DRAFT_ID 8)
(def DRAFT_URI (str "/objectives/" OBJECTIVE_ID "/drafts/" DRAFT_ID))
(def SECTION_LABEL "a84b23ca")
(def an-answer {:global-id GLOBAL_ID})
(def vote-data {:vote-on-uri :entity-uri
:created-by-id USER_ID
:vote-type :up})
(facts "about casting up-down votes"
(against-background
(actions/allowed-to-vote? anything anything) => true)
(fact "stores a vote if user has no active vote on entity"
(against-background
(up-down-votes/get-vote GLOBAL_ID USER_ID) => nil
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => an-answer)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/success
:result :the-stored-vote}
(provided
(up-down-votes/store-vote! an-answer vote-data) => :the-stored-vote))
(fact "fails if voting is not allowed on this entity"
(against-background
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => an-answer)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/forbidden}
(provided
(actions/allowed-to-vote? an-answer vote-data) => false))
(fact "reports an error when the entity to vote on cannot be found"
(against-background
(storage/pg-retrieve-entity-by-uri :entity-uri :with-global-id) => nil)
(actions/cast-up-down-vote! vote-data) => {:status ::actions/entity-not-found}))
(def an-objective {:entity :objective})
(facts "about allowing or disallowing voting"
(against-background
(up-down-votes/get-vote anything anything) => nil
(objectives/get-objective anything) => an-objective
(storage/pg-retrieve-entity-by-global-id :an-objective-global-id) => an-objective)
(fact "the same user cannot vote twice on the same entity"
(actions/allowed-to-vote? an-objective :vote-data) => falsey
(provided
(up-down-votes/get-vote anything anything) => :a-vote)))
(def a-draft {:entity :draft})
(def a-section {:entity :section :objective-id OBJECTIVE_ID})
(def comment-data {:comment-on-uri "/entity-uri"
:comment "A comment"
:created-by-id USER_ID})
(def COMMENT_ID)
(def section-uri (str "/objectives/" OBJECTIVE_ID "/drafts/" DRAFT_ID "/sections/" SECTION_LABEL))
(def reason-type "expand")
(def section-comment-data {:comment-on-uri section-uri :reason reason-type})
(facts "about creating comments"
(fact "can comment on an objective"
(actions/create-comment! comment-data) => {:status ::actions/success :result :the-stored-comment}
(provided
(storage/pg-retrieve-entity-by-uri "/entity-uri" :with-global-id) => an-objective
(comments/store-comment-for! an-objective comment-data) => :the-stored-comment))
(fact "can comment on a draft"
(actions/create-comment! comment-data) => {:status ::actions/success :result :the-stored-comment}
(provided
(storage/pg-retrieve-entity-by-uri "/entity-uri" :with-global-id) => a-draft
(comments/store-comment-for! a-draft comment-data) => :the-stored-comment))
(fact "can comment on a draft section with existing comments"
(actions/create-comment! section-comment-data) => {:status ::actions/success :result {:_id COMMENT_ID :reason reason-type}}
(provided
(storage/pg-retrieve-entity-by-uri section-uri :with-global-id) => a-section
(comments/store-comment-for! a-section section-comment-data) => {:_id COMMENT_ID}
(comments/store-reason! {:reason reason-type :comment-id COMMENT_ID}) => {:reason reason-type}))
(fact "can comment on a draft section with no previous comments"
(actions/create-comment! section-comment-data) => {:status ::actions/success :result {:_id COMMENT_ID :reason reason-type}}
(provided
(storage/pg-retrieve-entity-by-uri section-uri :with-global-id) => nil
(drafts/get-section-labels-for-draft-uri DRAFT_URI) => [SECTION_LABEL]
(drafts/store-section! {:entity :section :draft-id DRAFT_ID :objective-id OBJECTIVE_ID
:section-label SECTION_LABEL}) => a-section
(comments/store-comment-for! a-section section-comment-data) => {:_id COMMENT_ID}
(comments/store-reason! {:reason reason-type :comment-id COMMENT_ID}) => {:reason reason-type}))
(fact "reports an error when the entity to comment on cannot be found"
(actions/create-comment! comment-data) => {:status ::actions/entity-not-found}
(provided
(storage/pg-retrieve-entity-by-uri anything anything) => nil)))
(facts "about retrieving annotations for a draft"
(fact "annotations are retrieved with the annotated section"
(actions/get-annotations-for-draft DRAFT_URI) => {:status ::actions/success
:result [{:section :some-hiccup
:uri :section-uri
:objective-id OBJECTIVE_ID
:comments [:annotation]}]}
(provided
(drafts/get-annotated-sections-with-section-content DRAFT_URI) => [{:uri :section-uri
:objective-id OBJECTIVE_ID
:section :some-hiccup}]
(comments/get-comments :section-uri {}) => [:annotation])))
(def STAR_ID 47)
(def OBJECTIVE-URI (str "/objectives/" OBJECTIVE_ID))
(def user-uri (str "/users/" USER_ID))
(def star-data {:objective-uri OBJECTIVE-URI
:created-by-id USER_ID})
(def star-data-with-id (assoc star-data :objective-id OBJECTIVE_ID))
(facts "about toggling stars"
(fact "star is created for an objective if none already exists"
(actions/toggle-star! star-data) => {:status ::actions/success
:result :the-stored-star}
(provided
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI) => {:_id OBJECTIVE_ID}
(stars/get-star OBJECTIVE-URI user-uri) => nil
(stars/store-star! star-data-with-id) => :the-stored-star))
(fact "the state of the star is toggled if the user has already starred the objective"
(actions/toggle-star! star-data) => {:status ::actions/success
:result :the-toggled-star}
(provided
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI) => {:_id OBJECTIVE_ID}
(stars/get-star OBJECTIVE-URI user-uri) => :star
(stars/toggle-star! :star) => :the-toggled-star)))
(def mark-data {:question-uri QUESTION_URI
:created-by-uri user-uri})
(def question {:objective-id OBJECTIVE_ID :created-by-id USER_ID :uri QUESTION_URI :question "Sample question"})
(def stored-question (assoc question :_id QUESTION_ID))
(def retrieved-question (assoc stored-question :username "UserName"))
(facts "about creating questions"
(fact "A question can be created"
(actions/create-question! question) => {:status ::actions/success :result stored-question}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(writers/retrieve-writer-for-objective USER_ID OBJECTIVE_ID) => nil
(questions/store-question! question) => stored-question
(questions/get-question QUESTION_URI) => retrieved-question
(activities/store-activity! retrieved-question) => anything)))
(facts "about marking questions"
(fact "a mark is created if none already exists"
(actions/mark-question! mark-data) => {:status ::actions/success
:result :the-new-mark}
(provided
(questions/get-question QUESTION_URI) => :a-question
(marks/get-mark-for-question QUESTION_URI) => nil
(marks/store-mark! (contains (assoc mark-data :active true))) => :the-new-mark))
(fact "the state of the mark is toggled if a mark already exists for the question"
(actions/mark-question! mark-data) => {:status ::actions/success
:result :the-new-mark}
(provided
(questions/get-question QUESTION_URI) => :a-question
(marks/get-mark-for-question QUESTION_URI) => {:active true}
(marks/store-mark! (contains (assoc mark-data :active false))) => :the-new-mark))
(fact "a question with the given uri must exist in order to be marked"
(actions/mark-question! mark-data) => {:status ::actions/entity-not-found}
(provided
(questions/get-question QUESTION_URI) => nil)))
(facts "about getting users"
(fact "gets user with writer records, owned objectives and admin role if they exist"
(actions/get-user-with-roles user-uri)
=> {:status ::actions/success
:result {:entity :user
:_id USER_ID
:auth-provider-user-id "twitter-id"
:owned-objectives :stubbed-owned-objectives
:writer-records :stubbed-writer-records
:admin true}}
(provided
(users/retrieve-user user-uri) => {:entity :user :_id USER_ID :auth-provider-user-id "twitter-id"}
(users/get-admin-by-auth-provider-user-id "twitter-id") => {:auth-provider-user-id "twitter-id"}
(writers/retrieve-writers-by-user-id USER_ID) => :stubbed-writer-records
(objectives/get-objectives-owned-by-user-id USER_ID) => :stubbed-owned-objectives)))
(def user-uri (str "/users/" USER_ID))
(def profile-data {:name "PI:NAME:<NAME>END_PI" :biog "biography" :user-uri user-uri})
(def updated-user (assoc {:entity :user :_id USER_ID} :profile (dissoc profile-data :user-uri)))
(facts "about updating a user with a writer profile"
(fact "updates a user's profile"
(actions/update-user-with-profile! profile-data) => {:status ::actions/success
:result :the-updated-user}
(provided
(users/retrieve-user user-uri) => {:entity :user :_id USER_ID}
(users/update-user! updated-user) => :the-updated-user)))
(def answer {:objective-id OBJECTIVE_ID :question-id QUESTION_ID})
(facts "about creating an answer"
(fact "succeeds when the question exists"
(actions/create-answer! answer) => {:status ::actions/success
:result :stored-answer}
(provided
(questions/get-question QUESTION_URI) => :a-question
(answers/store-answer! answer) => :stored-answer))
(fact "returns entity-not-found status when the associated question doesn't exist"
(actions/create-answer! answer) => {:status ::actions/entity-not-found}
(provided
(questions/get-question QUESTION_URI) => nil))
(fact "returns failure status when storing the answer fails"
(actions/create-answer! answer) => {:status ::actions/failure}
(provided
(questions/get-question QUESTION_URI) => :a-question
(answers/store-answer! answer) => nil)))
(def invitation {:objective-id OBJECTIVE_ID
:invited-by-id USER_ID})
(facts "about creating an invitation"
(fact "succeeds when the inviter is an existing writer"
(against-background
(objectives/get-objectives-owned-by-user-id USER_ID) => [])
(actions/create-invitation! invitation) => {:status ::actions/success
:result :stored-invitation}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id OBJECTIVE_ID}]
(invitations/store-invitation! invitation) => :stored-invitation))
(fact "succeeds when the inviter is the objective owner"
(against-background
(writers/retrieve-writers-by-user-id USER_ID) => [])
(actions/create-invitation! invitation) => {:status ::actions/success
:result :stored-invitation}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(objectives/get-objectives-owned-by-user-id USER_ID) => [{:_id OBJECTIVE_ID}]
(invitations/store-invitation! invitation) => :stored-invitation))
(fact "returns failure status when the inviter is not authorised"
(actions/create-invitation! invitation) => {:status ::actions/failure}
(provided
(objectives/get-objective OBJECTIVE_ID) => :an-objective
(objectives/get-objectives-owned-by-user-id USER_ID) => []
(writers/retrieve-writers-by-user-id USER_ID) => []))
(fact "returns a list of objective-ids a user is writer-inviter for"
(actions/authorised-objectives-for-inviter USER_ID) => '(1 2 3 4)
(provided
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id 1} {:objective-id 2}]
(objectives/get-objectives-owned-by-user-id USER_ID) => [{:_id 3} {:_id 4}])))
(def objective {:created-by-id USER_ID :title "SOME TITLE"})
(def stored-objective (assoc objective :_id OBJECTIVE_ID))
(def retrieved-objective (assoc stored-objective :username "UserName"))
(def invitation {:invited-by-id USER_ID
:objective-id OBJECTIVE_ID
:reason (str "Default writer as creator of this objective")
:writer-name "UserName"})
(def writer-data {:invitation-uuid UU_ID
:invitee-id USER_ID})
(def user-uri (str "/users/" USER_ID))
(facts "about creating an objective"
(fact "when an objective is stored the creator becomes a writer for the objective"
(actions/create-objective! objective) => {:status ::actions/success
:result stored-objective}
(provided
(objectives/store-objective! objective) => stored-objective
(objectives/get-objective OBJECTIVE_ID) => retrieved-objective
(activities/store-activity! retrieved-objective) => anything
(users/retrieve-user user-uri) => {:username "UserName"}
(invitations/store-invitation! invitation) => {:uuid UU_ID}
(users/update-user! (contains {:profile {:name "UserName" :biog "This profile was automatically generated for the creator of objective: SOME TITLE"}})) => {}
(writers/create-writer writer-data) => :writer)))
(def writer-note {:note "the note content" :created-by-id USER_ID :note-on-uri ANSWER_URI})
(def entity-to-note-on {:objective-id OBJECTIVE_ID})
(facts "about creating a note"
(fact "writers can create a note against an answer"
(actions/create-writer-note! writer-note) => {:status ::actions/success
:result :stored-note}
(provided
(writer-notes/store-note-for! entity-to-note-on writer-note) => :stored-note
(writers/retrieve-writers-by-user-id USER_ID) => [{:objective-id OBJECTIVE_ID} {:objective-id 2}]
(storage/pg-retrieve-entity-by-uri ANSWER_URI :with-global-id) => entity-to-note-on
(writer-notes/retrieve-note ANSWER_URI) => [])))
(def admin-removal {:removal-uri OBJECTIVE-URI
:removed-by-uri USER_URI})
(fact "admin-removals"
(actions/create-admin-removal! admin-removal) => {:status ::actions/success
:result :stored-admin-removal}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => {:_id OBJECTIVE_ID}
(objectives/admin-remove-objective! {:_id OBJECTIVE_ID}) => {:_id OBJECTIVE_ID}
(admin-removals/store-admin-removal! admin-removal) => :stored-admin-removal))
(def promoted-objective-data {:objective-uri OBJECTIVE-URI :promoted-by USER_URI})
(facts "about promoting objectives"
(fact "does promote an existing objective when signed in as an admin"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/success
:result OBJECTIVE_ID}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => {:_id OBJECTIVE_ID}
(objectives/toggle-promoted-status! {:_id OBJECTIVE_ID}) => OBJECTIVE_ID))
(fact "unable to promote objective if user is not signed in"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => nil))
(fact "unable to promote objective if user is not an admin"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/forbidden}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => nil))
(fact "unable to promote objective if objective n'existe pas"
(actions/promote-objective! promoted-objective-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}
(storage/pg-retrieve-entity-by-uri OBJECTIVE-URI :with-global-id) => nil
)))
(def COMMENT_URI (str "/comments/" COMMENT_ID))
(def removed-comment-data {:_id COMMENT_ID :removal-uri COMMENT_URI :removed-by-uri USER_URI})
(facts "about removing comments"
(fact "does remove a comment when signed in as an admin and comment exists"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/success
:result COMMENT_ID}
(provided
(comments/admin-remove-comment! removed-comment-data) => COMMENT_ID
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => removed-comment-data
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "returns forbidden if comment removal unsuccessful"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/forbidden}
(provided
(comments/admin-remove-comment! removed-comment-data) => nil
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => removed-comment-data
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "unable to delete comment if comment does not exist"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/entity-not-found}
(provided
(storage/pg-retrieve-entity-by-uri COMMENT_URI :with-global-id) => nil
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => {:auth-provider-user-id "twitter-123456"}))
(fact "unable to delete comment if user is not an admin"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/forbidden}
(provided
(users/retrieve-user USER_URI) => {:auth-provider-user-id "twitter-123456"}
(users/get-admin-by-auth-provider-user-id "twitter-123456") => nil))
(fact "unable to delete comment if user is not signed in"
(actions/admin-remove-comment! removed-comment-data) => {:status ::actions/entity-not-found}
(provided
(users/retrieve-user USER_URI) => nil)))
|
[
{
"context": " [:developer\n [:id \"weavejester\"]\n [:name \"James Reeves\"]]\n ",
"end": 711,
"score": 0.9967065453529358,
"start": 700,
"tag": "USERNAME",
"value": "weavejester"
},
{
"context": " [:id \"weavejester\"]\n [:name \"James Reeves\"]]\n [:developer\n ",
"end": 753,
"score": 0.9998512864112854,
"start": 741,
"tag": "NAME",
"value": "James Reeves"
}
] |
weavejester/dependency/project.clj
|
juxt/clojars-mirrors
| 0 |
(defproject pro.juxt.clojars-mirrors.weavejester/dependency "0.2.1"
:description "A data structure for representing dependency graphs (mirrored from Clojars by JUXT)"
:url "https://github.com/weavejester/dependency"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:scm {:dir "../.."}
:dependencies [^:inline-dep [weavejester/dependency "0.2.1"
:exclusions []]]
:exclusions [org.clojure/clojure]
:plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]]
:mranderson {:project-prefix "juxt.clojars-mirrors"}
:pom-addition ([:developers
[:developer
[:id "weavejester"]
[:name "James Reeves"]]
[:developer
[:id "juxt"]
[:name "JUXT"]
[:roles [:role "packager"]]]])
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}})
|
20783
|
(defproject pro.juxt.clojars-mirrors.weavejester/dependency "0.2.1"
:description "A data structure for representing dependency graphs (mirrored from Clojars by JUXT)"
:url "https://github.com/weavejester/dependency"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:scm {:dir "../.."}
:dependencies [^:inline-dep [weavejester/dependency "0.2.1"
:exclusions []]]
:exclusions [org.clojure/clojure]
:plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]]
:mranderson {:project-prefix "juxt.clojars-mirrors"}
:pom-addition ([:developers
[:developer
[:id "weavejester"]
[:name "<NAME>"]]
[:developer
[:id "juxt"]
[:name "JUXT"]
[:roles [:role "packager"]]]])
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}})
| true |
(defproject pro.juxt.clojars-mirrors.weavejester/dependency "0.2.1"
:description "A data structure for representing dependency graphs (mirrored from Clojars by JUXT)"
:url "https://github.com/weavejester/dependency"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:scm {:dir "../.."}
:dependencies [^:inline-dep [weavejester/dependency "0.2.1"
:exclusions []]]
:exclusions [org.clojure/clojure]
:plugins [[io.github.jarohen/mranderson "0.5.4-SNAPSHOT"]]
:mranderson {:project-prefix "juxt.clojars-mirrors"}
:pom-addition ([:developers
[:developer
[:id "weavejester"]
[:name "PI:NAME:<NAME>END_PI"]]
[:developer
[:id "juxt"]
[:name "JUXT"]
[:roles [:role "packager"]]]])
:deploy-repositories {"releases" {:url "https://oss.sonatype.org/service/local/staging/deploy/maven2"
:creds :gpg}
"snapshots" {:url "https://oss.sonatype.org/content/repositories/snapshots"
:creds :gpg}})
|
[
{
"context": "credentials.\"\n [lora]\n (let [app-eui \"70B3D57ED0030333\"\n app-key \"70DD7BFD8ED660DC52AE7F7",
"end": 502,
"score": 0.905706524848938,
"start": 486,
"tag": "KEY",
"value": "70B3D57ED0030333"
},
{
"context": " \"70B3D57ED0030333\"\n app-key \"70DD7BFD8ED660DC52AE7F7D0BDB87B9\"\n device-eui \"005A344421CF7401\"]\n ",
"end": 561,
"score": 0.999661386013031,
"start": 529,
"tag": "KEY",
"value": "70DD7BFD8ED660DC52AE7F7D0BDB87B9"
}
] |
src/lostik/repl.clj
|
ClockworksIO/lostik
| 0 |
(ns lostik.repl
"REPL boilerplate to interactively connect to lostik and develop this library."
(:require
[clojure.core.async :as a]
[geraet.util :refer [normalize->eui]]
[lostik.device :as dv :refer [cmd! device-info! led! enable-device! new-device print-msg]]
[lostik.lora :as l]
[serial.core :as sc]
[lostik.util :as u]))
(comment
(defn join-ttn
"Perform an OTAA join on The Things Network using example credentials."
[lora]
(let [app-eui "70B3D57ED0030333"
app-key "70DD7BFD8ED660DC52AE7F7D0BDB87B9"
device-eui "005A344421CF7401"]
(l/join! lora app-eui app-key device-eui)))
"Example on how to setup lostik device, join the The Things Network and send
example payload ASCII bytes 'abc'."
(def lora (l/new-lora "/dev/ttyUSB0"))
(l/enable! lora)
(join-ttn lora)
(send-data! lora (u/str->bytes "abc")))
|
10102
|
(ns lostik.repl
"REPL boilerplate to interactively connect to lostik and develop this library."
(:require
[clojure.core.async :as a]
[geraet.util :refer [normalize->eui]]
[lostik.device :as dv :refer [cmd! device-info! led! enable-device! new-device print-msg]]
[lostik.lora :as l]
[serial.core :as sc]
[lostik.util :as u]))
(comment
(defn join-ttn
"Perform an OTAA join on The Things Network using example credentials."
[lora]
(let [app-eui "<KEY>"
app-key "<KEY>"
device-eui "005A344421CF7401"]
(l/join! lora app-eui app-key device-eui)))
"Example on how to setup lostik device, join the The Things Network and send
example payload ASCII bytes 'abc'."
(def lora (l/new-lora "/dev/ttyUSB0"))
(l/enable! lora)
(join-ttn lora)
(send-data! lora (u/str->bytes "abc")))
| true |
(ns lostik.repl
"REPL boilerplate to interactively connect to lostik and develop this library."
(:require
[clojure.core.async :as a]
[geraet.util :refer [normalize->eui]]
[lostik.device :as dv :refer [cmd! device-info! led! enable-device! new-device print-msg]]
[lostik.lora :as l]
[serial.core :as sc]
[lostik.util :as u]))
(comment
(defn join-ttn
"Perform an OTAA join on The Things Network using example credentials."
[lora]
(let [app-eui "PI:KEY:<KEY>END_PI"
app-key "PI:KEY:<KEY>END_PI"
device-eui "005A344421CF7401"]
(l/join! lora app-eui app-key device-eui)))
"Example on how to setup lostik device, join the The Things Network and send
example payload ASCII bytes 'abc'."
(def lora (l/new-lora "/dev/ttyUSB0"))
(l/enable! lora)
(join-ttn lora)
(send-data! lora (u/str->bytes "abc")))
|
[
{
"context": " (.setProperty \"javax.net.ssl.keyStorePassword\" \"aaaaaa\")\n (.setProperty \"javax.net.ssl.trustStore\" \"C:\\",
"end": 1075,
"score": 0.9873809814453125,
"start": 1069,
"tag": "PASSWORD",
"value": "aaaaaa"
},
{
"context": ".setProperty \"javax.net.ssl.trustStorePassword\", \"aaaaaa\"))\n\n(def userid \"super\")\n(def vos-view-type (SysC",
"end": 1226,
"score": 0.9949023723602295,
"start": 1220,
"tag": "PASSWORD",
"value": "aaaaaa"
}
] |
scripts/edit-pm-ldap.clj
|
PM-Master/PM
| 3 |
(ns gov.nist.csd.pm.scripts
(:import
(javax.swing WindowConstants JFrame JButton JTree JLabel SwingUtilities JTextArea JTextField
Action JScrollPane AbstractAction JMenuBar JMenu JPopupMenu JMenuItem JList ListModel KeyStroke InputMap ActionMap
JOptionPane JDialog JPanel)
(javax.swing.event ListSelectionListener)
(javax.swing.text JTextComponent)
(javax.swing.tree TreeModel TreeSelectionModel)
(java.awt Point Dialog Dialog$ModalityType)
(java.awt.event ActionListener ActionEvent KeyEvent InputEvent MouseAdapter)
(gov.nist.csd.pm.common.application SysCaller SysCallerImpl SSLSocketClient)
(gov.nist.csd.pm.common.net ItemType Packet)
(gov.nist.csd.pm.user CommandUtil)
(net.miginfocom.swing MigLayout)))
(load-file "./cljtoolbox.clj")
(load-file "./pm-commands.clj")
(refer 'toolboxes.cljtoolbox)
(refer 'pm-commands)
(println "hello world")
(doto (System/getProperties)
(.setProperty "javax.net.ssl.keyStore" "C:\\PM\\pm1.4\\keystores\\superKeystore")
(.setProperty "javax.net.ssl.keyStorePassword" "aaaaaa")
(.setProperty "javax.net.ssl.trustStore" "C:\\PM\\pm1.4\\keystores\\clientTruststore")
(.setProperty "javax.net.ssl.trustStorePassword", "aaaaaa"))
(def userid "super")
(def vos-view-type (SysCaller/PM_VOS_PRES_ADMIN))
(def client (SSLSocketClient. "localhost" 8081 true "scripter"))
(def sessinfo (CommandUtil/createSession client userid (.toCharArray userid)))
(println "sessinfo")
(def sid (.getSessionId sessinfo))
(def suid (.getUserId sessinfo))
(def process (CommandUtil/createProcess (.getSessionId sessinfo) client))
(println "process")
(def sys-caller (SysCallerImpl. 8081 (.getSessionId sessinfo) process true "clj"))
(println "sys-caller")
(defn send-command-packet [client cmd & args]
(let [packet (Packet.)]
(.addItem packet (ItemType/CMD_CODE)cmd)
(doseq [arg args] (.addItem packet (ItemType/CMD_ARG) arg))
(println "Issuing command")
(let [result (.sendReceive client packet (System/out))]
(println "Command issued")
(if-let [err (.hasError result)]
(println "Error in" cmd (.getErrorMessage result))
'("ok ")))))
(def command-to-ksim (partial send-command-packet client))
(command-to-ksim "computeVos" sid vos-view-type suid sid)
(defn remove-obj [coll pred]
(remove pred coll))
(defprotocol Contextual
(is-context? [p o])
(try-action [p o]))
(def action-key-names
{:accelerator Action/ACCELERATOR_KEY
:action_cmd Action/ACTION_COMMAND_KEY
:default Action/DEFAULT
:long Action/LONG_DESCRIPTION
:mnemonic Action/MNEMONIC_KEY
:short Action/SHORT_DESCRIPTION
:sm_icon Action/SMALL_ICON
:name Action/NAME})
(defn action
([name map f]
(let [act (proxy [AbstractAction] []
(actionPerformed [ae] (f ae)))]
(doseq [k (keys map)]
(println "Putting value" (get action-key-names k) (get map k))
(.putValue act (str (get action-key-names k)) (str (get map k))))
(println "returning action" act)
act))
([name f]
(action name {:name name} f)))
(defn action-event [o action]
(ActionEvent. o 0 (.getValue action Action/ACTION_COMMAND_KEY)))
(deftype ContextAction [action test]
Contextual
(is-context? [p o] (test o))
(try-action [p o] (when-let [is-ctx (is-context? p o)] (.actionPerformed action (action-event o )))))
(defn proxy-action
"Creates an Action wrapper that calls postfn after calling the proxied Action's
actionPerformed method"
[action postfn]
(proxy [Action][]
(addPropertyChangeListener [pcl] (.addPropertyChangeListener action pcl))
(removePropertyChangeListener [pcl] (.removePropertyChangeListener action pcl))
(getValue [key] (.getValue action key))
(putValue [key value] (.putValue action key value))
(isEnabled [] (.isEnabled action))
(setEnabled [e] (.setEnabled action e))
(actionPerformed [ae]
(.actionPerformed action ae)
(postfn ae))))
(defn modal-dialog
"Constructs a modal dialog with a content panel and a set of actions
Each action will be represented by a button on the bottom of the dialog.
Pressing any of the buttons will close the dialog"
[title content & rawactions]
(let [awindow (get-active-window)
dialog (JDialog. awindow title Dialog$ModalityType/APPLICATION_MODAL)
closefn (fn [ae] (.setVisible dialog false))
actions (map #(proxy-action % closefn) rawactions)
but-first (rest actions)
split-str (str "split " (count actions))]
(doto dialog
(.setLayout (MigLayout. "" "[fill, grow][]" ""))
(.add content "wrap")
(.add (JButton. (first actions)) split-str)
(.setLocationRelativeTo awindow))
(doseq [action but-first]
(.add dialog (JButton. action)))
dialog))
(defn present-request-dialog
"Method for getting information from the user
Input a title and some property names and this
method will present a modal dialog to gather input
and return that input as a list."
[title & propnames]
(let [panel (doto (JPanel.) (.setLayout (MigLayout. "" "[][fill, grow]" "")))
comps (map (fn [name] [(JLabel. name)(JTextField. 30)]) propnames)]
(doseq [pair comps]
(doto panel
(.add (first pair) "label")
(.add (second pair) "wrap")))
(let [result (atom false)
dialog (modal-dialog title panel
(action "OK" (fn [ae] (reset! result true)))
(action "Cancel" (fn [ae] (reset! result false))))]
(doto dialog
(.pack)
(.setVisible true))
(if @result
(map #(.getText (second %)) comps)
[]))))
(defprotocol Node
(get-output [p])
(get-label [p])
(get-id [p])
(get-type [p]))
(deftype PMNode [type id label]
Node
(get-output [p] (str "Node of class " (class p) "Type: " type "ID: " id "Label: " label))
(get-label [p] label)
(get-id [p] id)
(get-type [p] type)
Object
(toString [self] label))
(defn third
"Returns the third element of a list or the 2nth :-)"
[coll] (nth coll 2))
(defn get-pos-members-of
"returns the pos members of a VOS constructed for this session.
Note: a session must be created and a vos constructed before calling this method.
Otherwise nothing will be returned"
[sys-caller node]
(println (get-output node))
(println (str "SysCaller " sys-caller))
(map
#(PMNode. (first %1) (second %) (third %))
(.getPosMembersOf sys-caller (get-label node) (get-id node) (get-type node) vos-view-type)))
(defn graph-model [sys-caller]
"Returns a TreeModel of the current sessions VOS
Only loads the currently expanded levels of the VOS"
(let [listeners (atom '())
get-pos-members (memoize (partial get-pos-members-of sys-caller))]
(proxy [TreeModel] []
(addTreeModelListener [l] (swap! listeners conj l))
(getChild [parent index] (nth (get-pos-members parent) index))
(getChildCount [parent] (count (get-pos-members parent)))
(getIndexOfChild [parent child] (.indexOf child (get-pos-members parent)) )
(getRoot [] (PMNode. (SysCaller/PM_NODE_CONN) (SysCaller/PM_CONNECTOR_ID) (SysCaller/PM_CONNECTOR_NAME)))
(isLeaf [node] (empty? (get-pos-members node)))
(removeTreeModelListener [l] (swap! listeners remove-obj l))
(valueForPathChanged[path newValue]))))
(defn default-scroll-pane [view]
"Just a scrollpane. These defaults are more useful
than the ones set in the constructor."
(doto (JScrollPane. view)
(.setHorizontalScrollBarPolicy JScrollPane/HORIZONTAL_SCROLLBAR_AS_NEEDED)
(.setVerticalScrollBarPolicy JScrollPane/VERTICAL_SCROLLBAR_ALWAYS)
(.. getVerticalScrollBar (setUnitIncrement 10))
(.. getVerticalScrollBar (setBlockIncrement 10))
(.. getHorizontalScrollBar (setUnitIncrement 10))
(.. getHorizontalScrollBar (setBlockIncrement 10))))
(defn list-model [listfn]
"Takes listfn, a function with no arguments, and expects that function
to return a sequence or list. That returned list is used to populate the
ListModel"
(let [listeners (atom [])]
(proxy [ListModel] []
(addListDataListener [l] (swap! listeners conj l))
(removeListDataListener [l] (swap! listeners remove-obj l))
(getElementAt [i] (nth (listfn) i))
(getSize [] (count (listfn))))))
(defn list-selection-listener [selectionfn]
(proxy [ListSelectionListener] []
(valueChanged [e]
(if (instance? JList (.getSource e))
(println "is jlist")
(println "is not jlist"))
(println "SelectionChanged" e)
(selectionfn e))))
(defn listing-window [listfn selectionfn actionEvent]
(doto (JFrame. "listing window")
(.setLayout (MigLayout. "" "[fill, grow]" "[fill, grow]"))
(.add (default-scroll-pane
(doto (JList.)
(.setModel
(list-model listfn))
(.addListSelectionListener (list-selection-listener selectionfn)))))
(.setSize 400 400)
(.setVisible true)))
(defn list-detail-window [listfn detailfn actionEvent]
(let [window (get-active-window)
textview (doto (JTextArea. ) (.setEnabled false))
selfn (fn selected [e]
(println "list detail selected")
(let [details (detailfn (-> e .getSource .getSelectedValue))]
(println (class details) details)
(.setText textview details)))]
(doto (listing-window listfn selfn actionEvent)
(.setLocationRelativeTo window)
(.add textview "newline"))))
(defn template-list [sys-caller]
(-> sys-caller .getTemplates .getStringValues))
(defn get-entity-name [sys-caller eid]
(println "getting named entity" eid)
(.getEntityName sys-caller eid SysCaller/PM_NODE_OATTR))
(defn template-detail [sys-caller template-info]
(let [tid (second (split ":" template-info))
tinfo (-> sys-caller (.getTemplateInfo tid) (.getStringValues))
splits (->> tinfo second (split ":"))
]
(println "getting template detail" tid "from template list" template-info " splits " (apply str splits) )
(str (sjoin "\n" tinfo) "\n" (sjoin ", " (map (partial get-entity-name sys-caller) splits)))))
(defn execute-command [sys-caller textsource actionEvent]
(let [res (->> textsource (.getText) (eval))]
(println res)
(load-string res)))
(defn executor-window [sys-caller actionEvent]
(let [textarea (JTextArea.)
execute-action (action "Execute" (partial execute-command sys-caller textarea))
inputmap (.getInputMap textarea)
actionmap (.getActionMap textarea)
exactionname "exec-action"
keystroke (KeyStroke/getKeyStroke KeyEvent/VK_ENTER InputEvent/SHIFT_DOWN_MASK)]
(println "putting inputmap in place of" (.get inputmap keystroke))
(.put inputmap keystroke exactionname)
(println "replaces input action with" (.get inputmap keystroke))
(println "putting actionmap")
(.put actionmap exactionname execute-action)
(doto (JFrame.)
(.setSize 800 400)
(.setLayout (MigLayout. "" "[grow, fill][align left]" "[grow, fill][]"))
(.add (default-scroll-pane textarea))
(.add (JButton. execute-action) "newline")
(.setVisible true))))
(defn make-menu [sys-caller]
(let [listfn (partial template-list sys-caller)
detailfn (partial template-detail sys-caller)
template-window (partial list-detail-window listfn detailfn)]
(doto (JMenuBar.)
(.add (doto (JMenu. "File")
(.add (doto (JMenuItem. "Open...")))
(.add (doto (JMenuItem. (action "Exit" (fn exit [ae] (System/exit 0))))))
(.add (JMenuItem. (action "Show Templates..." template-window)))
(.add (JMenuItem. (action "Executor..." (partial executor-window sys-caller)))))))))
(defmulti get-context-for (fn [obj x y]
(println "classifying" obj x y)
(class obj)))
(defmethod get-context-for JList [obj x y]
(println "is jlist")
(.locationToIndex obj (Point. x y)))
(defmethod get-context-for JTree [obj x y]
(println "is jtree")
(if-let [path (.getPathForLocation obj x y)]
(.getLastPathComponent path)
nil))
(defmethod get-context-for :default [obj x y]
(println "oops")
nil)
(defn add-property-action [sys-caller pmnode actionEvent]
(let [props (present-request-dialog "Input Property" "Name" "Value")
cmd (add-property (decode-from-pmspeak (get-type pmnode))
(first props)
(second props)
(get-label pmnode))]
(println "Prop Values Retrieved" props)
(println "Command Constructed" cmd)))
(defn add-object-action [sys-caller pmnode actionEvent]
(let [props (present-request-dialog (str "Add object under" (get-label pmnode)) "Object Name")
sclass "Object attribute"
includesAscendants "yes"
host (get-label pmnode)
totype "p"
toname (get-policy-class pmnode)
cmd (add-object (decode-from-pmspeak (get-type pmnode))
(first props)
(second sprops)
(get-label pmnode))]
))
(defmulti context-menu-maker (fn [obj sc] (class obj)))
(defmethod context-menu-maker PMNode [pmnode sys-caller]
(println "need to supply actions for pm node")
(doto (JPopupMenu.)
(.add (JMenuItem. (action "Add Property" (partial add-property-action sys-caller pmnode))))
(.add (JMenuItem. (action "Add Object" (partial add-object-action sys-caller pmnode))))
(.add (JMenuItem. "Add File Object"))
(.add (JMenuItem. "Copy Object"))
(.add (JMenuItem. "Paste Object"))))
(defmethod context-menu-maker :default [obj sys-caller]
(println "no menu defined for object of type" (class obj) obj)
(JPopupMenu.))
(defn window [sys-caller]
(println "showing window")
(let [frame (JFrame. "Viewer")
menu (make-menu sys-caller)
tree (JTree. (graph-model sys-caller))
check-for-pop (fn [me] (
let [source (.getSource me)
point (.getPoint me)
x (.getX point)
y (.getY point)]
(println "is is being triggered?")
(if (.isPopupTrigger me)
(when-let [context (get-context-for source x y)]
(doto (context-menu-maker context sys-caller)
(.show (.getComponent me) x y)))
(println "not a poppler"))))]
(.addMouseListener tree (proxy [MouseAdapter] []
(mousePressed [me]
(println "Pressed check"))
(mouseReleased [me]
(println "Released check")
(check-for-pop me))))
(doto frame
(.setSize 400 400)
(.setLayout (MigLayout. "" "[fill, grow]" "[fill, grow]"))
(.add (default-scroll-pane tree))
(.setJMenuBar menu)
(.setDefaultCloseOperation (WindowConstants/EXIT_ON_CLOSE))
(.setVisible true))))
(def rt (Runtime/getRuntime))
(.addShutdownHook rt
(proxy [Thread] []
(run [] (println "goodbye")
(CommandUtil/exitProcess sid process client)
(CommandUtil/exitSession sid client))))
(SwingUtilities/invokeLater (partial window sys-caller))
(println "done")
|
64140
|
(ns gov.nist.csd.pm.scripts
(:import
(javax.swing WindowConstants JFrame JButton JTree JLabel SwingUtilities JTextArea JTextField
Action JScrollPane AbstractAction JMenuBar JMenu JPopupMenu JMenuItem JList ListModel KeyStroke InputMap ActionMap
JOptionPane JDialog JPanel)
(javax.swing.event ListSelectionListener)
(javax.swing.text JTextComponent)
(javax.swing.tree TreeModel TreeSelectionModel)
(java.awt Point Dialog Dialog$ModalityType)
(java.awt.event ActionListener ActionEvent KeyEvent InputEvent MouseAdapter)
(gov.nist.csd.pm.common.application SysCaller SysCallerImpl SSLSocketClient)
(gov.nist.csd.pm.common.net ItemType Packet)
(gov.nist.csd.pm.user CommandUtil)
(net.miginfocom.swing MigLayout)))
(load-file "./cljtoolbox.clj")
(load-file "./pm-commands.clj")
(refer 'toolboxes.cljtoolbox)
(refer 'pm-commands)
(println "hello world")
(doto (System/getProperties)
(.setProperty "javax.net.ssl.keyStore" "C:\\PM\\pm1.4\\keystores\\superKeystore")
(.setProperty "javax.net.ssl.keyStorePassword" "<PASSWORD>")
(.setProperty "javax.net.ssl.trustStore" "C:\\PM\\pm1.4\\keystores\\clientTruststore")
(.setProperty "javax.net.ssl.trustStorePassword", "<PASSWORD>"))
(def userid "super")
(def vos-view-type (SysCaller/PM_VOS_PRES_ADMIN))
(def client (SSLSocketClient. "localhost" 8081 true "scripter"))
(def sessinfo (CommandUtil/createSession client userid (.toCharArray userid)))
(println "sessinfo")
(def sid (.getSessionId sessinfo))
(def suid (.getUserId sessinfo))
(def process (CommandUtil/createProcess (.getSessionId sessinfo) client))
(println "process")
(def sys-caller (SysCallerImpl. 8081 (.getSessionId sessinfo) process true "clj"))
(println "sys-caller")
(defn send-command-packet [client cmd & args]
(let [packet (Packet.)]
(.addItem packet (ItemType/CMD_CODE)cmd)
(doseq [arg args] (.addItem packet (ItemType/CMD_ARG) arg))
(println "Issuing command")
(let [result (.sendReceive client packet (System/out))]
(println "Command issued")
(if-let [err (.hasError result)]
(println "Error in" cmd (.getErrorMessage result))
'("ok ")))))
(def command-to-ksim (partial send-command-packet client))
(command-to-ksim "computeVos" sid vos-view-type suid sid)
(defn remove-obj [coll pred]
(remove pred coll))
(defprotocol Contextual
(is-context? [p o])
(try-action [p o]))
(def action-key-names
{:accelerator Action/ACCELERATOR_KEY
:action_cmd Action/ACTION_COMMAND_KEY
:default Action/DEFAULT
:long Action/LONG_DESCRIPTION
:mnemonic Action/MNEMONIC_KEY
:short Action/SHORT_DESCRIPTION
:sm_icon Action/SMALL_ICON
:name Action/NAME})
(defn action
([name map f]
(let [act (proxy [AbstractAction] []
(actionPerformed [ae] (f ae)))]
(doseq [k (keys map)]
(println "Putting value" (get action-key-names k) (get map k))
(.putValue act (str (get action-key-names k)) (str (get map k))))
(println "returning action" act)
act))
([name f]
(action name {:name name} f)))
(defn action-event [o action]
(ActionEvent. o 0 (.getValue action Action/ACTION_COMMAND_KEY)))
(deftype ContextAction [action test]
Contextual
(is-context? [p o] (test o))
(try-action [p o] (when-let [is-ctx (is-context? p o)] (.actionPerformed action (action-event o )))))
(defn proxy-action
"Creates an Action wrapper that calls postfn after calling the proxied Action's
actionPerformed method"
[action postfn]
(proxy [Action][]
(addPropertyChangeListener [pcl] (.addPropertyChangeListener action pcl))
(removePropertyChangeListener [pcl] (.removePropertyChangeListener action pcl))
(getValue [key] (.getValue action key))
(putValue [key value] (.putValue action key value))
(isEnabled [] (.isEnabled action))
(setEnabled [e] (.setEnabled action e))
(actionPerformed [ae]
(.actionPerformed action ae)
(postfn ae))))
(defn modal-dialog
"Constructs a modal dialog with a content panel and a set of actions
Each action will be represented by a button on the bottom of the dialog.
Pressing any of the buttons will close the dialog"
[title content & rawactions]
(let [awindow (get-active-window)
dialog (JDialog. awindow title Dialog$ModalityType/APPLICATION_MODAL)
closefn (fn [ae] (.setVisible dialog false))
actions (map #(proxy-action % closefn) rawactions)
but-first (rest actions)
split-str (str "split " (count actions))]
(doto dialog
(.setLayout (MigLayout. "" "[fill, grow][]" ""))
(.add content "wrap")
(.add (JButton. (first actions)) split-str)
(.setLocationRelativeTo awindow))
(doseq [action but-first]
(.add dialog (JButton. action)))
dialog))
(defn present-request-dialog
"Method for getting information from the user
Input a title and some property names and this
method will present a modal dialog to gather input
and return that input as a list."
[title & propnames]
(let [panel (doto (JPanel.) (.setLayout (MigLayout. "" "[][fill, grow]" "")))
comps (map (fn [name] [(JLabel. name)(JTextField. 30)]) propnames)]
(doseq [pair comps]
(doto panel
(.add (first pair) "label")
(.add (second pair) "wrap")))
(let [result (atom false)
dialog (modal-dialog title panel
(action "OK" (fn [ae] (reset! result true)))
(action "Cancel" (fn [ae] (reset! result false))))]
(doto dialog
(.pack)
(.setVisible true))
(if @result
(map #(.getText (second %)) comps)
[]))))
(defprotocol Node
(get-output [p])
(get-label [p])
(get-id [p])
(get-type [p]))
(deftype PMNode [type id label]
Node
(get-output [p] (str "Node of class " (class p) "Type: " type "ID: " id "Label: " label))
(get-label [p] label)
(get-id [p] id)
(get-type [p] type)
Object
(toString [self] label))
(defn third
"Returns the third element of a list or the 2nth :-)"
[coll] (nth coll 2))
(defn get-pos-members-of
"returns the pos members of a VOS constructed for this session.
Note: a session must be created and a vos constructed before calling this method.
Otherwise nothing will be returned"
[sys-caller node]
(println (get-output node))
(println (str "SysCaller " sys-caller))
(map
#(PMNode. (first %1) (second %) (third %))
(.getPosMembersOf sys-caller (get-label node) (get-id node) (get-type node) vos-view-type)))
(defn graph-model [sys-caller]
"Returns a TreeModel of the current sessions VOS
Only loads the currently expanded levels of the VOS"
(let [listeners (atom '())
get-pos-members (memoize (partial get-pos-members-of sys-caller))]
(proxy [TreeModel] []
(addTreeModelListener [l] (swap! listeners conj l))
(getChild [parent index] (nth (get-pos-members parent) index))
(getChildCount [parent] (count (get-pos-members parent)))
(getIndexOfChild [parent child] (.indexOf child (get-pos-members parent)) )
(getRoot [] (PMNode. (SysCaller/PM_NODE_CONN) (SysCaller/PM_CONNECTOR_ID) (SysCaller/PM_CONNECTOR_NAME)))
(isLeaf [node] (empty? (get-pos-members node)))
(removeTreeModelListener [l] (swap! listeners remove-obj l))
(valueForPathChanged[path newValue]))))
(defn default-scroll-pane [view]
"Just a scrollpane. These defaults are more useful
than the ones set in the constructor."
(doto (JScrollPane. view)
(.setHorizontalScrollBarPolicy JScrollPane/HORIZONTAL_SCROLLBAR_AS_NEEDED)
(.setVerticalScrollBarPolicy JScrollPane/VERTICAL_SCROLLBAR_ALWAYS)
(.. getVerticalScrollBar (setUnitIncrement 10))
(.. getVerticalScrollBar (setBlockIncrement 10))
(.. getHorizontalScrollBar (setUnitIncrement 10))
(.. getHorizontalScrollBar (setBlockIncrement 10))))
(defn list-model [listfn]
"Takes listfn, a function with no arguments, and expects that function
to return a sequence or list. That returned list is used to populate the
ListModel"
(let [listeners (atom [])]
(proxy [ListModel] []
(addListDataListener [l] (swap! listeners conj l))
(removeListDataListener [l] (swap! listeners remove-obj l))
(getElementAt [i] (nth (listfn) i))
(getSize [] (count (listfn))))))
(defn list-selection-listener [selectionfn]
(proxy [ListSelectionListener] []
(valueChanged [e]
(if (instance? JList (.getSource e))
(println "is jlist")
(println "is not jlist"))
(println "SelectionChanged" e)
(selectionfn e))))
(defn listing-window [listfn selectionfn actionEvent]
(doto (JFrame. "listing window")
(.setLayout (MigLayout. "" "[fill, grow]" "[fill, grow]"))
(.add (default-scroll-pane
(doto (JList.)
(.setModel
(list-model listfn))
(.addListSelectionListener (list-selection-listener selectionfn)))))
(.setSize 400 400)
(.setVisible true)))
(defn list-detail-window [listfn detailfn actionEvent]
(let [window (get-active-window)
textview (doto (JTextArea. ) (.setEnabled false))
selfn (fn selected [e]
(println "list detail selected")
(let [details (detailfn (-> e .getSource .getSelectedValue))]
(println (class details) details)
(.setText textview details)))]
(doto (listing-window listfn selfn actionEvent)
(.setLocationRelativeTo window)
(.add textview "newline"))))
(defn template-list [sys-caller]
(-> sys-caller .getTemplates .getStringValues))
(defn get-entity-name [sys-caller eid]
(println "getting named entity" eid)
(.getEntityName sys-caller eid SysCaller/PM_NODE_OATTR))
(defn template-detail [sys-caller template-info]
(let [tid (second (split ":" template-info))
tinfo (-> sys-caller (.getTemplateInfo tid) (.getStringValues))
splits (->> tinfo second (split ":"))
]
(println "getting template detail" tid "from template list" template-info " splits " (apply str splits) )
(str (sjoin "\n" tinfo) "\n" (sjoin ", " (map (partial get-entity-name sys-caller) splits)))))
(defn execute-command [sys-caller textsource actionEvent]
(let [res (->> textsource (.getText) (eval))]
(println res)
(load-string res)))
(defn executor-window [sys-caller actionEvent]
(let [textarea (JTextArea.)
execute-action (action "Execute" (partial execute-command sys-caller textarea))
inputmap (.getInputMap textarea)
actionmap (.getActionMap textarea)
exactionname "exec-action"
keystroke (KeyStroke/getKeyStroke KeyEvent/VK_ENTER InputEvent/SHIFT_DOWN_MASK)]
(println "putting inputmap in place of" (.get inputmap keystroke))
(.put inputmap keystroke exactionname)
(println "replaces input action with" (.get inputmap keystroke))
(println "putting actionmap")
(.put actionmap exactionname execute-action)
(doto (JFrame.)
(.setSize 800 400)
(.setLayout (MigLayout. "" "[grow, fill][align left]" "[grow, fill][]"))
(.add (default-scroll-pane textarea))
(.add (JButton. execute-action) "newline")
(.setVisible true))))
(defn make-menu [sys-caller]
(let [listfn (partial template-list sys-caller)
detailfn (partial template-detail sys-caller)
template-window (partial list-detail-window listfn detailfn)]
(doto (JMenuBar.)
(.add (doto (JMenu. "File")
(.add (doto (JMenuItem. "Open...")))
(.add (doto (JMenuItem. (action "Exit" (fn exit [ae] (System/exit 0))))))
(.add (JMenuItem. (action "Show Templates..." template-window)))
(.add (JMenuItem. (action "Executor..." (partial executor-window sys-caller)))))))))
(defmulti get-context-for (fn [obj x y]
(println "classifying" obj x y)
(class obj)))
(defmethod get-context-for JList [obj x y]
(println "is jlist")
(.locationToIndex obj (Point. x y)))
(defmethod get-context-for JTree [obj x y]
(println "is jtree")
(if-let [path (.getPathForLocation obj x y)]
(.getLastPathComponent path)
nil))
(defmethod get-context-for :default [obj x y]
(println "oops")
nil)
(defn add-property-action [sys-caller pmnode actionEvent]
(let [props (present-request-dialog "Input Property" "Name" "Value")
cmd (add-property (decode-from-pmspeak (get-type pmnode))
(first props)
(second props)
(get-label pmnode))]
(println "Prop Values Retrieved" props)
(println "Command Constructed" cmd)))
(defn add-object-action [sys-caller pmnode actionEvent]
(let [props (present-request-dialog (str "Add object under" (get-label pmnode)) "Object Name")
sclass "Object attribute"
includesAscendants "yes"
host (get-label pmnode)
totype "p"
toname (get-policy-class pmnode)
cmd (add-object (decode-from-pmspeak (get-type pmnode))
(first props)
(second sprops)
(get-label pmnode))]
))
(defmulti context-menu-maker (fn [obj sc] (class obj)))
(defmethod context-menu-maker PMNode [pmnode sys-caller]
(println "need to supply actions for pm node")
(doto (JPopupMenu.)
(.add (JMenuItem. (action "Add Property" (partial add-property-action sys-caller pmnode))))
(.add (JMenuItem. (action "Add Object" (partial add-object-action sys-caller pmnode))))
(.add (JMenuItem. "Add File Object"))
(.add (JMenuItem. "Copy Object"))
(.add (JMenuItem. "Paste Object"))))
(defmethod context-menu-maker :default [obj sys-caller]
(println "no menu defined for object of type" (class obj) obj)
(JPopupMenu.))
(defn window [sys-caller]
(println "showing window")
(let [frame (JFrame. "Viewer")
menu (make-menu sys-caller)
tree (JTree. (graph-model sys-caller))
check-for-pop (fn [me] (
let [source (.getSource me)
point (.getPoint me)
x (.getX point)
y (.getY point)]
(println "is is being triggered?")
(if (.isPopupTrigger me)
(when-let [context (get-context-for source x y)]
(doto (context-menu-maker context sys-caller)
(.show (.getComponent me) x y)))
(println "not a poppler"))))]
(.addMouseListener tree (proxy [MouseAdapter] []
(mousePressed [me]
(println "Pressed check"))
(mouseReleased [me]
(println "Released check")
(check-for-pop me))))
(doto frame
(.setSize 400 400)
(.setLayout (MigLayout. "" "[fill, grow]" "[fill, grow]"))
(.add (default-scroll-pane tree))
(.setJMenuBar menu)
(.setDefaultCloseOperation (WindowConstants/EXIT_ON_CLOSE))
(.setVisible true))))
(def rt (Runtime/getRuntime))
(.addShutdownHook rt
(proxy [Thread] []
(run [] (println "goodbye")
(CommandUtil/exitProcess sid process client)
(CommandUtil/exitSession sid client))))
(SwingUtilities/invokeLater (partial window sys-caller))
(println "done")
| true |
(ns gov.nist.csd.pm.scripts
(:import
(javax.swing WindowConstants JFrame JButton JTree JLabel SwingUtilities JTextArea JTextField
Action JScrollPane AbstractAction JMenuBar JMenu JPopupMenu JMenuItem JList ListModel KeyStroke InputMap ActionMap
JOptionPane JDialog JPanel)
(javax.swing.event ListSelectionListener)
(javax.swing.text JTextComponent)
(javax.swing.tree TreeModel TreeSelectionModel)
(java.awt Point Dialog Dialog$ModalityType)
(java.awt.event ActionListener ActionEvent KeyEvent InputEvent MouseAdapter)
(gov.nist.csd.pm.common.application SysCaller SysCallerImpl SSLSocketClient)
(gov.nist.csd.pm.common.net ItemType Packet)
(gov.nist.csd.pm.user CommandUtil)
(net.miginfocom.swing MigLayout)))
(load-file "./cljtoolbox.clj")
(load-file "./pm-commands.clj")
(refer 'toolboxes.cljtoolbox)
(refer 'pm-commands)
(println "hello world")
(doto (System/getProperties)
(.setProperty "javax.net.ssl.keyStore" "C:\\PM\\pm1.4\\keystores\\superKeystore")
(.setProperty "javax.net.ssl.keyStorePassword" "PI:PASSWORD:<PASSWORD>END_PI")
(.setProperty "javax.net.ssl.trustStore" "C:\\PM\\pm1.4\\keystores\\clientTruststore")
(.setProperty "javax.net.ssl.trustStorePassword", "PI:PASSWORD:<PASSWORD>END_PI"))
(def userid "super")
(def vos-view-type (SysCaller/PM_VOS_PRES_ADMIN))
(def client (SSLSocketClient. "localhost" 8081 true "scripter"))
(def sessinfo (CommandUtil/createSession client userid (.toCharArray userid)))
(println "sessinfo")
(def sid (.getSessionId sessinfo))
(def suid (.getUserId sessinfo))
(def process (CommandUtil/createProcess (.getSessionId sessinfo) client))
(println "process")
(def sys-caller (SysCallerImpl. 8081 (.getSessionId sessinfo) process true "clj"))
(println "sys-caller")
(defn send-command-packet [client cmd & args]
(let [packet (Packet.)]
(.addItem packet (ItemType/CMD_CODE)cmd)
(doseq [arg args] (.addItem packet (ItemType/CMD_ARG) arg))
(println "Issuing command")
(let [result (.sendReceive client packet (System/out))]
(println "Command issued")
(if-let [err (.hasError result)]
(println "Error in" cmd (.getErrorMessage result))
'("ok ")))))
(def command-to-ksim (partial send-command-packet client))
(command-to-ksim "computeVos" sid vos-view-type suid sid)
(defn remove-obj [coll pred]
(remove pred coll))
(defprotocol Contextual
(is-context? [p o])
(try-action [p o]))
(def action-key-names
{:accelerator Action/ACCELERATOR_KEY
:action_cmd Action/ACTION_COMMAND_KEY
:default Action/DEFAULT
:long Action/LONG_DESCRIPTION
:mnemonic Action/MNEMONIC_KEY
:short Action/SHORT_DESCRIPTION
:sm_icon Action/SMALL_ICON
:name Action/NAME})
(defn action
([name map f]
(let [act (proxy [AbstractAction] []
(actionPerformed [ae] (f ae)))]
(doseq [k (keys map)]
(println "Putting value" (get action-key-names k) (get map k))
(.putValue act (str (get action-key-names k)) (str (get map k))))
(println "returning action" act)
act))
([name f]
(action name {:name name} f)))
(defn action-event [o action]
(ActionEvent. o 0 (.getValue action Action/ACTION_COMMAND_KEY)))
(deftype ContextAction [action test]
Contextual
(is-context? [p o] (test o))
(try-action [p o] (when-let [is-ctx (is-context? p o)] (.actionPerformed action (action-event o )))))
(defn proxy-action
"Creates an Action wrapper that calls postfn after calling the proxied Action's
actionPerformed method"
[action postfn]
(proxy [Action][]
(addPropertyChangeListener [pcl] (.addPropertyChangeListener action pcl))
(removePropertyChangeListener [pcl] (.removePropertyChangeListener action pcl))
(getValue [key] (.getValue action key))
(putValue [key value] (.putValue action key value))
(isEnabled [] (.isEnabled action))
(setEnabled [e] (.setEnabled action e))
(actionPerformed [ae]
(.actionPerformed action ae)
(postfn ae))))
(defn modal-dialog
"Constructs a modal dialog with a content panel and a set of actions
Each action will be represented by a button on the bottom of the dialog.
Pressing any of the buttons will close the dialog"
[title content & rawactions]
(let [awindow (get-active-window)
dialog (JDialog. awindow title Dialog$ModalityType/APPLICATION_MODAL)
closefn (fn [ae] (.setVisible dialog false))
actions (map #(proxy-action % closefn) rawactions)
but-first (rest actions)
split-str (str "split " (count actions))]
(doto dialog
(.setLayout (MigLayout. "" "[fill, grow][]" ""))
(.add content "wrap")
(.add (JButton. (first actions)) split-str)
(.setLocationRelativeTo awindow))
(doseq [action but-first]
(.add dialog (JButton. action)))
dialog))
(defn present-request-dialog
"Method for getting information from the user
Input a title and some property names and this
method will present a modal dialog to gather input
and return that input as a list."
[title & propnames]
(let [panel (doto (JPanel.) (.setLayout (MigLayout. "" "[][fill, grow]" "")))
comps (map (fn [name] [(JLabel. name)(JTextField. 30)]) propnames)]
(doseq [pair comps]
(doto panel
(.add (first pair) "label")
(.add (second pair) "wrap")))
(let [result (atom false)
dialog (modal-dialog title panel
(action "OK" (fn [ae] (reset! result true)))
(action "Cancel" (fn [ae] (reset! result false))))]
(doto dialog
(.pack)
(.setVisible true))
(if @result
(map #(.getText (second %)) comps)
[]))))
(defprotocol Node
(get-output [p])
(get-label [p])
(get-id [p])
(get-type [p]))
(deftype PMNode [type id label]
Node
(get-output [p] (str "Node of class " (class p) "Type: " type "ID: " id "Label: " label))
(get-label [p] label)
(get-id [p] id)
(get-type [p] type)
Object
(toString [self] label))
(defn third
"Returns the third element of a list or the 2nth :-)"
[coll] (nth coll 2))
(defn get-pos-members-of
"returns the pos members of a VOS constructed for this session.
Note: a session must be created and a vos constructed before calling this method.
Otherwise nothing will be returned"
[sys-caller node]
(println (get-output node))
(println (str "SysCaller " sys-caller))
(map
#(PMNode. (first %1) (second %) (third %))
(.getPosMembersOf sys-caller (get-label node) (get-id node) (get-type node) vos-view-type)))
(defn graph-model [sys-caller]
"Returns a TreeModel of the current sessions VOS
Only loads the currently expanded levels of the VOS"
(let [listeners (atom '())
get-pos-members (memoize (partial get-pos-members-of sys-caller))]
(proxy [TreeModel] []
(addTreeModelListener [l] (swap! listeners conj l))
(getChild [parent index] (nth (get-pos-members parent) index))
(getChildCount [parent] (count (get-pos-members parent)))
(getIndexOfChild [parent child] (.indexOf child (get-pos-members parent)) )
(getRoot [] (PMNode. (SysCaller/PM_NODE_CONN) (SysCaller/PM_CONNECTOR_ID) (SysCaller/PM_CONNECTOR_NAME)))
(isLeaf [node] (empty? (get-pos-members node)))
(removeTreeModelListener [l] (swap! listeners remove-obj l))
(valueForPathChanged[path newValue]))))
(defn default-scroll-pane [view]
"Just a scrollpane. These defaults are more useful
than the ones set in the constructor."
(doto (JScrollPane. view)
(.setHorizontalScrollBarPolicy JScrollPane/HORIZONTAL_SCROLLBAR_AS_NEEDED)
(.setVerticalScrollBarPolicy JScrollPane/VERTICAL_SCROLLBAR_ALWAYS)
(.. getVerticalScrollBar (setUnitIncrement 10))
(.. getVerticalScrollBar (setBlockIncrement 10))
(.. getHorizontalScrollBar (setUnitIncrement 10))
(.. getHorizontalScrollBar (setBlockIncrement 10))))
(defn list-model [listfn]
"Takes listfn, a function with no arguments, and expects that function
to return a sequence or list. That returned list is used to populate the
ListModel"
(let [listeners (atom [])]
(proxy [ListModel] []
(addListDataListener [l] (swap! listeners conj l))
(removeListDataListener [l] (swap! listeners remove-obj l))
(getElementAt [i] (nth (listfn) i))
(getSize [] (count (listfn))))))
(defn list-selection-listener [selectionfn]
(proxy [ListSelectionListener] []
(valueChanged [e]
(if (instance? JList (.getSource e))
(println "is jlist")
(println "is not jlist"))
(println "SelectionChanged" e)
(selectionfn e))))
(defn listing-window [listfn selectionfn actionEvent]
(doto (JFrame. "listing window")
(.setLayout (MigLayout. "" "[fill, grow]" "[fill, grow]"))
(.add (default-scroll-pane
(doto (JList.)
(.setModel
(list-model listfn))
(.addListSelectionListener (list-selection-listener selectionfn)))))
(.setSize 400 400)
(.setVisible true)))
(defn list-detail-window [listfn detailfn actionEvent]
(let [window (get-active-window)
textview (doto (JTextArea. ) (.setEnabled false))
selfn (fn selected [e]
(println "list detail selected")
(let [details (detailfn (-> e .getSource .getSelectedValue))]
(println (class details) details)
(.setText textview details)))]
(doto (listing-window listfn selfn actionEvent)
(.setLocationRelativeTo window)
(.add textview "newline"))))
(defn template-list [sys-caller]
(-> sys-caller .getTemplates .getStringValues))
(defn get-entity-name [sys-caller eid]
(println "getting named entity" eid)
(.getEntityName sys-caller eid SysCaller/PM_NODE_OATTR))
(defn template-detail [sys-caller template-info]
(let [tid (second (split ":" template-info))
tinfo (-> sys-caller (.getTemplateInfo tid) (.getStringValues))
splits (->> tinfo second (split ":"))
]
(println "getting template detail" tid "from template list" template-info " splits " (apply str splits) )
(str (sjoin "\n" tinfo) "\n" (sjoin ", " (map (partial get-entity-name sys-caller) splits)))))
(defn execute-command [sys-caller textsource actionEvent]
(let [res (->> textsource (.getText) (eval))]
(println res)
(load-string res)))
(defn executor-window [sys-caller actionEvent]
(let [textarea (JTextArea.)
execute-action (action "Execute" (partial execute-command sys-caller textarea))
inputmap (.getInputMap textarea)
actionmap (.getActionMap textarea)
exactionname "exec-action"
keystroke (KeyStroke/getKeyStroke KeyEvent/VK_ENTER InputEvent/SHIFT_DOWN_MASK)]
(println "putting inputmap in place of" (.get inputmap keystroke))
(.put inputmap keystroke exactionname)
(println "replaces input action with" (.get inputmap keystroke))
(println "putting actionmap")
(.put actionmap exactionname execute-action)
(doto (JFrame.)
(.setSize 800 400)
(.setLayout (MigLayout. "" "[grow, fill][align left]" "[grow, fill][]"))
(.add (default-scroll-pane textarea))
(.add (JButton. execute-action) "newline")
(.setVisible true))))
(defn make-menu [sys-caller]
(let [listfn (partial template-list sys-caller)
detailfn (partial template-detail sys-caller)
template-window (partial list-detail-window listfn detailfn)]
(doto (JMenuBar.)
(.add (doto (JMenu. "File")
(.add (doto (JMenuItem. "Open...")))
(.add (doto (JMenuItem. (action "Exit" (fn exit [ae] (System/exit 0))))))
(.add (JMenuItem. (action "Show Templates..." template-window)))
(.add (JMenuItem. (action "Executor..." (partial executor-window sys-caller)))))))))
(defmulti get-context-for (fn [obj x y]
(println "classifying" obj x y)
(class obj)))
(defmethod get-context-for JList [obj x y]
(println "is jlist")
(.locationToIndex obj (Point. x y)))
(defmethod get-context-for JTree [obj x y]
(println "is jtree")
(if-let [path (.getPathForLocation obj x y)]
(.getLastPathComponent path)
nil))
(defmethod get-context-for :default [obj x y]
(println "oops")
nil)
(defn add-property-action [sys-caller pmnode actionEvent]
(let [props (present-request-dialog "Input Property" "Name" "Value")
cmd (add-property (decode-from-pmspeak (get-type pmnode))
(first props)
(second props)
(get-label pmnode))]
(println "Prop Values Retrieved" props)
(println "Command Constructed" cmd)))
(defn add-object-action [sys-caller pmnode actionEvent]
(let [props (present-request-dialog (str "Add object under" (get-label pmnode)) "Object Name")
sclass "Object attribute"
includesAscendants "yes"
host (get-label pmnode)
totype "p"
toname (get-policy-class pmnode)
cmd (add-object (decode-from-pmspeak (get-type pmnode))
(first props)
(second sprops)
(get-label pmnode))]
))
(defmulti context-menu-maker (fn [obj sc] (class obj)))
(defmethod context-menu-maker PMNode [pmnode sys-caller]
(println "need to supply actions for pm node")
(doto (JPopupMenu.)
(.add (JMenuItem. (action "Add Property" (partial add-property-action sys-caller pmnode))))
(.add (JMenuItem. (action "Add Object" (partial add-object-action sys-caller pmnode))))
(.add (JMenuItem. "Add File Object"))
(.add (JMenuItem. "Copy Object"))
(.add (JMenuItem. "Paste Object"))))
(defmethod context-menu-maker :default [obj sys-caller]
(println "no menu defined for object of type" (class obj) obj)
(JPopupMenu.))
(defn window [sys-caller]
(println "showing window")
(let [frame (JFrame. "Viewer")
menu (make-menu sys-caller)
tree (JTree. (graph-model sys-caller))
check-for-pop (fn [me] (
let [source (.getSource me)
point (.getPoint me)
x (.getX point)
y (.getY point)]
(println "is is being triggered?")
(if (.isPopupTrigger me)
(when-let [context (get-context-for source x y)]
(doto (context-menu-maker context sys-caller)
(.show (.getComponent me) x y)))
(println "not a poppler"))))]
(.addMouseListener tree (proxy [MouseAdapter] []
(mousePressed [me]
(println "Pressed check"))
(mouseReleased [me]
(println "Released check")
(check-for-pop me))))
(doto frame
(.setSize 400 400)
(.setLayout (MigLayout. "" "[fill, grow]" "[fill, grow]"))
(.add (default-scroll-pane tree))
(.setJMenuBar menu)
(.setDefaultCloseOperation (WindowConstants/EXIT_ON_CLOSE))
(.setVisible true))))
(def rt (Runtime/getRuntime))
(.addShutdownHook rt
(proxy [Thread] []
(run [] (println "goodbye")
(CommandUtil/exitProcess sid process client)
(CommandUtil/exitSession sid client))))
(SwingUtilities/invokeLater (partial window sys-caller))
(println "done")
|
[
{
"context": "son-id\n :person/name \"Bob\"\n :person/address {:db/i",
"end": 3015,
"score": 0.9996726512908936,
"start": 3012,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name \"Bob\"\n :person/a",
"end": 6061,
"score": 0.9998183250427246,
"start": 6058,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name \"Joe\"}\n ",
"end": 8086,
"score": 0.9996897578239441,
"start": 8083,
"tag": "NAME",
"value": "Joe"
},
{
"context": " :person/name \"Sam\"}\n ",
"end": 8434,
"score": 0.999849796295166,
"start": 8431,
"tag": "NAME",
"value": "Sam"
},
{
"context": " :person/name \"Sally\"}\n ",
"end": 8784,
"score": 0.9997506141662598,
"start": 8779,
"tag": "NAME",
"value": "Sally"
},
{
"context": " :person/name \"Dupe Sally\"}])]\n (assertions\n \"Leaves keywords alone",
"end": 9139,
"score": 0.9997115135192871,
"start": 9129,
"tag": "NAME",
"value": "Dupe Sally"
},
{
"context": " :person/name \"Joe\"}])\n {:strs [PERSON1]} tempids\n {:k",
"end": 10796,
"score": 0.9997668266296387,
"start": 10793,
"tag": "NAME",
"value": "Joe"
},
{
"context": " :person/name \"Bob\"}\n ",
"end": 10979,
"score": 0.9998552799224854,
"start": 10976,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name \"Mary\"}])\n {:strs [PERSON2]} tempids]\n (try\n ",
"end": 11203,
"score": 0.999767005443573,
"start": 11199,
"tag": "NAME",
"value": "Mary"
},
{
"context": "\n :person/name \"Joe\"}]})\n tx-id (->> tx2-entry :data (f",
"end": 12495,
"score": 0.9997378587722778,
"start": 12492,
"tag": "NAME",
"value": "Joe"
},
{
"context": " :person/name \"Joe\"}])\n {:strs [PERSON1]} tempids\n {:k",
"end": 14236,
"score": 0.999631941318512,
"start": 14233,
"tag": "NAME",
"value": "Joe"
},
{
"context": " :person/name \"Bob\"}\n ",
"end": 14419,
"score": 0.9998421669006348,
"start": 14416,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name \"Mary\"}])\n id->attr (cloning/id->attr (d/a",
"end": 14643,
"score": 0.9997396469116211,
"start": 14639,
"tag": "NAME",
"value": "Mary"
},
{
"context": " :person/name \"Joe\"}]})\n db (d/db target-co",
"end": 16706,
"score": 0.9995365142822266,
"start": 16703,
"tag": "NAME",
"value": "Joe"
},
{
"context": " (subvec txn 4 6) => [[:db/add NEW-PERSON1 \"75\" \"Bob\"]\n [:db/retract N",
"end": 18149,
"score": 0.999777615070343,
"start": 18146,
"tag": "NAME",
"value": "Bob"
},
{
"context": " [:db/retract NEW-PERSON1 \"75\" \"Joe\"]]\n \"Uses correct tmpid for new entiti",
"end": 18219,
"score": 0.999762773513794,
"start": 18216,
"tag": "NAME",
"value": "Joe"
},
{
"context": "ext-id)\n :person/name \"Bob\"})\n _ (d/transact conn {:tx-data",
"end": 19655,
"score": 0.9998036026954651,
"start": 19652,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name (str \"Bob \" n)}]}))\n\n (cloning/backup-segment! db-name",
"end": 22875,
"score": 0.9982585310935974,
"start": 22872,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name (str \"Bob \" n)}]}))\n\n (cloning/backup-segment! db-name",
"end": 25316,
"score": 0.9998171925544739,
"start": 25313,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :person/name (str \"Bob \" n)}]}))\n\n (cloning/backup! db-name conn st",
"end": 28170,
"score": 0.9996107220649719,
"start": 28167,
"tag": "NAME",
"value": "Bob"
},
{
"context": " [:person/name] [:person/id 1]) => {:person/name \"Bob 1\"}\n (d/pull new-db [:person/name] [:per",
"end": 28865,
"score": 0.9979484677314758,
"start": 28862,
"tag": "NAME",
"value": "Bob"
},
{
"context": ":person/name] [:person/id 100]) => {:person/name \"Bob 100\"}))\n\n (finally\n (d/delete-databas",
"end": 28949,
"score": 0.9992018342018127,
"start": 28946,
"tag": "NAME",
"value": "Bob"
}
] |
src/test/com/fulcrologic/datomic_cloud_backup/cloning_test.clj
|
fulcrologic/datomic-cloud-backup
| 16 |
(ns com.fulcrologic.datomic-cloud-backup.cloning-test
(:require
[datomic.client.api :as d]
[com.fulcrologic.datomic-cloud-backup.ram-stores :refer [new-ram-store]]
[com.fulcrologic.datomic-cloud-backup.protocols :as dcbp]
[com.fulcrologic.datomic-cloud-backup.cloning :as cloning]
[com.fulcrologic.datomic-cloud-backup.s3-backup-store :refer [new-s3-store aws-credentials?]]
[com.fulcrologic.datomic-cloud-backup.filesystem-backup-store :refer [new-filesystem-store]]
[fulcro-spec.core :refer [specification behavior component assertions => provided]]
[com.fulcrologic.datomic-cloud-backup.filesystem-backup-store :as fs]
[clojure.string :as str]
[taoensso.timbre :as log])
(:import (java.util UUID)
(java.nio.file Files)
(java.nio.file.attribute FileAttribute)
(java.io File)))
(defonce client (d/client {:server-type :dev-local
:storage-dir :mem
:system "test"}))
(defn backup! [dbname source-connection target-store]
(loop [n (cloning/backup-next-segment! dbname source-connection target-store 2)]
(when (pos? n)
(Thread/sleep 10)
(recur (cloning/backup-next-segment! dbname source-connection target-store 2)))))
(defn restore! [dbname target-conn db-store]
(while (= :restored-segment (cloning/restore-segment! dbname target-conn db-store {}))))
(defn clean-filesystem! [^File tmpdir]
(when (and (.exists tmpdir) (.isDirectory tmpdir) (str/starts-with? (.getAbsolutePath tmpdir) "/t"))
(doseq [backup-file (filter
(fn [^File nm] (str/ends-with? (.getName nm) ".nippy"))
(file-seq tmpdir))]
(.delete backup-file))))
(def sample-schema
[{:db/ident :transaction/reason
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :person/id
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :address/id
:db/valueType :db.type/uuid
:db/cardinality :db.cardinality/one}
{:db/ident :address/street
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :person/address
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one}])
(defn run-tests [dbname db-store]
(let [source-db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
person-id (UUID/randomUUID)
address-id (UUID/randomUUID)
txns [sample-schema
[[:db/add "BAD-DATOM" :person/address 4872362574]
[:db/add "datomic.tx" :transaction/reason "Because"]
{:db/id "BOB"
:person/id person-id
:person/name "Bob"
:person/address {:db/id "MAIN"
:address/id address-id
:address/street "123 Main"}}]]
_ (d/create-database client {:db-name source-db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name source-db-name})
target-conn (d/connect client {:db-name target-db-name})
{{:strs [BOB MAIN]} :tempids} (last (mapv (fn [txn]
(Thread/sleep 1)
(d/transact conn {:tx-data txn})) txns))]
;; Hack to make sure IDs don't align internally, so that less likely to get false success
(d/transact target-conn {:tx-data [{:db/ident :thing/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :other/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
[:db/add "datomic.tx" :db/txInstant #inst "1970-01-01T12:00"]]})
(d/transact target-conn {:tx-data [{:db/id "new-thing"
:thing/id 99}
[:db/add "datomic.tx" :db/txInstant #inst "1970-01-01T12:01"]]})
(try
(component "incremental backup"
(backup! dbname conn db-store)
(assertions
"Can back up the database in pieces"
(mapv
#(select-keys % #{:start-t :end-t})
(dcbp/saved-segment-info db-store dbname)) => [{:start-t 1 :end-t 2}
{:start-t 3 :end-t 4}
{:start-t 5 :end-t 6}
{:start-t 7 :end-t 7}]))
(component "incremental restore"
(restore! dbname target-conn db-store)
(let [restored-db (d/db target-conn)
person (d/pull restored-db [:person/id :person/name
::cloning/original-id
{:person/address [:address/id :address/street
::cloning/original-id]}]
[:person/id person-id])]
(assertions
"Can restore the database in pieces"
(dissoc person :db/id) => {:person/id person-id
::cloning/original-id BOB
:person/name "Bob"
:person/address {:address/id address-id
::cloning/original-id MAIN
:address/street "123 Main"}})))
(finally
(d/delete-database client {:db-name source-db-name})
(d/delete-database client {:db-name target-db-name})))))
(specification "Adding tracking schema"
(let [db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})]
(cloning/ensure-restore-schema! conn)
(let [db (d/db conn)]
(assertions
"Adds the proper starting location"
(-> (d/datoms db {:index :eavt
:components [::cloning/last-source-transaction ::cloning/last-source-transaction]})
first
:v)
=> 0))))
(specification "Resolving IDs"
(let [db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
person3-id (UUID/randomUUID)
person4-id (UUID/randomUUID)
_ (cloning/ensure-restore-schema! conn)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
_ (tx! conn sample-schema)
{{:strs [PERSON1 PERSON2]} :tempids} (tx! conn [{:db/id "PERSON1"
::cloning/original-id 99
:person/id person-id
:person/name "Joe"}
{:db/id "PERSON2"
::cloning/original-id 100
:person/id person2-id
:person/name "Sam"}
{:db/id "PERSON3"
::cloning/original-id 101
:person/id person3-id
:person/name "Sally"}
{:db/id "PERSON4"
::cloning/original-id 101
:person/id person4-id
:person/name "Dupe Sally"}])]
(assertions
"Leaves keywords alone"
(cloning/resolve-id {:db (d/db conn)} :x) => :x
"Rewrites transaction ID number to \"datomic.tx\""
(cloning/resolve-id {:db (d/db conn)
:tx-id 44} 44) => "datomic.tx"
"Can find original entities by ::original-id"
(cloning/resolve-id {:db (d/db conn)} 99) => PERSON1
(cloning/resolve-id {:db (d/db conn)} 100) => PERSON2
"Throws an exception if the original ID isn't unique"
(cloning/resolve-id {:db (d/db conn)} 101) =throws=> #"Two entities share the same original ID")))
(specification "Bookkeeping transaction"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name db-name})
target-conn (d/connect client {:db-name target-db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
schema-entry (tx! conn sample-schema)
{:keys [tempids] :as tx1-entry} (tx! conn [{:db/id "PERSON1"
:person/id person-id
:person/name "Joe"}])
{:strs [PERSON1]} tempids
{:keys [tempids] :as tx2-entry} (tx! conn [{:person/id person-id
:person/name "Bob"}
{:db/id "PERSON2"
:person/id person2-id
:person/name "Mary"}])
{:strs [PERSON2]} tempids]
(try
(cloning/ensure-restore-schema! target-conn)
(tx! target-conn [{:db/ident :boogers/mcgee
:db/cardinality :db.cardinality/one
:db/valueType :db.type/string}])
(let [db (d/db target-conn)
datoms (cloning/bookkeeping-txn {:db db} schema-entry)
{:keys [t]} schema-entry]
(assertions
"Adds a CAS operation to ensure the entry being restored in the correct one"
(first datoms) => [:db/cas ::cloning/last-source-transaction ::cloning/last-source-transaction 0 t]
"Adds original IDs to the schema attributes"
(every? (fn [[add tmpid k id]]
(and
(= add :db/add)
(string? tmpid)
(= k ::cloning/original-id)
(int? id))) (rest datoms)) => true)
(tx! target-conn sample-schema)
(let [_ (d/transact target-conn
{:tx-data
[{:db/id (str PERSON1)
::cloning/original-id PERSON1
:person/id person-id
:person/name "Joe"}]})
tx-id (->> tx2-entry :data (filter (fn [{:keys [v]}] (inst? v))) (map :e) (first))
db (d/db target-conn)
datoms (cloning/bookkeeping-txn {:db db} tx2-entry)]
(assertions
"Fixes tempids on the tx and new items"
(vec (rest datoms)) => [[:db/add "datomic.tx" ::cloning/original-id tx-id]
[:db/add (str PERSON2) ::cloning/original-id PERSON2]])))
(finally
(d/delete-database client {:db-name db-name})
(d/delete-database client {:db-name target-db-name})))))
;; Flaky test...it passes if run enough times, and fails for poor reasons. No time to rewrite
(specification "resolved-txn"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name db-name})
target-conn (d/connect client {:db-name target-db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
schema-entry (tx! conn sample-schema)
{:keys [tempids] :as tx1-entry} (tx! conn [{:db/id "PERSON1"
:person/id person-id
:person/name "Joe"}])
{:strs [PERSON1]} tempids
{:keys [tempids] :as tx2-entry} (tx! conn [{:person/id person-id
:person/name "Bob"}
{:db/id "PERSON2"
:person/id person2-id
:person/name "Mary"}])
id->attr (cloning/id->attr (d/as-of (d/db conn) #inst "2000-01-01"))
{:strs [PERSON2]} tempids]
(try
(cloning/ensure-restore-schema! target-conn)
(tx! target-conn [{:db/ident :boogers/mcgee
:db/cardinality :db.cardinality/one
:db/valueType :db.type/string}])
(let [db (d/db target-conn)
source-refs (cloning/all-refs (d/db conn))
original-tx-id (-> schema-entry :data first :tx)
txn (cloning/resolved-txn {:db db
:id->attr id->attr
:source-refs source-refs} schema-entry)
txn-set (set txn)]
(component "When dealing with early schema"
(assertions
"Adds original IDs to user schema attributes"
(contains? txn-set [:db/add "77" :com.fulcrologic.datomic-cloud-backup.cloning/original-id 77]) => true
"Rewrites the db id of the txn to datomic.tx"
(contains? txn-set [:db/add "datomic.tx" :com.fulcrologic.datomic-cloud-backup.cloning/original-id original-tx-id]) => true
"Rewrites the :db/id of the new items to strings that match the original ids"
(contains? txn-set [:db/add "74" :db/ident :person/id]) => true
"Uses the temp ids as the values for install attribute"
(contains? txn-set [:db/add :db.part/db :db.install/attribute "74"]) => true))
(tx! target-conn sample-schema)
(let [{{:strs [NEW-PERSON1]} :tempids} (d/transact target-conn
{:tx-data
[{:db/id "NEW-PERSON1"
::cloning/original-id PERSON1
:person/id person-id
:person/name "Joe"}]})
db (d/db target-conn)
source-refs (cloning/all-refs (d/db conn))
txn (cloning/resolved-txn {:db db
:id->attr id->attr
:source-refs source-refs} tx2-entry)
original-tx-id (-> tx2-entry :data first :tx)]
(assertions
"Includes the transaction sequence CAS"
(ffirst txn) => :db/cas
"Adds the original ID to the transaction"
(second txn) => [:db/add
"datomic.tx"
:com.fulcrologic.datomic-cloud-backup.cloning/original-id
original-tx-id]
"Adds original IDs to new entities"
(nth txn 2) => [:db/add
(str PERSON2)
:com.fulcrologic.datomic-cloud-backup.cloning/original-id
PERSON2]
"Includes the original transaction time"
(-> txn (nth 3) butlast) => [:db/add "datomic.tx" :db/txInstant]
"Uses real IDs for updating things that are in the database"
;; NOTE: The strings for attributes are because we are not doing the actual restore,
;; so it cannot find the original IDs
(subvec txn 4 6) => [[:db/add NEW-PERSON1 "75" "Bob"]
[:db/retract NEW-PERSON1 "75" "Joe"]]
"Uses correct tmpid for new entities"
(map second (subvec txn 6)) => [(str PERSON2) (str PERSON2)])))
(finally
(d/delete-database client {:db-name db-name})
(d/delete-database client {:db-name target-db-name})))))
(specification "Backup"
(component "Using Test Stores (RAM-Based)"
(run-tests :db1 (new-ram-store)))
(component "Using Filesystem"
(let [tmpdirfile (.toFile (Files/createTempDirectory "" (make-array FileAttribute 0)))
tempdir (.getAbsolutePath tmpdirfile)]
(run-tests :db1 (new-filesystem-store tempdir))
(clean-filesystem! tmpdirfile)))
(component "Using S3"
(if (and (aws-credentials?))
(let [dbname (keyword (gensym "test"))]
(run-tests dbname (new-s3-store "datomic-cloning-test-bucket")))
(assertions
"Resources not available. Test skipped"
true => true))))
(specification "Parallel backup"
(let [tmpdir (.toFile (Files/createTempDirectory "test" (make-array FileAttribute 0)))
db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
base-id (atom 0)
next-id (fn [] (UUID/fromString (format "ffffffff-ffff-ffff-ffff-%012d" (swap! base-id inc))))
make-person (fn [] {:person/id (next-id)
:person/name "Bob"})
_ (d/transact conn {:tx-data [{:db/ident :person/id
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]})
fs-store (fs/new-filesystem-store (.getAbsolutePath tmpdir))]
(try
(dotimes [n 1061]
(d/transact conn {:tx-data [(make-person)]}))
(let [segments (cloning/backup! db-name conn fs-store {:parallel? true
:txns-per-segment 100})
last-stored-t (-> segments last :end-t)
{final-data :data
final-t :t} (last (d/tx-range conn {:start 1061 :limit -1}))
final-saved-tx (last (:transactions (dcbp/load-transaction-group fs-store db-name 1000)))]
(assertions
"Backs up the correct number of segments"
(count segments) => 11
(:t final-saved-tx) => final-t
"Stops at the last actual transaction in the database"
last-stored-t => final-t))
(finally
(clean-filesystem! tmpdir)
(d/delete-database client {:db-name db-name})))))
(specification "backup-gaps"
(assertions
"Returns a sequence of gaps that are found in the provided database segments"
(cloning/backup-gaps [{:start-t 100
:end-t 105}
{:start-t 110
:end-t 118}
#_{:start-t 109
:end-t 130}
#_{:start-t 109
:end-t 145}
{:start-t 146
:end-t 163}])
=> [{:start-t 106 :end-t 110}
{:start-t 119 :end-t 146}]))
(specification "repair-backup!"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
tempdirfile (.toFile (Files/createTempDirectory "" (make-array FileAttribute 0)))
tempdir (.getAbsolutePath tempdirfile)
store (new-filesystem-store tempdir)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 1000]
(d/transact conn {:tx-data [{:person/id n
:person/name (str "Bob " n)}]}))
(cloning/backup-segment! db-name conn store 1 300)
(cloning/backup-segment! db-name conn store 330 565)
(cloning/backup-segment! db-name conn store 575 1000)
(cloning/backup-segment! db-name conn store 1000 1100)
(assertions
"When there is a gap in the backup"
(count (cloning/backup-gaps (dcbp/saved-segment-info store db-name))) => 2)
(cloning/repair-backup! db-name conn store)
(assertions
"Creates the missing file(s)"
(count (cloning/backup-gaps (dcbp/saved-segment-info store db-name))) => 0)
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})]
(while (= :restored-segment (cloning/restore-segment! db-name target-conn store {}))
(cloning/restore-segment! db-name target-conn store {}))
(let [db (d/db target-conn)
cnt (ffirst (try (d/q '[:find (count ?p) :where [?p :person/name]] db)
(catch Exception e nil)))]
(assertions
"The repaired backup contains all of the original entities"
cnt => 1000)))
(finally
(clean-filesystem! tempdirfile)
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
(specification "Resuming an Interrupted Restore"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
store (new-ram-store)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 101]
(Thread/sleep 1) ; important. if too fast then tx time doesn't change and we get a false success on test
(d/transact conn {:tx-data [{:person/id n
:person/name (str "Bob " n)}]}))
(cloning/backup-segment! db-name conn store 1 10)
(cloning/backup-segment! db-name conn store 10 20)
(cloning/backup-segment! db-name conn store 20 (:t (d/db conn)))
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})]
(assertions
"Restore :restored-segment when it restores some data"
(cloning/restore-segment! db-name target-conn store {}) => :restored-segment)
(let [group (dcbp/load-transaction-group store db-name 10)
real-load-txns cloning/-load-transactions]
(provided "The restore restores only PART of a segment"
;; The first time we simulate a failure midway through restore
(cloning/-load-transactions s n start) =1x=> (update group :transactions subvec 0 5)
;; The rest of the time we do what we are asked
(cloning/-load-transactions s n start) => (real-load-txns s n start)
;; First attempt on this segment only gets half of them
(cloning/restore-segment! db-name target-conn store {})
;; Retry should get the rest, an complain about the duplicates
(cloning/restore-segment! db-name target-conn store {})
;; Load the remainder of the database
(cloning/restore-segment! db-name target-conn store {})
(assertions
"Resuming succeeds"
(ffirst
(d/q '[:find (count ?id)
:where
[?id :person/id]] (d/db target-conn))) => 100))))
(finally
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
(specification "restore!! for fast restores"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
store (new-ram-store)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 101]
(Thread/sleep 1) ; important. if too fast then tx time doesn't change and we get a false success on test
(d/transact conn {:tx-data [{:person/id n
:person/name (str "Bob " n)}]}))
(cloning/backup! db-name conn store {:txns-per-segment 10
:parallel? false})
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})
result (cloning/restore!! db-name target-conn store {})
new-db (d/db target-conn)]
(assertions
"Returns a result to indicate it is done"
result => {:result "No more segments to restore. Was looking for the next start: 108"}
"Restores the expected data"
(d/pull new-db [:person/name] [:person/id 1]) => {:person/name "Bob 1"}
(d/pull new-db [:person/name] [:person/id 100]) => {:person/name "Bob 100"}))
(finally
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
|
83487
|
(ns com.fulcrologic.datomic-cloud-backup.cloning-test
(:require
[datomic.client.api :as d]
[com.fulcrologic.datomic-cloud-backup.ram-stores :refer [new-ram-store]]
[com.fulcrologic.datomic-cloud-backup.protocols :as dcbp]
[com.fulcrologic.datomic-cloud-backup.cloning :as cloning]
[com.fulcrologic.datomic-cloud-backup.s3-backup-store :refer [new-s3-store aws-credentials?]]
[com.fulcrologic.datomic-cloud-backup.filesystem-backup-store :refer [new-filesystem-store]]
[fulcro-spec.core :refer [specification behavior component assertions => provided]]
[com.fulcrologic.datomic-cloud-backup.filesystem-backup-store :as fs]
[clojure.string :as str]
[taoensso.timbre :as log])
(:import (java.util UUID)
(java.nio.file Files)
(java.nio.file.attribute FileAttribute)
(java.io File)))
(defonce client (d/client {:server-type :dev-local
:storage-dir :mem
:system "test"}))
(defn backup! [dbname source-connection target-store]
(loop [n (cloning/backup-next-segment! dbname source-connection target-store 2)]
(when (pos? n)
(Thread/sleep 10)
(recur (cloning/backup-next-segment! dbname source-connection target-store 2)))))
(defn restore! [dbname target-conn db-store]
(while (= :restored-segment (cloning/restore-segment! dbname target-conn db-store {}))))
(defn clean-filesystem! [^File tmpdir]
(when (and (.exists tmpdir) (.isDirectory tmpdir) (str/starts-with? (.getAbsolutePath tmpdir) "/t"))
(doseq [backup-file (filter
(fn [^File nm] (str/ends-with? (.getName nm) ".nippy"))
(file-seq tmpdir))]
(.delete backup-file))))
(def sample-schema
[{:db/ident :transaction/reason
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :person/id
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :address/id
:db/valueType :db.type/uuid
:db/cardinality :db.cardinality/one}
{:db/ident :address/street
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :person/address
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one}])
(defn run-tests [dbname db-store]
(let [source-db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
person-id (UUID/randomUUID)
address-id (UUID/randomUUID)
txns [sample-schema
[[:db/add "BAD-DATOM" :person/address 4872362574]
[:db/add "datomic.tx" :transaction/reason "Because"]
{:db/id "BOB"
:person/id person-id
:person/name "<NAME>"
:person/address {:db/id "MAIN"
:address/id address-id
:address/street "123 Main"}}]]
_ (d/create-database client {:db-name source-db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name source-db-name})
target-conn (d/connect client {:db-name target-db-name})
{{:strs [BOB MAIN]} :tempids} (last (mapv (fn [txn]
(Thread/sleep 1)
(d/transact conn {:tx-data txn})) txns))]
;; Hack to make sure IDs don't align internally, so that less likely to get false success
(d/transact target-conn {:tx-data [{:db/ident :thing/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :other/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
[:db/add "datomic.tx" :db/txInstant #inst "1970-01-01T12:00"]]})
(d/transact target-conn {:tx-data [{:db/id "new-thing"
:thing/id 99}
[:db/add "datomic.tx" :db/txInstant #inst "1970-01-01T12:01"]]})
(try
(component "incremental backup"
(backup! dbname conn db-store)
(assertions
"Can back up the database in pieces"
(mapv
#(select-keys % #{:start-t :end-t})
(dcbp/saved-segment-info db-store dbname)) => [{:start-t 1 :end-t 2}
{:start-t 3 :end-t 4}
{:start-t 5 :end-t 6}
{:start-t 7 :end-t 7}]))
(component "incremental restore"
(restore! dbname target-conn db-store)
(let [restored-db (d/db target-conn)
person (d/pull restored-db [:person/id :person/name
::cloning/original-id
{:person/address [:address/id :address/street
::cloning/original-id]}]
[:person/id person-id])]
(assertions
"Can restore the database in pieces"
(dissoc person :db/id) => {:person/id person-id
::cloning/original-id BOB
:person/name "<NAME>"
:person/address {:address/id address-id
::cloning/original-id MAIN
:address/street "123 Main"}})))
(finally
(d/delete-database client {:db-name source-db-name})
(d/delete-database client {:db-name target-db-name})))))
(specification "Adding tracking schema"
(let [db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})]
(cloning/ensure-restore-schema! conn)
(let [db (d/db conn)]
(assertions
"Adds the proper starting location"
(-> (d/datoms db {:index :eavt
:components [::cloning/last-source-transaction ::cloning/last-source-transaction]})
first
:v)
=> 0))))
(specification "Resolving IDs"
(let [db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
person3-id (UUID/randomUUID)
person4-id (UUID/randomUUID)
_ (cloning/ensure-restore-schema! conn)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
_ (tx! conn sample-schema)
{{:strs [PERSON1 PERSON2]} :tempids} (tx! conn [{:db/id "PERSON1"
::cloning/original-id 99
:person/id person-id
:person/name "<NAME>"}
{:db/id "PERSON2"
::cloning/original-id 100
:person/id person2-id
:person/name "<NAME>"}
{:db/id "PERSON3"
::cloning/original-id 101
:person/id person3-id
:person/name "<NAME>"}
{:db/id "PERSON4"
::cloning/original-id 101
:person/id person4-id
:person/name "<NAME>"}])]
(assertions
"Leaves keywords alone"
(cloning/resolve-id {:db (d/db conn)} :x) => :x
"Rewrites transaction ID number to \"datomic.tx\""
(cloning/resolve-id {:db (d/db conn)
:tx-id 44} 44) => "datomic.tx"
"Can find original entities by ::original-id"
(cloning/resolve-id {:db (d/db conn)} 99) => PERSON1
(cloning/resolve-id {:db (d/db conn)} 100) => PERSON2
"Throws an exception if the original ID isn't unique"
(cloning/resolve-id {:db (d/db conn)} 101) =throws=> #"Two entities share the same original ID")))
(specification "Bookkeeping transaction"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name db-name})
target-conn (d/connect client {:db-name target-db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
schema-entry (tx! conn sample-schema)
{:keys [tempids] :as tx1-entry} (tx! conn [{:db/id "PERSON1"
:person/id person-id
:person/name "<NAME>"}])
{:strs [PERSON1]} tempids
{:keys [tempids] :as tx2-entry} (tx! conn [{:person/id person-id
:person/name "<NAME>"}
{:db/id "PERSON2"
:person/id person2-id
:person/name "<NAME>"}])
{:strs [PERSON2]} tempids]
(try
(cloning/ensure-restore-schema! target-conn)
(tx! target-conn [{:db/ident :boogers/mcgee
:db/cardinality :db.cardinality/one
:db/valueType :db.type/string}])
(let [db (d/db target-conn)
datoms (cloning/bookkeeping-txn {:db db} schema-entry)
{:keys [t]} schema-entry]
(assertions
"Adds a CAS operation to ensure the entry being restored in the correct one"
(first datoms) => [:db/cas ::cloning/last-source-transaction ::cloning/last-source-transaction 0 t]
"Adds original IDs to the schema attributes"
(every? (fn [[add tmpid k id]]
(and
(= add :db/add)
(string? tmpid)
(= k ::cloning/original-id)
(int? id))) (rest datoms)) => true)
(tx! target-conn sample-schema)
(let [_ (d/transact target-conn
{:tx-data
[{:db/id (str PERSON1)
::cloning/original-id PERSON1
:person/id person-id
:person/name "<NAME>"}]})
tx-id (->> tx2-entry :data (filter (fn [{:keys [v]}] (inst? v))) (map :e) (first))
db (d/db target-conn)
datoms (cloning/bookkeeping-txn {:db db} tx2-entry)]
(assertions
"Fixes tempids on the tx and new items"
(vec (rest datoms)) => [[:db/add "datomic.tx" ::cloning/original-id tx-id]
[:db/add (str PERSON2) ::cloning/original-id PERSON2]])))
(finally
(d/delete-database client {:db-name db-name})
(d/delete-database client {:db-name target-db-name})))))
;; Flaky test...it passes if run enough times, and fails for poor reasons. No time to rewrite
(specification "resolved-txn"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name db-name})
target-conn (d/connect client {:db-name target-db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
schema-entry (tx! conn sample-schema)
{:keys [tempids] :as tx1-entry} (tx! conn [{:db/id "PERSON1"
:person/id person-id
:person/name "<NAME>"}])
{:strs [PERSON1]} tempids
{:keys [tempids] :as tx2-entry} (tx! conn [{:person/id person-id
:person/name "<NAME>"}
{:db/id "PERSON2"
:person/id person2-id
:person/name "<NAME>"}])
id->attr (cloning/id->attr (d/as-of (d/db conn) #inst "2000-01-01"))
{:strs [PERSON2]} tempids]
(try
(cloning/ensure-restore-schema! target-conn)
(tx! target-conn [{:db/ident :boogers/mcgee
:db/cardinality :db.cardinality/one
:db/valueType :db.type/string}])
(let [db (d/db target-conn)
source-refs (cloning/all-refs (d/db conn))
original-tx-id (-> schema-entry :data first :tx)
txn (cloning/resolved-txn {:db db
:id->attr id->attr
:source-refs source-refs} schema-entry)
txn-set (set txn)]
(component "When dealing with early schema"
(assertions
"Adds original IDs to user schema attributes"
(contains? txn-set [:db/add "77" :com.fulcrologic.datomic-cloud-backup.cloning/original-id 77]) => true
"Rewrites the db id of the txn to datomic.tx"
(contains? txn-set [:db/add "datomic.tx" :com.fulcrologic.datomic-cloud-backup.cloning/original-id original-tx-id]) => true
"Rewrites the :db/id of the new items to strings that match the original ids"
(contains? txn-set [:db/add "74" :db/ident :person/id]) => true
"Uses the temp ids as the values for install attribute"
(contains? txn-set [:db/add :db.part/db :db.install/attribute "74"]) => true))
(tx! target-conn sample-schema)
(let [{{:strs [NEW-PERSON1]} :tempids} (d/transact target-conn
{:tx-data
[{:db/id "NEW-PERSON1"
::cloning/original-id PERSON1
:person/id person-id
:person/name "<NAME>"}]})
db (d/db target-conn)
source-refs (cloning/all-refs (d/db conn))
txn (cloning/resolved-txn {:db db
:id->attr id->attr
:source-refs source-refs} tx2-entry)
original-tx-id (-> tx2-entry :data first :tx)]
(assertions
"Includes the transaction sequence CAS"
(ffirst txn) => :db/cas
"Adds the original ID to the transaction"
(second txn) => [:db/add
"datomic.tx"
:com.fulcrologic.datomic-cloud-backup.cloning/original-id
original-tx-id]
"Adds original IDs to new entities"
(nth txn 2) => [:db/add
(str PERSON2)
:com.fulcrologic.datomic-cloud-backup.cloning/original-id
PERSON2]
"Includes the original transaction time"
(-> txn (nth 3) butlast) => [:db/add "datomic.tx" :db/txInstant]
"Uses real IDs for updating things that are in the database"
;; NOTE: The strings for attributes are because we are not doing the actual restore,
;; so it cannot find the original IDs
(subvec txn 4 6) => [[:db/add NEW-PERSON1 "75" "<NAME>"]
[:db/retract NEW-PERSON1 "75" "<NAME>"]]
"Uses correct tmpid for new entities"
(map second (subvec txn 6)) => [(str PERSON2) (str PERSON2)])))
(finally
(d/delete-database client {:db-name db-name})
(d/delete-database client {:db-name target-db-name})))))
(specification "Backup"
(component "Using Test Stores (RAM-Based)"
(run-tests :db1 (new-ram-store)))
(component "Using Filesystem"
(let [tmpdirfile (.toFile (Files/createTempDirectory "" (make-array FileAttribute 0)))
tempdir (.getAbsolutePath tmpdirfile)]
(run-tests :db1 (new-filesystem-store tempdir))
(clean-filesystem! tmpdirfile)))
(component "Using S3"
(if (and (aws-credentials?))
(let [dbname (keyword (gensym "test"))]
(run-tests dbname (new-s3-store "datomic-cloning-test-bucket")))
(assertions
"Resources not available. Test skipped"
true => true))))
(specification "Parallel backup"
(let [tmpdir (.toFile (Files/createTempDirectory "test" (make-array FileAttribute 0)))
db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
base-id (atom 0)
next-id (fn [] (UUID/fromString (format "ffffffff-ffff-ffff-ffff-%012d" (swap! base-id inc))))
make-person (fn [] {:person/id (next-id)
:person/name "<NAME>"})
_ (d/transact conn {:tx-data [{:db/ident :person/id
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]})
fs-store (fs/new-filesystem-store (.getAbsolutePath tmpdir))]
(try
(dotimes [n 1061]
(d/transact conn {:tx-data [(make-person)]}))
(let [segments (cloning/backup! db-name conn fs-store {:parallel? true
:txns-per-segment 100})
last-stored-t (-> segments last :end-t)
{final-data :data
final-t :t} (last (d/tx-range conn {:start 1061 :limit -1}))
final-saved-tx (last (:transactions (dcbp/load-transaction-group fs-store db-name 1000)))]
(assertions
"Backs up the correct number of segments"
(count segments) => 11
(:t final-saved-tx) => final-t
"Stops at the last actual transaction in the database"
last-stored-t => final-t))
(finally
(clean-filesystem! tmpdir)
(d/delete-database client {:db-name db-name})))))
(specification "backup-gaps"
(assertions
"Returns a sequence of gaps that are found in the provided database segments"
(cloning/backup-gaps [{:start-t 100
:end-t 105}
{:start-t 110
:end-t 118}
#_{:start-t 109
:end-t 130}
#_{:start-t 109
:end-t 145}
{:start-t 146
:end-t 163}])
=> [{:start-t 106 :end-t 110}
{:start-t 119 :end-t 146}]))
(specification "repair-backup!"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
tempdirfile (.toFile (Files/createTempDirectory "" (make-array FileAttribute 0)))
tempdir (.getAbsolutePath tempdirfile)
store (new-filesystem-store tempdir)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 1000]
(d/transact conn {:tx-data [{:person/id n
:person/name (str "<NAME> " n)}]}))
(cloning/backup-segment! db-name conn store 1 300)
(cloning/backup-segment! db-name conn store 330 565)
(cloning/backup-segment! db-name conn store 575 1000)
(cloning/backup-segment! db-name conn store 1000 1100)
(assertions
"When there is a gap in the backup"
(count (cloning/backup-gaps (dcbp/saved-segment-info store db-name))) => 2)
(cloning/repair-backup! db-name conn store)
(assertions
"Creates the missing file(s)"
(count (cloning/backup-gaps (dcbp/saved-segment-info store db-name))) => 0)
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})]
(while (= :restored-segment (cloning/restore-segment! db-name target-conn store {}))
(cloning/restore-segment! db-name target-conn store {}))
(let [db (d/db target-conn)
cnt (ffirst (try (d/q '[:find (count ?p) :where [?p :person/name]] db)
(catch Exception e nil)))]
(assertions
"The repaired backup contains all of the original entities"
cnt => 1000)))
(finally
(clean-filesystem! tempdirfile)
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
(specification "Resuming an Interrupted Restore"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
store (new-ram-store)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 101]
(Thread/sleep 1) ; important. if too fast then tx time doesn't change and we get a false success on test
(d/transact conn {:tx-data [{:person/id n
:person/name (str "<NAME> " n)}]}))
(cloning/backup-segment! db-name conn store 1 10)
(cloning/backup-segment! db-name conn store 10 20)
(cloning/backup-segment! db-name conn store 20 (:t (d/db conn)))
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})]
(assertions
"Restore :restored-segment when it restores some data"
(cloning/restore-segment! db-name target-conn store {}) => :restored-segment)
(let [group (dcbp/load-transaction-group store db-name 10)
real-load-txns cloning/-load-transactions]
(provided "The restore restores only PART of a segment"
;; The first time we simulate a failure midway through restore
(cloning/-load-transactions s n start) =1x=> (update group :transactions subvec 0 5)
;; The rest of the time we do what we are asked
(cloning/-load-transactions s n start) => (real-load-txns s n start)
;; First attempt on this segment only gets half of them
(cloning/restore-segment! db-name target-conn store {})
;; Retry should get the rest, an complain about the duplicates
(cloning/restore-segment! db-name target-conn store {})
;; Load the remainder of the database
(cloning/restore-segment! db-name target-conn store {})
(assertions
"Resuming succeeds"
(ffirst
(d/q '[:find (count ?id)
:where
[?id :person/id]] (d/db target-conn))) => 100))))
(finally
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
(specification "restore!! for fast restores"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
store (new-ram-store)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 101]
(Thread/sleep 1) ; important. if too fast then tx time doesn't change and we get a false success on test
(d/transact conn {:tx-data [{:person/id n
:person/name (str "<NAME> " n)}]}))
(cloning/backup! db-name conn store {:txns-per-segment 10
:parallel? false})
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})
result (cloning/restore!! db-name target-conn store {})
new-db (d/db target-conn)]
(assertions
"Returns a result to indicate it is done"
result => {:result "No more segments to restore. Was looking for the next start: 108"}
"Restores the expected data"
(d/pull new-db [:person/name] [:person/id 1]) => {:person/name "<NAME> 1"}
(d/pull new-db [:person/name] [:person/id 100]) => {:person/name "<NAME> 100"}))
(finally
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
| true |
(ns com.fulcrologic.datomic-cloud-backup.cloning-test
(:require
[datomic.client.api :as d]
[com.fulcrologic.datomic-cloud-backup.ram-stores :refer [new-ram-store]]
[com.fulcrologic.datomic-cloud-backup.protocols :as dcbp]
[com.fulcrologic.datomic-cloud-backup.cloning :as cloning]
[com.fulcrologic.datomic-cloud-backup.s3-backup-store :refer [new-s3-store aws-credentials?]]
[com.fulcrologic.datomic-cloud-backup.filesystem-backup-store :refer [new-filesystem-store]]
[fulcro-spec.core :refer [specification behavior component assertions => provided]]
[com.fulcrologic.datomic-cloud-backup.filesystem-backup-store :as fs]
[clojure.string :as str]
[taoensso.timbre :as log])
(:import (java.util UUID)
(java.nio.file Files)
(java.nio.file.attribute FileAttribute)
(java.io File)))
(defonce client (d/client {:server-type :dev-local
:storage-dir :mem
:system "test"}))
(defn backup! [dbname source-connection target-store]
(loop [n (cloning/backup-next-segment! dbname source-connection target-store 2)]
(when (pos? n)
(Thread/sleep 10)
(recur (cloning/backup-next-segment! dbname source-connection target-store 2)))))
(defn restore! [dbname target-conn db-store]
(while (= :restored-segment (cloning/restore-segment! dbname target-conn db-store {}))))
(defn clean-filesystem! [^File tmpdir]
(when (and (.exists tmpdir) (.isDirectory tmpdir) (str/starts-with? (.getAbsolutePath tmpdir) "/t"))
(doseq [backup-file (filter
(fn [^File nm] (str/ends-with? (.getName nm) ".nippy"))
(file-seq tmpdir))]
(.delete backup-file))))
(def sample-schema
[{:db/ident :transaction/reason
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :person/id
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :address/id
:db/valueType :db.type/uuid
:db/cardinality :db.cardinality/one}
{:db/ident :address/street
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :person/address
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one}])
(defn run-tests [dbname db-store]
(let [source-db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
person-id (UUID/randomUUID)
address-id (UUID/randomUUID)
txns [sample-schema
[[:db/add "BAD-DATOM" :person/address 4872362574]
[:db/add "datomic.tx" :transaction/reason "Because"]
{:db/id "BOB"
:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"
:person/address {:db/id "MAIN"
:address/id address-id
:address/street "123 Main"}}]]
_ (d/create-database client {:db-name source-db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name source-db-name})
target-conn (d/connect client {:db-name target-db-name})
{{:strs [BOB MAIN]} :tempids} (last (mapv (fn [txn]
(Thread/sleep 1)
(d/transact conn {:tx-data txn})) txns))]
;; Hack to make sure IDs don't align internally, so that less likely to get false success
(d/transact target-conn {:tx-data [{:db/ident :thing/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :other/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
[:db/add "datomic.tx" :db/txInstant #inst "1970-01-01T12:00"]]})
(d/transact target-conn {:tx-data [{:db/id "new-thing"
:thing/id 99}
[:db/add "datomic.tx" :db/txInstant #inst "1970-01-01T12:01"]]})
(try
(component "incremental backup"
(backup! dbname conn db-store)
(assertions
"Can back up the database in pieces"
(mapv
#(select-keys % #{:start-t :end-t})
(dcbp/saved-segment-info db-store dbname)) => [{:start-t 1 :end-t 2}
{:start-t 3 :end-t 4}
{:start-t 5 :end-t 6}
{:start-t 7 :end-t 7}]))
(component "incremental restore"
(restore! dbname target-conn db-store)
(let [restored-db (d/db target-conn)
person (d/pull restored-db [:person/id :person/name
::cloning/original-id
{:person/address [:address/id :address/street
::cloning/original-id]}]
[:person/id person-id])]
(assertions
"Can restore the database in pieces"
(dissoc person :db/id) => {:person/id person-id
::cloning/original-id BOB
:person/name "PI:NAME:<NAME>END_PI"
:person/address {:address/id address-id
::cloning/original-id MAIN
:address/street "123 Main"}})))
(finally
(d/delete-database client {:db-name source-db-name})
(d/delete-database client {:db-name target-db-name})))))
(specification "Adding tracking schema"
(let [db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})]
(cloning/ensure-restore-schema! conn)
(let [db (d/db conn)]
(assertions
"Adds the proper starting location"
(-> (d/datoms db {:index :eavt
:components [::cloning/last-source-transaction ::cloning/last-source-transaction]})
first
:v)
=> 0))))
(specification "Resolving IDs"
(let [db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
person3-id (UUID/randomUUID)
person4-id (UUID/randomUUID)
_ (cloning/ensure-restore-schema! conn)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
_ (tx! conn sample-schema)
{{:strs [PERSON1 PERSON2]} :tempids} (tx! conn [{:db/id "PERSON1"
::cloning/original-id 99
:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id "PERSON2"
::cloning/original-id 100
:person/id person2-id
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id "PERSON3"
::cloning/original-id 101
:person/id person3-id
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id "PERSON4"
::cloning/original-id 101
:person/id person4-id
:person/name "PI:NAME:<NAME>END_PI"}])]
(assertions
"Leaves keywords alone"
(cloning/resolve-id {:db (d/db conn)} :x) => :x
"Rewrites transaction ID number to \"datomic.tx\""
(cloning/resolve-id {:db (d/db conn)
:tx-id 44} 44) => "datomic.tx"
"Can find original entities by ::original-id"
(cloning/resolve-id {:db (d/db conn)} 99) => PERSON1
(cloning/resolve-id {:db (d/db conn)} 100) => PERSON2
"Throws an exception if the original ID isn't unique"
(cloning/resolve-id {:db (d/db conn)} 101) =throws=> #"Two entities share the same original ID")))
(specification "Bookkeeping transaction"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name db-name})
target-conn (d/connect client {:db-name target-db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
schema-entry (tx! conn sample-schema)
{:keys [tempids] :as tx1-entry} (tx! conn [{:db/id "PERSON1"
:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}])
{:strs [PERSON1]} tempids
{:keys [tempids] :as tx2-entry} (tx! conn [{:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id "PERSON2"
:person/id person2-id
:person/name "PI:NAME:<NAME>END_PI"}])
{:strs [PERSON2]} tempids]
(try
(cloning/ensure-restore-schema! target-conn)
(tx! target-conn [{:db/ident :boogers/mcgee
:db/cardinality :db.cardinality/one
:db/valueType :db.type/string}])
(let [db (d/db target-conn)
datoms (cloning/bookkeeping-txn {:db db} schema-entry)
{:keys [t]} schema-entry]
(assertions
"Adds a CAS operation to ensure the entry being restored in the correct one"
(first datoms) => [:db/cas ::cloning/last-source-transaction ::cloning/last-source-transaction 0 t]
"Adds original IDs to the schema attributes"
(every? (fn [[add tmpid k id]]
(and
(= add :db/add)
(string? tmpid)
(= k ::cloning/original-id)
(int? id))) (rest datoms)) => true)
(tx! target-conn sample-schema)
(let [_ (d/transact target-conn
{:tx-data
[{:db/id (str PERSON1)
::cloning/original-id PERSON1
:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}]})
tx-id (->> tx2-entry :data (filter (fn [{:keys [v]}] (inst? v))) (map :e) (first))
db (d/db target-conn)
datoms (cloning/bookkeeping-txn {:db db} tx2-entry)]
(assertions
"Fixes tempids on the tx and new items"
(vec (rest datoms)) => [[:db/add "datomic.tx" ::cloning/original-id tx-id]
[:db/add (str PERSON2) ::cloning/original-id PERSON2]])))
(finally
(d/delete-database client {:db-name db-name})
(d/delete-database client {:db-name target-db-name})))))
;; Flaky test...it passes if run enough times, and fails for poor reasons. No time to rewrite
(specification "resolved-txn"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
_ (d/create-database client {:db-name target-db-name})
conn (d/connect client {:db-name db-name})
target-conn (d/connect client {:db-name target-db-name})
person-id (UUID/randomUUID)
person2-id (UUID/randomUUID)
tx! (fn [c tx] (as-> (d/transact c {:tx-data tx}) $
(assoc {}
:data (:tx-data $)
:tempids (:tempids $)
:t (dec (:t (d/db c))))))
schema-entry (tx! conn sample-schema)
{:keys [tempids] :as tx1-entry} (tx! conn [{:db/id "PERSON1"
:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}])
{:strs [PERSON1]} tempids
{:keys [tempids] :as tx2-entry} (tx! conn [{:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id "PERSON2"
:person/id person2-id
:person/name "PI:NAME:<NAME>END_PI"}])
id->attr (cloning/id->attr (d/as-of (d/db conn) #inst "2000-01-01"))
{:strs [PERSON2]} tempids]
(try
(cloning/ensure-restore-schema! target-conn)
(tx! target-conn [{:db/ident :boogers/mcgee
:db/cardinality :db.cardinality/one
:db/valueType :db.type/string}])
(let [db (d/db target-conn)
source-refs (cloning/all-refs (d/db conn))
original-tx-id (-> schema-entry :data first :tx)
txn (cloning/resolved-txn {:db db
:id->attr id->attr
:source-refs source-refs} schema-entry)
txn-set (set txn)]
(component "When dealing with early schema"
(assertions
"Adds original IDs to user schema attributes"
(contains? txn-set [:db/add "77" :com.fulcrologic.datomic-cloud-backup.cloning/original-id 77]) => true
"Rewrites the db id of the txn to datomic.tx"
(contains? txn-set [:db/add "datomic.tx" :com.fulcrologic.datomic-cloud-backup.cloning/original-id original-tx-id]) => true
"Rewrites the :db/id of the new items to strings that match the original ids"
(contains? txn-set [:db/add "74" :db/ident :person/id]) => true
"Uses the temp ids as the values for install attribute"
(contains? txn-set [:db/add :db.part/db :db.install/attribute "74"]) => true))
(tx! target-conn sample-schema)
(let [{{:strs [NEW-PERSON1]} :tempids} (d/transact target-conn
{:tx-data
[{:db/id "NEW-PERSON1"
::cloning/original-id PERSON1
:person/id person-id
:person/name "PI:NAME:<NAME>END_PI"}]})
db (d/db target-conn)
source-refs (cloning/all-refs (d/db conn))
txn (cloning/resolved-txn {:db db
:id->attr id->attr
:source-refs source-refs} tx2-entry)
original-tx-id (-> tx2-entry :data first :tx)]
(assertions
"Includes the transaction sequence CAS"
(ffirst txn) => :db/cas
"Adds the original ID to the transaction"
(second txn) => [:db/add
"datomic.tx"
:com.fulcrologic.datomic-cloud-backup.cloning/original-id
original-tx-id]
"Adds original IDs to new entities"
(nth txn 2) => [:db/add
(str PERSON2)
:com.fulcrologic.datomic-cloud-backup.cloning/original-id
PERSON2]
"Includes the original transaction time"
(-> txn (nth 3) butlast) => [:db/add "datomic.tx" :db/txInstant]
"Uses real IDs for updating things that are in the database"
;; NOTE: The strings for attributes are because we are not doing the actual restore,
;; so it cannot find the original IDs
(subvec txn 4 6) => [[:db/add NEW-PERSON1 "75" "PI:NAME:<NAME>END_PI"]
[:db/retract NEW-PERSON1 "75" "PI:NAME:<NAME>END_PI"]]
"Uses correct tmpid for new entities"
(map second (subvec txn 6)) => [(str PERSON2) (str PERSON2)])))
(finally
(d/delete-database client {:db-name db-name})
(d/delete-database client {:db-name target-db-name})))))
(specification "Backup"
(component "Using Test Stores (RAM-Based)"
(run-tests :db1 (new-ram-store)))
(component "Using Filesystem"
(let [tmpdirfile (.toFile (Files/createTempDirectory "" (make-array FileAttribute 0)))
tempdir (.getAbsolutePath tmpdirfile)]
(run-tests :db1 (new-filesystem-store tempdir))
(clean-filesystem! tmpdirfile)))
(component "Using S3"
(if (and (aws-credentials?))
(let [dbname (keyword (gensym "test"))]
(run-tests dbname (new-s3-store "datomic-cloning-test-bucket")))
(assertions
"Resources not available. Test skipped"
true => true))))
(specification "Parallel backup"
(let [tmpdir (.toFile (Files/createTempDirectory "test" (make-array FileAttribute 0)))
db-name (keyword (gensym "db"))
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
base-id (atom 0)
next-id (fn [] (UUID/fromString (format "ffffffff-ffff-ffff-ffff-%012d" (swap! base-id inc))))
make-person (fn [] {:person/id (next-id)
:person/name "PI:NAME:<NAME>END_PI"})
_ (d/transact conn {:tx-data [{:db/ident :person/id
:db/valueType :db.type/uuid
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]})
fs-store (fs/new-filesystem-store (.getAbsolutePath tmpdir))]
(try
(dotimes [n 1061]
(d/transact conn {:tx-data [(make-person)]}))
(let [segments (cloning/backup! db-name conn fs-store {:parallel? true
:txns-per-segment 100})
last-stored-t (-> segments last :end-t)
{final-data :data
final-t :t} (last (d/tx-range conn {:start 1061 :limit -1}))
final-saved-tx (last (:transactions (dcbp/load-transaction-group fs-store db-name 1000)))]
(assertions
"Backs up the correct number of segments"
(count segments) => 11
(:t final-saved-tx) => final-t
"Stops at the last actual transaction in the database"
last-stored-t => final-t))
(finally
(clean-filesystem! tmpdir)
(d/delete-database client {:db-name db-name})))))
(specification "backup-gaps"
(assertions
"Returns a sequence of gaps that are found in the provided database segments"
(cloning/backup-gaps [{:start-t 100
:end-t 105}
{:start-t 110
:end-t 118}
#_{:start-t 109
:end-t 130}
#_{:start-t 109
:end-t 145}
{:start-t 146
:end-t 163}])
=> [{:start-t 106 :end-t 110}
{:start-t 119 :end-t 146}]))
(specification "repair-backup!"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
tempdirfile (.toFile (Files/createTempDirectory "" (make-array FileAttribute 0)))
tempdir (.getAbsolutePath tempdirfile)
store (new-filesystem-store tempdir)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 1000]
(d/transact conn {:tx-data [{:person/id n
:person/name (str "PI:NAME:<NAME>END_PI " n)}]}))
(cloning/backup-segment! db-name conn store 1 300)
(cloning/backup-segment! db-name conn store 330 565)
(cloning/backup-segment! db-name conn store 575 1000)
(cloning/backup-segment! db-name conn store 1000 1100)
(assertions
"When there is a gap in the backup"
(count (cloning/backup-gaps (dcbp/saved-segment-info store db-name))) => 2)
(cloning/repair-backup! db-name conn store)
(assertions
"Creates the missing file(s)"
(count (cloning/backup-gaps (dcbp/saved-segment-info store db-name))) => 0)
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})]
(while (= :restored-segment (cloning/restore-segment! db-name target-conn store {}))
(cloning/restore-segment! db-name target-conn store {}))
(let [db (d/db target-conn)
cnt (ffirst (try (d/q '[:find (count ?p) :where [?p :person/name]] db)
(catch Exception e nil)))]
(assertions
"The repaired backup contains all of the original entities"
cnt => 1000)))
(finally
(clean-filesystem! tempdirfile)
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
(specification "Resuming an Interrupted Restore"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
store (new-ram-store)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 101]
(Thread/sleep 1) ; important. if too fast then tx time doesn't change and we get a false success on test
(d/transact conn {:tx-data [{:person/id n
:person/name (str "PI:NAME:<NAME>END_PI " n)}]}))
(cloning/backup-segment! db-name conn store 1 10)
(cloning/backup-segment! db-name conn store 10 20)
(cloning/backup-segment! db-name conn store 20 (:t (d/db conn)))
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})]
(assertions
"Restore :restored-segment when it restores some data"
(cloning/restore-segment! db-name target-conn store {}) => :restored-segment)
(let [group (dcbp/load-transaction-group store db-name 10)
real-load-txns cloning/-load-transactions]
(provided "The restore restores only PART of a segment"
;; The first time we simulate a failure midway through restore
(cloning/-load-transactions s n start) =1x=> (update group :transactions subvec 0 5)
;; The rest of the time we do what we are asked
(cloning/-load-transactions s n start) => (real-load-txns s n start)
;; First attempt on this segment only gets half of them
(cloning/restore-segment! db-name target-conn store {})
;; Retry should get the rest, an complain about the duplicates
(cloning/restore-segment! db-name target-conn store {})
;; Load the remainder of the database
(cloning/restore-segment! db-name target-conn store {})
(assertions
"Resuming succeeds"
(ffirst
(d/q '[:find (count ?id)
:where
[?id :person/id]] (d/db target-conn))) => 100))))
(finally
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
(specification "restore!! for fast restores"
(let [db-name (keyword (gensym "db"))
target-db-name (keyword (gensym "db"))
schema [{:db/ident :person/id
:db/valueType :db.type/long
:db/unique :db.unique/identity
:db/cardinality :db.cardinality/one}
{:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}]
store (new-ram-store)
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
_ (d/transact conn {:tx-data schema})]
(try
(dotimes [n 101]
(Thread/sleep 1) ; important. if too fast then tx time doesn't change and we get a false success on test
(d/transact conn {:tx-data [{:person/id n
:person/name (str "PI:NAME:<NAME>END_PI " n)}]}))
(cloning/backup! db-name conn store {:txns-per-segment 10
:parallel? false})
(let [_ (d/create-database client {:db-name target-db-name})
target-conn (d/connect client {:db-name target-db-name})
result (cloning/restore!! db-name target-conn store {})
new-db (d/db target-conn)]
(assertions
"Returns a result to indicate it is done"
result => {:result "No more segments to restore. Was looking for the next start: 108"}
"Restores the expected data"
(d/pull new-db [:person/name] [:person/id 1]) => {:person/name "PI:NAME:<NAME>END_PI 1"}
(d/pull new-db [:person/name] [:person/id 100]) => {:person/name "PI:NAME:<NAME>END_PI 100"}))
(finally
(d/delete-database client {:db-name target-db-name})
(d/delete-database client {:db-name db-name})))))
|
[
{
"context": "(ns\n ^{:author \"Brian Craft\"\n :doc \"Specialized collections for chrom posi",
"end": 28,
"score": 0.9998834133148193,
"start": 17,
"tag": "NAME",
"value": "Brian Craft"
}
] |
src/cavm/chrom_pos.clj
|
ucscXena/ucsc-xena-server
| 8 |
(ns
^{:author "Brian Craft"
:doc "Specialized collections for chrom positions, with low memory footprint.
Measured to be about 1/7 the size of a vector of hash-maps, and about
1/5 the size of a vector of records.
Chrom names are interned. The interned collection never shrinks."}
cavm.chrom-pos)
(defrecord Chrom [^String chrom ^long chromStart ^long chromEnd ^char strand]
clojure.lang.IFn
(invoke [self k] (k self)))
(def chrom-pos ->Chrom)
(declare ->ChromPosVec chrom-pos-vec)
(deftype ChromPosVec [chroms starts ends strands chrom-cache]
clojure.lang.IPersistentVector
(seq [self] (when (> (count chroms) 0)
(map ->Chrom chroms starts ends strands)))
(nth [self i] (apply ->Chrom (map #(nth % i) [chroms starts ends strands])))
(nth [self i notfound] (or (.valAt self i) notfound))
(empty [self] (chrom-pos-vec))
clojure.lang.ILookup
(valAt [self i] (when (and (>= i 0) (< i (count starts)))
(.nth self i)))
(valAt [self i notfound] (.nth self i notfound))
clojure.lang.ISeq
(first [self] (.valAt self 0))
(next [self] (when (> (count chroms) 1)
(->ChromPosVec (next chroms) (next starts)
(next ends) (next strands) chrom-cache)))
(more [self] (if (> (count chroms) 1)
(->ChromPosVec (rest chroms) (rest starts)
(rest ends) (rest strands) chrom-cache)
'()))
(cons [self {:keys [chrom chromStart chromEnd strand]}]
(->ChromPosVec (conj chroms (chrom-cache chrom)) (conj starts chromStart)
(conj ends chromEnd) (conj strands (or strand \.)) chrom-cache))
(count [self] (count starts))
clojure.lang.IFn
(invoke [self i] (.nth self i))
Object
(toString [self] (str (into [] self))))
(defn strcpy [s] (String. ^String s))
(defn chrom-pos-vec []
(->ChromPosVec [] (vector-of :long) (vector-of :long) (vector-of :char)
(memoize strcpy)))
|
49324
|
(ns
^{:author "<NAME>"
:doc "Specialized collections for chrom positions, with low memory footprint.
Measured to be about 1/7 the size of a vector of hash-maps, and about
1/5 the size of a vector of records.
Chrom names are interned. The interned collection never shrinks."}
cavm.chrom-pos)
(defrecord Chrom [^String chrom ^long chromStart ^long chromEnd ^char strand]
clojure.lang.IFn
(invoke [self k] (k self)))
(def chrom-pos ->Chrom)
(declare ->ChromPosVec chrom-pos-vec)
(deftype ChromPosVec [chroms starts ends strands chrom-cache]
clojure.lang.IPersistentVector
(seq [self] (when (> (count chroms) 0)
(map ->Chrom chroms starts ends strands)))
(nth [self i] (apply ->Chrom (map #(nth % i) [chroms starts ends strands])))
(nth [self i notfound] (or (.valAt self i) notfound))
(empty [self] (chrom-pos-vec))
clojure.lang.ILookup
(valAt [self i] (when (and (>= i 0) (< i (count starts)))
(.nth self i)))
(valAt [self i notfound] (.nth self i notfound))
clojure.lang.ISeq
(first [self] (.valAt self 0))
(next [self] (when (> (count chroms) 1)
(->ChromPosVec (next chroms) (next starts)
(next ends) (next strands) chrom-cache)))
(more [self] (if (> (count chroms) 1)
(->ChromPosVec (rest chroms) (rest starts)
(rest ends) (rest strands) chrom-cache)
'()))
(cons [self {:keys [chrom chromStart chromEnd strand]}]
(->ChromPosVec (conj chroms (chrom-cache chrom)) (conj starts chromStart)
(conj ends chromEnd) (conj strands (or strand \.)) chrom-cache))
(count [self] (count starts))
clojure.lang.IFn
(invoke [self i] (.nth self i))
Object
(toString [self] (str (into [] self))))
(defn strcpy [s] (String. ^String s))
(defn chrom-pos-vec []
(->ChromPosVec [] (vector-of :long) (vector-of :long) (vector-of :char)
(memoize strcpy)))
| true |
(ns
^{:author "PI:NAME:<NAME>END_PI"
:doc "Specialized collections for chrom positions, with low memory footprint.
Measured to be about 1/7 the size of a vector of hash-maps, and about
1/5 the size of a vector of records.
Chrom names are interned. The interned collection never shrinks."}
cavm.chrom-pos)
(defrecord Chrom [^String chrom ^long chromStart ^long chromEnd ^char strand]
clojure.lang.IFn
(invoke [self k] (k self)))
(def chrom-pos ->Chrom)
(declare ->ChromPosVec chrom-pos-vec)
(deftype ChromPosVec [chroms starts ends strands chrom-cache]
clojure.lang.IPersistentVector
(seq [self] (when (> (count chroms) 0)
(map ->Chrom chroms starts ends strands)))
(nth [self i] (apply ->Chrom (map #(nth % i) [chroms starts ends strands])))
(nth [self i notfound] (or (.valAt self i) notfound))
(empty [self] (chrom-pos-vec))
clojure.lang.ILookup
(valAt [self i] (when (and (>= i 0) (< i (count starts)))
(.nth self i)))
(valAt [self i notfound] (.nth self i notfound))
clojure.lang.ISeq
(first [self] (.valAt self 0))
(next [self] (when (> (count chroms) 1)
(->ChromPosVec (next chroms) (next starts)
(next ends) (next strands) chrom-cache)))
(more [self] (if (> (count chroms) 1)
(->ChromPosVec (rest chroms) (rest starts)
(rest ends) (rest strands) chrom-cache)
'()))
(cons [self {:keys [chrom chromStart chromEnd strand]}]
(->ChromPosVec (conj chroms (chrom-cache chrom)) (conj starts chromStart)
(conj ends chromEnd) (conj strands (or strand \.)) chrom-cache))
(count [self] (count starts))
clojure.lang.IFn
(invoke [self i] (.nth self i))
Object
(toString [self] (str (into [] self))))
(defn strcpy [s] (String. ^String s))
(defn chrom-pos-vec []
(->ChromPosVec [] (vector-of :long) (vector-of :long) (vector-of :char)
(memoize strcpy)))
|
[
{
"context": "-endorsement! [ctx user-badge-id owner-id {:keys [user-ids emails content]}]\n (try+\n (if-not (badge-owner? ",
"end": 8576,
"score": 0.8678520321846008,
"start": 8568,
"tag": "KEY",
"value": "user-ids"
}
] |
src/clj/salava/badge/endorsement.clj
|
discendum/salava
| 17 |
(ns salava.badge.endorsement
(:require [yesql.core :refer [defqueries]]
[salava.core.util :refer [get-db md->html get-full-path plugin-fun get-plugins event publish digest bytes->base64]]
[slingshot.slingshot :refer :all]
[clojure.tools.logging :as log]
[salava.badge.main :refer [send-badge-info-to-obf badge-exists?]]
[salava.core.time :as time]
[salava.badge.ext-endorsement :as ext]))
(defqueries "sql/badge/main.sql")
(defqueries "sql/badge/endorsement.sql")
(defqueries "sql/badge/ext_endorsement.sql")
(defn generate-external-id []
(str "urn:uuid:" (java.util.UUID/randomUUID)))
(defn badge-owner? [ctx badge-id user-id]
(let [owner (select-badge-owner {:id badge-id} (into {:result-set-fn first :row-fn :user_id} (get-db ctx)))]
(= owner user-id)))
(defn endorsement-owner? [ctx endorsement-id user-id]
(let [owner (select-endorsement-owner {:id endorsement-id} (into {:result-set-fn first :row-fn :issuer_id} (get-db ctx)))]
(= owner user-id)))
(defn already-endorsed? [ctx user-badge-id user-id]
(pos? (count (select-endorsement-by-issuerid-and-badgeid {:user_id user-id :id user-badge-id} (get-db ctx)))))
(defn insert-endorse-event! [ctx data]
(insert-endorsement-event<! data (get-db ctx)))
(defn insert-endorsement-owner! [ctx data]
(let [owner-id (select-endorsement-receiver-by-badge-id {:id (:object data)} (into {:result-set-fn first :row-fn :id} (get-db ctx)))]
(insert-event-owner! (assoc data :object owner-id) (get-db ctx))))
(defn endorse! [ctx user-badge-id user-id content]
;;TODO check endorsment request first
(try+
(if-not (badge-exists? ctx user-badge-id)
(throw+ {:status "error" :message (str "badge with id " user-badge-id " does not exist")})
(if (badge-owner? ctx user-badge-id user-id)
(throw+ {:status "error" :message "User cannot endorse himself"})
(let [endorser-info-fn (first (plugin-fun (get-plugins ctx) "db" "user-information"))
endorser-info (endorser-info-fn ctx user-id)]
(when-let [id (->> (insert-user-badge-endorsement<! {:user_badge_id user-badge-id
:external_id (generate-external-id)
:issuer_id user-id
:issuer_name (str (:first_name endorser-info) " " (:last_name endorser-info))
:issuer_url (str (get-full-path ctx) "/user/profile/" user-id)
:content content} (get-db ctx))
:generated_key)]
(publish ctx :endorse_badge {:subject user-id :verb "endorse_badge" :object id :type "badge"})
{:id id :status "success"}))))
(catch Object _
(log/error _)
_)))
(defn edit! [ctx user-badge-id endorsement-id content user-id]
(try+
(if (endorsement-owner? ctx endorsement-id user-id)
(do
(update-user-badge-endorsement! {:content content :id endorsement-id} (get-db ctx))
{:status "success"})
(throw+ {:status "error" :message "User cannot delete endorsement they do not own"}))
(catch Object _
{:status "error" :message _})))
(defn delete! [ctx user-badge-id endorsement-id user-id]
(try+
(if (or (endorsement-owner? ctx endorsement-id user-id) (badge-owner? ctx user-badge-id user-id))
(do
(delete-user-badge-endorsement! {:id endorsement-id} (get-db ctx))
(send-badge-info-to-obf ctx user-badge-id user-id)
{:status "success"})
{:status "error"})
(catch Object _
(log/error _)
{:status "error"})))
(defn update-status! [ctx user-id user-badge-id endorsement-id status]
(try+
(when (badge-owner? ctx user-badge-id user-id)
(update-endorsement-status! {:id endorsement-id :status status} (get-db ctx))
(case status
"accepted" (send-badge-info-to-obf ctx user-badge-id user-id)
"declined" (delete! ctx user-badge-id endorsement-id user-id)
nil)
{:status "success"})
(catch Object _
(log/error _)
{:status "error"})))
(defn user-badge-endorsements
([ctx user-badge-id]
(concat (select-user-badge-endorsements {:user_badge_id user-badge-id} (get-db ctx)) (map #(assoc % :type "ext" )(ext/select-user-badge-ext-endorsements {:user_badge_id user-badge-id} (get-db ctx)))))
([ctx user-badge-id html?]
(reduce (fn [r e]
(conj r (-> e (update :content md->html)))) [] (user-badge-endorsements ctx user-badge-id))))
(defn user-badge-endorsements-p [ctx user-badge-id]
(select-user-badge-endorsements-p {:id user-badge-id} (get-db ctx)))
(defn received-pending-endorsements [ctx user-id]
(->> (list*
(map (fn [e] (-> e (update :content md->html))) (select-pending-endorsements {:user_id user-id} (get-db ctx)))
(some->> (ext/endorsements-received ctx user-id true)
(filter #(= (:status %) "pending"))
(map #(update % :content md->html))
(map #(assoc % :type "ext"))))
flatten
(sort-by :mtime >)))
(defn endorsements-received
([ctx user-id]
(map (fn [e] (-> e (update :content md->html)))
(select-received-endorsements {:user_id user-id} (get-db ctx))))
([ctx user-id md?]
(select-received-endorsements {:user_id user-id} (get-db ctx))))
(defn endorsements-received-p [ctx user-id]
(select-received-endorsements-p {:user_id user-id} (get-db ctx)))
(defn endorsements-given [ctx user-id]
(select-given-endorsements {:user_id user-id} (get-db ctx)))
(defn endorsements-given-p [ctx user-id]
(select-given-endorsements-p {:user_id user-id} (get-db ctx)))
(defn endorsement-requests [ctx user-id]
(map (fn [r] (-> r (update :content md->html))) (select-endorsement-requests {:user_id user-id} (get-db ctx))))
(defn endorsement-requests-p [ctx user-id]
(select-endorsement-requests-p {:user_id user-id} (get-db ctx)))
(defn endorsement-requests-pending [ctx user-id]
(->> (endorsement-requests ctx user-id) (filter #(= "pending" (:status %)))))
(defn all-user-endorsements [ctx user-id & md?]
(let [received (if md? (endorsements-received ctx user-id true)(endorsements-received ctx user-id))
given (endorsements-given ctx user-id)
requests (->> (endorsement-requests ctx user-id) (filterv #(= (:status %) "pending")) (mapv #(assoc % :type "request")))
sent-requests (some->> (select-sent-endorsement-requests {:id user-id} (get-db ctx)) (mapv #(assoc % :type "sent_request")))
ext-received (some->> (if md? (ext/endorsements-received ctx user-id true)(ext/endorsements-received ctx user-id))
(mapv #(assoc % :type "ext")))
ext-sent-requests (some->> (select-sent-ext-endorsement-requests {:id user-id} (get-db ctx)) (mapv #(assoc % :type "ext_request")))
all (->> (list* given received requests sent-requests ext-received ext-sent-requests) flatten (sort-by :mtime >))]
{:given given
:received received
:requests requests
:sent-requests sent-requests
:ext-received ext-received
:ext-sent-requests ext-sent-requests
:all-endorsements all}))
(defn all-user-endorsements-p [ctx user-id]
(let [received (endorsements-received-p ctx user-id)
given (endorsements-given-p ctx user-id)
sent-requests (some->> (select-sent-endorsement-requests-p {:id user-id} (get-db ctx)) (mapv #(assoc % :type "sent_request")))
requests (->> (endorsement-requests-p ctx user-id) (filterv #(= (:status %) "pending")) (mapv #(assoc % :type "request")))]
{:given given
:received received
:sent-requests sent-requests
:requests requests}))
(defn insert-request-event! [ctx data]
(insert-endorsement-request-event<! data (get-db ctx)))
(defn insert-request-owner! [ctx data]
(let [owner-id (select-endorsement-request-owner-by-badge-id {:id (:object data)} (into {:result-set-fn first :row-fn :id} (get-db ctx)))]
(insert-event-owner! (assoc data :object owner-id) (get-db ctx))))
(defn- request-sent?
"Avoid request spamming; Check if request has previously been sent to user, returns map of request-id and status"
[ctx user-badge-id user-id]
(select-user-badge-endorsement-request-by-issuer-id {:user_badge_id user-badge-id :issuer_id user-id } (into {:result-set-fn first} (get-db ctx))))
(defn request-endorsement! [ctx user-badge-id owner-id {:keys [user-ids emails content]}]
(try+
(if-not (badge-owner? ctx user-badge-id owner-id)
(throw+ {:status "error" :message "User cannot request endorsement for a badge they do not own"})
(do
(doseq [id user-ids]
(if-let [check (-> (request-sent? ctx user-badge-id id) :id)]
(throw+ {:status "error" :message "Request already sent to user"})
(let [endorser-info (as-> (first (plugin-fun (get-plugins ctx) "db" "user-information")) $
(if $ ($ ctx id) {}))
{:keys [first_name last_name]} endorser-info
user-connection (as-> (first (plugin-fun (get-plugins ctx) "db" "get-connections-user")) $
(if $ (some-> ($ ctx owner-id id) :status) nil))
request-id (-> (request-endorsement<! {:id user-badge-id
:content content
:issuer_name (str first_name " " last_name)
:issuer_id id
:issuer_url (str (get-full-path ctx) "/profile/" id)} (get-db ctx))
:generated_key)]
(publish ctx :request_endorsement {:verb "request_endorsement" :type "badge" :subject owner-id :object request-id})
(when-not user-connection (as-> (first (plugin-fun (get-plugins ctx) "db" "create-connections-user!")) $ ;;create user connection if not existing
(when $ ($ ctx owner-id id)))))))
(when (seq emails) (ext/request-external-endorsements ctx user-badge-id owner-id emails content))))
{:status "success"}
(catch Object ex
(log/error ex)
{:status "error"})))
(defn- request-owner? [ctx request-id user-id]
(let [{:keys [id issuer_id]} (->> (select-endorsement-request-owner {:id request-id} (into {:result-set-fn first} (get-db ctx))))]
(or (= id user-id) (= issuer_id user-id))))
(defn- delete-request! [ctx request-id user-id]
(delete-endorsement-request! {:id request-id} (get-db ctx)))
(defn update-request-status!
"Update endorsement request status, delete when request is declined"
[ctx request-id status user-id]
(try+
(if (request-owner? ctx request-id user-id)
(do
(update-endorsement-request-status! {:id request-id :status status} (get-db ctx))
(case status
"declined" (delete-request! ctx request-id user-id)
nil))
(throw+ {:status "error" :message "User does not own request"}))
{:status "success"}
(catch Object ex
(log/error ex)
{:status "error"})))
(defn user-endorsements-status
"Return endorsement interaction statuses based on user-badge-id"
[ctx user-badge-id current-user-id user-id]
{:received (select-user-received-endorsement-status {:id user-badge-id :issuer_id user-id} (into {:result-set-fn first :row-fn :status} (get-db ctx)))
:request (select-user-endorsement-request-status {:id user-badge-id :issuer_id user-id} (into {:result-set-fn first :row-fn :status} (get-db ctx)))})
(defn pending-endorsement-count [ctx user-badge-id user-id]
(+ (pending-user-badge-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))
(ext/pending-ext-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))))
(defn accepted-endorsement-count [ctx user-badge-id user-id]
{:user_endorsement_count (+ (->> (select-accepted-badge-endorsements {:id user-badge-id} (get-db ctx)) count)
(ext/accepted-ext-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx))))})
(defn endorsements-count [ctx user-badge-id user-id]
{:pending_endorsements_count (pending-endorsement-count ctx user-badge-id user-id)
:user_endorsement_count ""
:endorsement_count ""})
(defn user-badge-pending-requests [ctx user-badge-id user-id]
(sent-pending-requests-by-badge-id {:id user-badge-id} (get-db ctx)))
(defn delete-pending-request! [ctx user-badge-id]
(let [requests (user-badge-pending-requests ctx user-badge-id nil)]
(try+
(doseq [r requests
:let [days-pending (time/no-of-days-passed (long (:mtime r)))]]
(when (>= days-pending 30)
(log/info "Expired pending request id" (:id r))
(log/info "Deleting pending request id " (:id r))
(delete-request! ctx (:id r) nil)
(log/info "Pending request deleted!")))
(catch Object _
(log/error _)))))
|
70551
|
(ns salava.badge.endorsement
(:require [yesql.core :refer [defqueries]]
[salava.core.util :refer [get-db md->html get-full-path plugin-fun get-plugins event publish digest bytes->base64]]
[slingshot.slingshot :refer :all]
[clojure.tools.logging :as log]
[salava.badge.main :refer [send-badge-info-to-obf badge-exists?]]
[salava.core.time :as time]
[salava.badge.ext-endorsement :as ext]))
(defqueries "sql/badge/main.sql")
(defqueries "sql/badge/endorsement.sql")
(defqueries "sql/badge/ext_endorsement.sql")
(defn generate-external-id []
(str "urn:uuid:" (java.util.UUID/randomUUID)))
(defn badge-owner? [ctx badge-id user-id]
(let [owner (select-badge-owner {:id badge-id} (into {:result-set-fn first :row-fn :user_id} (get-db ctx)))]
(= owner user-id)))
(defn endorsement-owner? [ctx endorsement-id user-id]
(let [owner (select-endorsement-owner {:id endorsement-id} (into {:result-set-fn first :row-fn :issuer_id} (get-db ctx)))]
(= owner user-id)))
(defn already-endorsed? [ctx user-badge-id user-id]
(pos? (count (select-endorsement-by-issuerid-and-badgeid {:user_id user-id :id user-badge-id} (get-db ctx)))))
(defn insert-endorse-event! [ctx data]
(insert-endorsement-event<! data (get-db ctx)))
(defn insert-endorsement-owner! [ctx data]
(let [owner-id (select-endorsement-receiver-by-badge-id {:id (:object data)} (into {:result-set-fn first :row-fn :id} (get-db ctx)))]
(insert-event-owner! (assoc data :object owner-id) (get-db ctx))))
(defn endorse! [ctx user-badge-id user-id content]
;;TODO check endorsment request first
(try+
(if-not (badge-exists? ctx user-badge-id)
(throw+ {:status "error" :message (str "badge with id " user-badge-id " does not exist")})
(if (badge-owner? ctx user-badge-id user-id)
(throw+ {:status "error" :message "User cannot endorse himself"})
(let [endorser-info-fn (first (plugin-fun (get-plugins ctx) "db" "user-information"))
endorser-info (endorser-info-fn ctx user-id)]
(when-let [id (->> (insert-user-badge-endorsement<! {:user_badge_id user-badge-id
:external_id (generate-external-id)
:issuer_id user-id
:issuer_name (str (:first_name endorser-info) " " (:last_name endorser-info))
:issuer_url (str (get-full-path ctx) "/user/profile/" user-id)
:content content} (get-db ctx))
:generated_key)]
(publish ctx :endorse_badge {:subject user-id :verb "endorse_badge" :object id :type "badge"})
{:id id :status "success"}))))
(catch Object _
(log/error _)
_)))
(defn edit! [ctx user-badge-id endorsement-id content user-id]
(try+
(if (endorsement-owner? ctx endorsement-id user-id)
(do
(update-user-badge-endorsement! {:content content :id endorsement-id} (get-db ctx))
{:status "success"})
(throw+ {:status "error" :message "User cannot delete endorsement they do not own"}))
(catch Object _
{:status "error" :message _})))
(defn delete! [ctx user-badge-id endorsement-id user-id]
(try+
(if (or (endorsement-owner? ctx endorsement-id user-id) (badge-owner? ctx user-badge-id user-id))
(do
(delete-user-badge-endorsement! {:id endorsement-id} (get-db ctx))
(send-badge-info-to-obf ctx user-badge-id user-id)
{:status "success"})
{:status "error"})
(catch Object _
(log/error _)
{:status "error"})))
(defn update-status! [ctx user-id user-badge-id endorsement-id status]
(try+
(when (badge-owner? ctx user-badge-id user-id)
(update-endorsement-status! {:id endorsement-id :status status} (get-db ctx))
(case status
"accepted" (send-badge-info-to-obf ctx user-badge-id user-id)
"declined" (delete! ctx user-badge-id endorsement-id user-id)
nil)
{:status "success"})
(catch Object _
(log/error _)
{:status "error"})))
(defn user-badge-endorsements
([ctx user-badge-id]
(concat (select-user-badge-endorsements {:user_badge_id user-badge-id} (get-db ctx)) (map #(assoc % :type "ext" )(ext/select-user-badge-ext-endorsements {:user_badge_id user-badge-id} (get-db ctx)))))
([ctx user-badge-id html?]
(reduce (fn [r e]
(conj r (-> e (update :content md->html)))) [] (user-badge-endorsements ctx user-badge-id))))
(defn user-badge-endorsements-p [ctx user-badge-id]
(select-user-badge-endorsements-p {:id user-badge-id} (get-db ctx)))
(defn received-pending-endorsements [ctx user-id]
(->> (list*
(map (fn [e] (-> e (update :content md->html))) (select-pending-endorsements {:user_id user-id} (get-db ctx)))
(some->> (ext/endorsements-received ctx user-id true)
(filter #(= (:status %) "pending"))
(map #(update % :content md->html))
(map #(assoc % :type "ext"))))
flatten
(sort-by :mtime >)))
(defn endorsements-received
([ctx user-id]
(map (fn [e] (-> e (update :content md->html)))
(select-received-endorsements {:user_id user-id} (get-db ctx))))
([ctx user-id md?]
(select-received-endorsements {:user_id user-id} (get-db ctx))))
(defn endorsements-received-p [ctx user-id]
(select-received-endorsements-p {:user_id user-id} (get-db ctx)))
(defn endorsements-given [ctx user-id]
(select-given-endorsements {:user_id user-id} (get-db ctx)))
(defn endorsements-given-p [ctx user-id]
(select-given-endorsements-p {:user_id user-id} (get-db ctx)))
(defn endorsement-requests [ctx user-id]
(map (fn [r] (-> r (update :content md->html))) (select-endorsement-requests {:user_id user-id} (get-db ctx))))
(defn endorsement-requests-p [ctx user-id]
(select-endorsement-requests-p {:user_id user-id} (get-db ctx)))
(defn endorsement-requests-pending [ctx user-id]
(->> (endorsement-requests ctx user-id) (filter #(= "pending" (:status %)))))
(defn all-user-endorsements [ctx user-id & md?]
(let [received (if md? (endorsements-received ctx user-id true)(endorsements-received ctx user-id))
given (endorsements-given ctx user-id)
requests (->> (endorsement-requests ctx user-id) (filterv #(= (:status %) "pending")) (mapv #(assoc % :type "request")))
sent-requests (some->> (select-sent-endorsement-requests {:id user-id} (get-db ctx)) (mapv #(assoc % :type "sent_request")))
ext-received (some->> (if md? (ext/endorsements-received ctx user-id true)(ext/endorsements-received ctx user-id))
(mapv #(assoc % :type "ext")))
ext-sent-requests (some->> (select-sent-ext-endorsement-requests {:id user-id} (get-db ctx)) (mapv #(assoc % :type "ext_request")))
all (->> (list* given received requests sent-requests ext-received ext-sent-requests) flatten (sort-by :mtime >))]
{:given given
:received received
:requests requests
:sent-requests sent-requests
:ext-received ext-received
:ext-sent-requests ext-sent-requests
:all-endorsements all}))
(defn all-user-endorsements-p [ctx user-id]
(let [received (endorsements-received-p ctx user-id)
given (endorsements-given-p ctx user-id)
sent-requests (some->> (select-sent-endorsement-requests-p {:id user-id} (get-db ctx)) (mapv #(assoc % :type "sent_request")))
requests (->> (endorsement-requests-p ctx user-id) (filterv #(= (:status %) "pending")) (mapv #(assoc % :type "request")))]
{:given given
:received received
:sent-requests sent-requests
:requests requests}))
(defn insert-request-event! [ctx data]
(insert-endorsement-request-event<! data (get-db ctx)))
(defn insert-request-owner! [ctx data]
(let [owner-id (select-endorsement-request-owner-by-badge-id {:id (:object data)} (into {:result-set-fn first :row-fn :id} (get-db ctx)))]
(insert-event-owner! (assoc data :object owner-id) (get-db ctx))))
(defn- request-sent?
"Avoid request spamming; Check if request has previously been sent to user, returns map of request-id and status"
[ctx user-badge-id user-id]
(select-user-badge-endorsement-request-by-issuer-id {:user_badge_id user-badge-id :issuer_id user-id } (into {:result-set-fn first} (get-db ctx))))
(defn request-endorsement! [ctx user-badge-id owner-id {:keys [<KEY> emails content]}]
(try+
(if-not (badge-owner? ctx user-badge-id owner-id)
(throw+ {:status "error" :message "User cannot request endorsement for a badge they do not own"})
(do
(doseq [id user-ids]
(if-let [check (-> (request-sent? ctx user-badge-id id) :id)]
(throw+ {:status "error" :message "Request already sent to user"})
(let [endorser-info (as-> (first (plugin-fun (get-plugins ctx) "db" "user-information")) $
(if $ ($ ctx id) {}))
{:keys [first_name last_name]} endorser-info
user-connection (as-> (first (plugin-fun (get-plugins ctx) "db" "get-connections-user")) $
(if $ (some-> ($ ctx owner-id id) :status) nil))
request-id (-> (request-endorsement<! {:id user-badge-id
:content content
:issuer_name (str first_name " " last_name)
:issuer_id id
:issuer_url (str (get-full-path ctx) "/profile/" id)} (get-db ctx))
:generated_key)]
(publish ctx :request_endorsement {:verb "request_endorsement" :type "badge" :subject owner-id :object request-id})
(when-not user-connection (as-> (first (plugin-fun (get-plugins ctx) "db" "create-connections-user!")) $ ;;create user connection if not existing
(when $ ($ ctx owner-id id)))))))
(when (seq emails) (ext/request-external-endorsements ctx user-badge-id owner-id emails content))))
{:status "success"}
(catch Object ex
(log/error ex)
{:status "error"})))
(defn- request-owner? [ctx request-id user-id]
(let [{:keys [id issuer_id]} (->> (select-endorsement-request-owner {:id request-id} (into {:result-set-fn first} (get-db ctx))))]
(or (= id user-id) (= issuer_id user-id))))
(defn- delete-request! [ctx request-id user-id]
(delete-endorsement-request! {:id request-id} (get-db ctx)))
(defn update-request-status!
"Update endorsement request status, delete when request is declined"
[ctx request-id status user-id]
(try+
(if (request-owner? ctx request-id user-id)
(do
(update-endorsement-request-status! {:id request-id :status status} (get-db ctx))
(case status
"declined" (delete-request! ctx request-id user-id)
nil))
(throw+ {:status "error" :message "User does not own request"}))
{:status "success"}
(catch Object ex
(log/error ex)
{:status "error"})))
(defn user-endorsements-status
"Return endorsement interaction statuses based on user-badge-id"
[ctx user-badge-id current-user-id user-id]
{:received (select-user-received-endorsement-status {:id user-badge-id :issuer_id user-id} (into {:result-set-fn first :row-fn :status} (get-db ctx)))
:request (select-user-endorsement-request-status {:id user-badge-id :issuer_id user-id} (into {:result-set-fn first :row-fn :status} (get-db ctx)))})
(defn pending-endorsement-count [ctx user-badge-id user-id]
(+ (pending-user-badge-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))
(ext/pending-ext-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))))
(defn accepted-endorsement-count [ctx user-badge-id user-id]
{:user_endorsement_count (+ (->> (select-accepted-badge-endorsements {:id user-badge-id} (get-db ctx)) count)
(ext/accepted-ext-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx))))})
(defn endorsements-count [ctx user-badge-id user-id]
{:pending_endorsements_count (pending-endorsement-count ctx user-badge-id user-id)
:user_endorsement_count ""
:endorsement_count ""})
(defn user-badge-pending-requests [ctx user-badge-id user-id]
(sent-pending-requests-by-badge-id {:id user-badge-id} (get-db ctx)))
(defn delete-pending-request! [ctx user-badge-id]
(let [requests (user-badge-pending-requests ctx user-badge-id nil)]
(try+
(doseq [r requests
:let [days-pending (time/no-of-days-passed (long (:mtime r)))]]
(when (>= days-pending 30)
(log/info "Expired pending request id" (:id r))
(log/info "Deleting pending request id " (:id r))
(delete-request! ctx (:id r) nil)
(log/info "Pending request deleted!")))
(catch Object _
(log/error _)))))
| true |
(ns salava.badge.endorsement
(:require [yesql.core :refer [defqueries]]
[salava.core.util :refer [get-db md->html get-full-path plugin-fun get-plugins event publish digest bytes->base64]]
[slingshot.slingshot :refer :all]
[clojure.tools.logging :as log]
[salava.badge.main :refer [send-badge-info-to-obf badge-exists?]]
[salava.core.time :as time]
[salava.badge.ext-endorsement :as ext]))
(defqueries "sql/badge/main.sql")
(defqueries "sql/badge/endorsement.sql")
(defqueries "sql/badge/ext_endorsement.sql")
(defn generate-external-id []
(str "urn:uuid:" (java.util.UUID/randomUUID)))
(defn badge-owner? [ctx badge-id user-id]
(let [owner (select-badge-owner {:id badge-id} (into {:result-set-fn first :row-fn :user_id} (get-db ctx)))]
(= owner user-id)))
(defn endorsement-owner? [ctx endorsement-id user-id]
(let [owner (select-endorsement-owner {:id endorsement-id} (into {:result-set-fn first :row-fn :issuer_id} (get-db ctx)))]
(= owner user-id)))
(defn already-endorsed? [ctx user-badge-id user-id]
(pos? (count (select-endorsement-by-issuerid-and-badgeid {:user_id user-id :id user-badge-id} (get-db ctx)))))
(defn insert-endorse-event! [ctx data]
(insert-endorsement-event<! data (get-db ctx)))
(defn insert-endorsement-owner! [ctx data]
(let [owner-id (select-endorsement-receiver-by-badge-id {:id (:object data)} (into {:result-set-fn first :row-fn :id} (get-db ctx)))]
(insert-event-owner! (assoc data :object owner-id) (get-db ctx))))
(defn endorse! [ctx user-badge-id user-id content]
;;TODO check endorsment request first
(try+
(if-not (badge-exists? ctx user-badge-id)
(throw+ {:status "error" :message (str "badge with id " user-badge-id " does not exist")})
(if (badge-owner? ctx user-badge-id user-id)
(throw+ {:status "error" :message "User cannot endorse himself"})
(let [endorser-info-fn (first (plugin-fun (get-plugins ctx) "db" "user-information"))
endorser-info (endorser-info-fn ctx user-id)]
(when-let [id (->> (insert-user-badge-endorsement<! {:user_badge_id user-badge-id
:external_id (generate-external-id)
:issuer_id user-id
:issuer_name (str (:first_name endorser-info) " " (:last_name endorser-info))
:issuer_url (str (get-full-path ctx) "/user/profile/" user-id)
:content content} (get-db ctx))
:generated_key)]
(publish ctx :endorse_badge {:subject user-id :verb "endorse_badge" :object id :type "badge"})
{:id id :status "success"}))))
(catch Object _
(log/error _)
_)))
(defn edit! [ctx user-badge-id endorsement-id content user-id]
(try+
(if (endorsement-owner? ctx endorsement-id user-id)
(do
(update-user-badge-endorsement! {:content content :id endorsement-id} (get-db ctx))
{:status "success"})
(throw+ {:status "error" :message "User cannot delete endorsement they do not own"}))
(catch Object _
{:status "error" :message _})))
(defn delete! [ctx user-badge-id endorsement-id user-id]
(try+
(if (or (endorsement-owner? ctx endorsement-id user-id) (badge-owner? ctx user-badge-id user-id))
(do
(delete-user-badge-endorsement! {:id endorsement-id} (get-db ctx))
(send-badge-info-to-obf ctx user-badge-id user-id)
{:status "success"})
{:status "error"})
(catch Object _
(log/error _)
{:status "error"})))
(defn update-status! [ctx user-id user-badge-id endorsement-id status]
(try+
(when (badge-owner? ctx user-badge-id user-id)
(update-endorsement-status! {:id endorsement-id :status status} (get-db ctx))
(case status
"accepted" (send-badge-info-to-obf ctx user-badge-id user-id)
"declined" (delete! ctx user-badge-id endorsement-id user-id)
nil)
{:status "success"})
(catch Object _
(log/error _)
{:status "error"})))
(defn user-badge-endorsements
([ctx user-badge-id]
(concat (select-user-badge-endorsements {:user_badge_id user-badge-id} (get-db ctx)) (map #(assoc % :type "ext" )(ext/select-user-badge-ext-endorsements {:user_badge_id user-badge-id} (get-db ctx)))))
([ctx user-badge-id html?]
(reduce (fn [r e]
(conj r (-> e (update :content md->html)))) [] (user-badge-endorsements ctx user-badge-id))))
(defn user-badge-endorsements-p [ctx user-badge-id]
(select-user-badge-endorsements-p {:id user-badge-id} (get-db ctx)))
(defn received-pending-endorsements [ctx user-id]
(->> (list*
(map (fn [e] (-> e (update :content md->html))) (select-pending-endorsements {:user_id user-id} (get-db ctx)))
(some->> (ext/endorsements-received ctx user-id true)
(filter #(= (:status %) "pending"))
(map #(update % :content md->html))
(map #(assoc % :type "ext"))))
flatten
(sort-by :mtime >)))
(defn endorsements-received
([ctx user-id]
(map (fn [e] (-> e (update :content md->html)))
(select-received-endorsements {:user_id user-id} (get-db ctx))))
([ctx user-id md?]
(select-received-endorsements {:user_id user-id} (get-db ctx))))
(defn endorsements-received-p [ctx user-id]
(select-received-endorsements-p {:user_id user-id} (get-db ctx)))
(defn endorsements-given [ctx user-id]
(select-given-endorsements {:user_id user-id} (get-db ctx)))
(defn endorsements-given-p [ctx user-id]
(select-given-endorsements-p {:user_id user-id} (get-db ctx)))
(defn endorsement-requests [ctx user-id]
(map (fn [r] (-> r (update :content md->html))) (select-endorsement-requests {:user_id user-id} (get-db ctx))))
(defn endorsement-requests-p [ctx user-id]
(select-endorsement-requests-p {:user_id user-id} (get-db ctx)))
(defn endorsement-requests-pending [ctx user-id]
(->> (endorsement-requests ctx user-id) (filter #(= "pending" (:status %)))))
(defn all-user-endorsements [ctx user-id & md?]
(let [received (if md? (endorsements-received ctx user-id true)(endorsements-received ctx user-id))
given (endorsements-given ctx user-id)
requests (->> (endorsement-requests ctx user-id) (filterv #(= (:status %) "pending")) (mapv #(assoc % :type "request")))
sent-requests (some->> (select-sent-endorsement-requests {:id user-id} (get-db ctx)) (mapv #(assoc % :type "sent_request")))
ext-received (some->> (if md? (ext/endorsements-received ctx user-id true)(ext/endorsements-received ctx user-id))
(mapv #(assoc % :type "ext")))
ext-sent-requests (some->> (select-sent-ext-endorsement-requests {:id user-id} (get-db ctx)) (mapv #(assoc % :type "ext_request")))
all (->> (list* given received requests sent-requests ext-received ext-sent-requests) flatten (sort-by :mtime >))]
{:given given
:received received
:requests requests
:sent-requests sent-requests
:ext-received ext-received
:ext-sent-requests ext-sent-requests
:all-endorsements all}))
(defn all-user-endorsements-p [ctx user-id]
(let [received (endorsements-received-p ctx user-id)
given (endorsements-given-p ctx user-id)
sent-requests (some->> (select-sent-endorsement-requests-p {:id user-id} (get-db ctx)) (mapv #(assoc % :type "sent_request")))
requests (->> (endorsement-requests-p ctx user-id) (filterv #(= (:status %) "pending")) (mapv #(assoc % :type "request")))]
{:given given
:received received
:sent-requests sent-requests
:requests requests}))
(defn insert-request-event! [ctx data]
(insert-endorsement-request-event<! data (get-db ctx)))
(defn insert-request-owner! [ctx data]
(let [owner-id (select-endorsement-request-owner-by-badge-id {:id (:object data)} (into {:result-set-fn first :row-fn :id} (get-db ctx)))]
(insert-event-owner! (assoc data :object owner-id) (get-db ctx))))
(defn- request-sent?
"Avoid request spamming; Check if request has previously been sent to user, returns map of request-id and status"
[ctx user-badge-id user-id]
(select-user-badge-endorsement-request-by-issuer-id {:user_badge_id user-badge-id :issuer_id user-id } (into {:result-set-fn first} (get-db ctx))))
(defn request-endorsement! [ctx user-badge-id owner-id {:keys [PI:KEY:<KEY>END_PI emails content]}]
(try+
(if-not (badge-owner? ctx user-badge-id owner-id)
(throw+ {:status "error" :message "User cannot request endorsement for a badge they do not own"})
(do
(doseq [id user-ids]
(if-let [check (-> (request-sent? ctx user-badge-id id) :id)]
(throw+ {:status "error" :message "Request already sent to user"})
(let [endorser-info (as-> (first (plugin-fun (get-plugins ctx) "db" "user-information")) $
(if $ ($ ctx id) {}))
{:keys [first_name last_name]} endorser-info
user-connection (as-> (first (plugin-fun (get-plugins ctx) "db" "get-connections-user")) $
(if $ (some-> ($ ctx owner-id id) :status) nil))
request-id (-> (request-endorsement<! {:id user-badge-id
:content content
:issuer_name (str first_name " " last_name)
:issuer_id id
:issuer_url (str (get-full-path ctx) "/profile/" id)} (get-db ctx))
:generated_key)]
(publish ctx :request_endorsement {:verb "request_endorsement" :type "badge" :subject owner-id :object request-id})
(when-not user-connection (as-> (first (plugin-fun (get-plugins ctx) "db" "create-connections-user!")) $ ;;create user connection if not existing
(when $ ($ ctx owner-id id)))))))
(when (seq emails) (ext/request-external-endorsements ctx user-badge-id owner-id emails content))))
{:status "success"}
(catch Object ex
(log/error ex)
{:status "error"})))
(defn- request-owner? [ctx request-id user-id]
(let [{:keys [id issuer_id]} (->> (select-endorsement-request-owner {:id request-id} (into {:result-set-fn first} (get-db ctx))))]
(or (= id user-id) (= issuer_id user-id))))
(defn- delete-request! [ctx request-id user-id]
(delete-endorsement-request! {:id request-id} (get-db ctx)))
(defn update-request-status!
"Update endorsement request status, delete when request is declined"
[ctx request-id status user-id]
(try+
(if (request-owner? ctx request-id user-id)
(do
(update-endorsement-request-status! {:id request-id :status status} (get-db ctx))
(case status
"declined" (delete-request! ctx request-id user-id)
nil))
(throw+ {:status "error" :message "User does not own request"}))
{:status "success"}
(catch Object ex
(log/error ex)
{:status "error"})))
(defn user-endorsements-status
"Return endorsement interaction statuses based on user-badge-id"
[ctx user-badge-id current-user-id user-id]
{:received (select-user-received-endorsement-status {:id user-badge-id :issuer_id user-id} (into {:result-set-fn first :row-fn :status} (get-db ctx)))
:request (select-user-endorsement-request-status {:id user-badge-id :issuer_id user-id} (into {:result-set-fn first :row-fn :status} (get-db ctx)))})
(defn pending-endorsement-count [ctx user-badge-id user-id]
(+ (pending-user-badge-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))
(ext/pending-ext-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx)))))
(defn accepted-endorsement-count [ctx user-badge-id user-id]
{:user_endorsement_count (+ (->> (select-accepted-badge-endorsements {:id user-badge-id} (get-db ctx)) count)
(ext/accepted-ext-endorsement-count {:id user-badge-id} (into {:result-set-fn first :row-fn :count} (get-db ctx))))})
(defn endorsements-count [ctx user-badge-id user-id]
{:pending_endorsements_count (pending-endorsement-count ctx user-badge-id user-id)
:user_endorsement_count ""
:endorsement_count ""})
(defn user-badge-pending-requests [ctx user-badge-id user-id]
(sent-pending-requests-by-badge-id {:id user-badge-id} (get-db ctx)))
(defn delete-pending-request! [ctx user-badge-id]
(let [requests (user-badge-pending-requests ctx user-badge-id nil)]
(try+
(doseq [r requests
:let [days-pending (time/no-of-days-passed (long (:mtime r)))]]
(when (>= days-pending 30)
(log/info "Expired pending request id" (:id r))
(log/info "Deleting pending request id " (:id r))
(delete-request! ctx (:id r) nil)
(log/info "Pending request deleted!")))
(catch Object _
(log/error _)))))
|
[
{
"context": "correctamente los valores\"\n (is (= '(\"HOLA\" + \" MUNDO\" + \"\")\n (preprocesar-expresion '(X$ + \"",
"end": 8070,
"score": 0.6524322628974915,
"start": 8065,
"tag": "NAME",
"value": "MUNDO"
}
] |
test/tp/core_test.clj
|
SantiValdezUlzurrun/Interprete-AppleSoft-Basic
| 2 |
(ns tp.core-test
(:require [clojure.test :refer :all]
[tp.basic :refer :all]))
(deftest testPalabrasReservadas
(testing "Al Preguntarse Si Las Siguientes Palabras Son Reservadas El Resultado Es El Indicado"
(is (= false (palabra-reservada? 'SPACE)))
(is (= true (palabra-reservada? 'REM)))))
(deftest testOperadores
(testing "Al Preguntarse Si Las Siguientes Simbolos Son Operadores El Resultado Es El Indicado"
(is (= false (operador? (symbol "%"))))
(is (= true (operador? '+)))))
(deftest testVariableFloat
(testing "Al preguntarse si la variable es del tipo float se devuelve el resultado correcto"
(is (= false (variable-float? 'X%)))
(is (= false (variable-float? 'X$)))
(is (= true (variable-float? 'X)))))
(deftest testVariableInteger
(testing "Al preguntarse si la variable es del tipo integer se devuelve el resultado correcto"
(is (= true (variable-integer? 'X%)))
(is (= false (variable-integer? 'X$)))
(is (= false (variable-integer? 'X)))))
(deftest testVariableString
(testing "Al preguntarse si la variable es del tipo string se devuelve el resultado correcto"
(is (= false (variable-string? 'X%)))
(is (= true (variable-string? 'X$)))
(is (= false (variable-string? 'X)))))
(deftest testeliminarCeroDecimal
(testing "Al eliminar el cero decimal de los siguientes ejemplos el valor es el esperado"
(is (= 1.5 (eliminar-cero-decimal 1.5)))
(is (= 'A (eliminar-cero-decimal 'A)))
(is (= 1 (eliminar-cero-decimal 1.0)))
(is (= 1.5 (eliminar-cero-decimal 1.50)))))
(deftest testeliminarCeroEntero
(testing "Al eliminar el cero entero de los siguientes ejemplos el valor es el esperado"
(is (= nil (eliminar-cero-entero nil)))
(is (= "A" (eliminar-cero-entero 'A)))
(is (= "0" (eliminar-cero-entero 0)))
(is (= "1.5" (eliminar-cero-entero 1.5)))
(is (= "1" (eliminar-cero-entero 1)))
(is (= "-1" (eliminar-cero-entero -1)))
(is (= "-1.5" (eliminar-cero-entero -1.5)))
(is (= ".5" (eliminar-cero-entero 0.5)))
(is (= "-.5" (eliminar-cero-entero -0.5)))))
(deftest test-anular-invalidos
(testing "Al ingresar una sentencia se anulan los invalidos"
(is (= '(IF X nil * Y < 12 THEN LET nil X = 0)
(anular-invalidos '(IF X & * Y < 12 THEN LET ! X = 0))))))
(deftest test-cargar-linea
(testing "Al recibir una linea de codigo y un ambiente retorna el ambiente correctamente actualizado"
(is (= '[((10 (PRINT X))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(10 (PRINT X)) [() [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(20 (X = 100)) ['((10 (PRINT X))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (15 (X = X + 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(15 (X = X + 1)) ['((10 (PRINT X)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (15 (X = X - 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(15 (X = X - 1)) ['((10 (PRINT X)) (15 (X = X + 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))))
(deftest test-eliminar-rem
(testing "Al recibir una representacion intermedia elimina las sentencias REM correctamente"
(is (= '((10 (PRINT X)) (20 (DATA HOLA)) (100 (DATA MUNDO , 10 , 20)))
(eliminar-rem '((10 (PRINT X) (REM ESTE NO) (DATA 30)) (20 (DATA HOLA)) (100 (DATA MUNDO , 10 , 20))))))
(is (= '((10 (PRINT X) (DATA 30)) (20) (100 (DATA MUNDO , 10 , 20)))
(eliminar-rem '((10 (PRINT X) (DATA 30)) (20 (REM HOLA)) (100 (DATA MUNDO , 10 , 20))))))))
(deftest test-expandir-nexts
(testing "Al recibir una secuencia de sentencias expande los nexts correctamente"
(is (= '((PRINT 1) (NEXT A) (NEXT B))
(expandir-nexts (list '(PRINT 1) (list 'NEXT 'A (symbol ",") 'B)))))
(is (= '(10 (PRINT X) (NEXT A))
(expandir-nexts (list 10 '(PRINT X) '(NEXT A)))))
(is (= '(10 (PRINT X) (PRINT Y))
(expandir-nexts '(10 (PRINT X) (PRINT Y)))))
(is (= '(10 (PRINT Y) (NEXT A) (DATA HOLA))
(expandir-nexts '(10 (PRINT Y) (NEXT A) (DATA HOLA)))))
(is (= '(10 (PRINT Y) (NEXT A) (NEXT B) (DATA HOLA))
(expandir-nexts (list 10 '(PRINT Y) (list 'NEXT 'A (symbol ",") 'B) '(DATA HOLA)))))
(is (= '((NEXT A) (NEXT B) (PRINT 1))
(expandir-nexts (list (list 'NEXT 'A (symbol ",") 'B) '(PRINT 1)))))
(is (= '((NEXT A) (PRINT 1))
(expandir-nexts '((NEXT A) (PRINT 1)))))))
(deftest test-contar-sentencias
(testing "Al recibir un nro-linea y un amb cuenta las sentencias de esa linea correctamente"
(is (= 2
(contar-sentencias 10 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= 1
(contar-sentencias 15 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= 2
(contar-sentencias 20 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))))
(deftest test-buscar-lineas-restantes
(testing "Al recibir un ambiente devuelve una lista con las lineas restantes de la siguiente forma"
(is (= nil
(buscar-lineas-restantes [() [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= nil
(buscar-lineas-restantes ['((PRINT X) (PRINT Y)) [:ejecucion-inmediata 2] [] [] [] 0 {}])))
(is (= (list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 2] [] [] [] 0 {}])))
(is (= (list '(10 (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= (list '(10) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 0] [] [] [] 0 {}])))
(is (= (list '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 1] [] [] [] 0 {}])))
(is (= (list '(15) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 0] [] [] [] 0 {}])))
(is (= '((20 (NEXT I) (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}])))
(is (= '((20 (NEXT I) (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 2] [] [] [] 0 {}])))
(is (= '((20 (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 1] [] [] [] 0 {}])))
(is (= '((20))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 0] [] [] [] 0 {}])))
(is (= '((20))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 -1] [] [] [] 0 {}])))
(is (= nil
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [25 0] [] [] [] 0 {}])))))
(deftest test-preprocesar-expresion
(testing "Al recibir una expresion y el ambiente remplaza correctamente los valores"
(is (= '("HOLA" + " MUNDO" + "")
(preprocesar-expresion '(X$ + " MUNDO" + Z$) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X$ "HOLA"}])))
(is (= '(5 + 0 / 2 * 0)
(preprocesar-expresion '(X + . / Y% * Z) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 5 Y% 2}])))))
(deftest test-desambiguar
(testing "Al desambiguar las siguientes expresiones el resultado es correcto"
(is (= (list '-u 2 '* (symbol "(") '-u 3 '+ 5 '- (symbol "(") 2 '/ 7 (symbol ")") (symbol ")"))
(desambiguar (list '- 2 '* (symbol "(") '- 3 '+ 5 '- (symbol "(") '+ 2 '/ 7 (symbol ")") (symbol ")")))))
(is (= (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ")")))))
(is (= (list 'MID3$ (symbol "(") 1 (symbol ",") 2 (symbol ",") 3 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ",") 3 (symbol ")")))))
(is (= (list 'MID3$ (symbol "(") 1 (symbol ",") '-u 2 '+ 'K (symbol ",") 3 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") '- 2 '+ 'K (symbol ",") 3 (symbol ")")))))))
(deftest test-ejecutar-asignacion
(testing "Al recibir una asignacion y un amb y devuelve el amb actualizado"
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 5}]
(ejecutar-asignacion '(X = 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 5}]
(ejecutar-asignacion '(X = 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 3}]
(ejecutar-asignacion '(X = X + 1) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X$ "HOLA MUNDO"}]
(ejecutar-asignacion '(X$ = X$ + " MUNDO") ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X$ "HOLA"}])))))
(deftest test-continuar-linea
(testing "Al recibir un amb devuelve el resultado correcto"
(is (= [nil [(list '(10 (PRINT X)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}]]
(continuar-linea [(list '(10 (PRINT X)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}])))
(is (= [:omitir-restante [(list '(10 (PRINT X)) '(15 (GOSUB 100) (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 1] [] [] [] 0 {}]]
(continuar-linea [(list '(10 (PRINT X)) '(15 (GOSUB 100) (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [[15 2]] [] [] 0 {}])))))
(deftest test-aridad
(testing "Al recibir las sentencias correspondientes devuelve la aridad correcta"
(is (= 0
(aridad 'THEN)))
(is (= 1
(aridad 'SIN)))
(is (= 2
(aridad '*)))
(is (= 2
(aridad 'MID$)))
(is (= 3
(aridad 'MID3$)))))
|
96523
|
(ns tp.core-test
(:require [clojure.test :refer :all]
[tp.basic :refer :all]))
(deftest testPalabrasReservadas
(testing "Al Preguntarse Si Las Siguientes Palabras Son Reservadas El Resultado Es El Indicado"
(is (= false (palabra-reservada? 'SPACE)))
(is (= true (palabra-reservada? 'REM)))))
(deftest testOperadores
(testing "Al Preguntarse Si Las Siguientes Simbolos Son Operadores El Resultado Es El Indicado"
(is (= false (operador? (symbol "%"))))
(is (= true (operador? '+)))))
(deftest testVariableFloat
(testing "Al preguntarse si la variable es del tipo float se devuelve el resultado correcto"
(is (= false (variable-float? 'X%)))
(is (= false (variable-float? 'X$)))
(is (= true (variable-float? 'X)))))
(deftest testVariableInteger
(testing "Al preguntarse si la variable es del tipo integer se devuelve el resultado correcto"
(is (= true (variable-integer? 'X%)))
(is (= false (variable-integer? 'X$)))
(is (= false (variable-integer? 'X)))))
(deftest testVariableString
(testing "Al preguntarse si la variable es del tipo string se devuelve el resultado correcto"
(is (= false (variable-string? 'X%)))
(is (= true (variable-string? 'X$)))
(is (= false (variable-string? 'X)))))
(deftest testeliminarCeroDecimal
(testing "Al eliminar el cero decimal de los siguientes ejemplos el valor es el esperado"
(is (= 1.5 (eliminar-cero-decimal 1.5)))
(is (= 'A (eliminar-cero-decimal 'A)))
(is (= 1 (eliminar-cero-decimal 1.0)))
(is (= 1.5 (eliminar-cero-decimal 1.50)))))
(deftest testeliminarCeroEntero
(testing "Al eliminar el cero entero de los siguientes ejemplos el valor es el esperado"
(is (= nil (eliminar-cero-entero nil)))
(is (= "A" (eliminar-cero-entero 'A)))
(is (= "0" (eliminar-cero-entero 0)))
(is (= "1.5" (eliminar-cero-entero 1.5)))
(is (= "1" (eliminar-cero-entero 1)))
(is (= "-1" (eliminar-cero-entero -1)))
(is (= "-1.5" (eliminar-cero-entero -1.5)))
(is (= ".5" (eliminar-cero-entero 0.5)))
(is (= "-.5" (eliminar-cero-entero -0.5)))))
(deftest test-anular-invalidos
(testing "Al ingresar una sentencia se anulan los invalidos"
(is (= '(IF X nil * Y < 12 THEN LET nil X = 0)
(anular-invalidos '(IF X & * Y < 12 THEN LET ! X = 0))))))
(deftest test-cargar-linea
(testing "Al recibir una linea de codigo y un ambiente retorna el ambiente correctamente actualizado"
(is (= '[((10 (PRINT X))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(10 (PRINT X)) [() [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(20 (X = 100)) ['((10 (PRINT X))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (15 (X = X + 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(15 (X = X + 1)) ['((10 (PRINT X)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (15 (X = X - 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(15 (X = X - 1)) ['((10 (PRINT X)) (15 (X = X + 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))))
(deftest test-eliminar-rem
(testing "Al recibir una representacion intermedia elimina las sentencias REM correctamente"
(is (= '((10 (PRINT X)) (20 (DATA HOLA)) (100 (DATA MUNDO , 10 , 20)))
(eliminar-rem '((10 (PRINT X) (REM ESTE NO) (DATA 30)) (20 (DATA HOLA)) (100 (DATA MUNDO , 10 , 20))))))
(is (= '((10 (PRINT X) (DATA 30)) (20) (100 (DATA MUNDO , 10 , 20)))
(eliminar-rem '((10 (PRINT X) (DATA 30)) (20 (REM HOLA)) (100 (DATA MUNDO , 10 , 20))))))))
(deftest test-expandir-nexts
(testing "Al recibir una secuencia de sentencias expande los nexts correctamente"
(is (= '((PRINT 1) (NEXT A) (NEXT B))
(expandir-nexts (list '(PRINT 1) (list 'NEXT 'A (symbol ",") 'B)))))
(is (= '(10 (PRINT X) (NEXT A))
(expandir-nexts (list 10 '(PRINT X) '(NEXT A)))))
(is (= '(10 (PRINT X) (PRINT Y))
(expandir-nexts '(10 (PRINT X) (PRINT Y)))))
(is (= '(10 (PRINT Y) (NEXT A) (DATA HOLA))
(expandir-nexts '(10 (PRINT Y) (NEXT A) (DATA HOLA)))))
(is (= '(10 (PRINT Y) (NEXT A) (NEXT B) (DATA HOLA))
(expandir-nexts (list 10 '(PRINT Y) (list 'NEXT 'A (symbol ",") 'B) '(DATA HOLA)))))
(is (= '((NEXT A) (NEXT B) (PRINT 1))
(expandir-nexts (list (list 'NEXT 'A (symbol ",") 'B) '(PRINT 1)))))
(is (= '((NEXT A) (PRINT 1))
(expandir-nexts '((NEXT A) (PRINT 1)))))))
(deftest test-contar-sentencias
(testing "Al recibir un nro-linea y un amb cuenta las sentencias de esa linea correctamente"
(is (= 2
(contar-sentencias 10 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= 1
(contar-sentencias 15 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= 2
(contar-sentencias 20 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))))
(deftest test-buscar-lineas-restantes
(testing "Al recibir un ambiente devuelve una lista con las lineas restantes de la siguiente forma"
(is (= nil
(buscar-lineas-restantes [() [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= nil
(buscar-lineas-restantes ['((PRINT X) (PRINT Y)) [:ejecucion-inmediata 2] [] [] [] 0 {}])))
(is (= (list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 2] [] [] [] 0 {}])))
(is (= (list '(10 (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= (list '(10) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 0] [] [] [] 0 {}])))
(is (= (list '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 1] [] [] [] 0 {}])))
(is (= (list '(15) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 0] [] [] [] 0 {}])))
(is (= '((20 (NEXT I) (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}])))
(is (= '((20 (NEXT I) (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 2] [] [] [] 0 {}])))
(is (= '((20 (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 1] [] [] [] 0 {}])))
(is (= '((20))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 0] [] [] [] 0 {}])))
(is (= '((20))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 -1] [] [] [] 0 {}])))
(is (= nil
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [25 0] [] [] [] 0 {}])))))
(deftest test-preprocesar-expresion
(testing "Al recibir una expresion y el ambiente remplaza correctamente los valores"
(is (= '("HOLA" + " <NAME>" + "")
(preprocesar-expresion '(X$ + " MUNDO" + Z$) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X$ "HOLA"}])))
(is (= '(5 + 0 / 2 * 0)
(preprocesar-expresion '(X + . / Y% * Z) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 5 Y% 2}])))))
(deftest test-desambiguar
(testing "Al desambiguar las siguientes expresiones el resultado es correcto"
(is (= (list '-u 2 '* (symbol "(") '-u 3 '+ 5 '- (symbol "(") 2 '/ 7 (symbol ")") (symbol ")"))
(desambiguar (list '- 2 '* (symbol "(") '- 3 '+ 5 '- (symbol "(") '+ 2 '/ 7 (symbol ")") (symbol ")")))))
(is (= (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ")")))))
(is (= (list 'MID3$ (symbol "(") 1 (symbol ",") 2 (symbol ",") 3 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ",") 3 (symbol ")")))))
(is (= (list 'MID3$ (symbol "(") 1 (symbol ",") '-u 2 '+ 'K (symbol ",") 3 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") '- 2 '+ 'K (symbol ",") 3 (symbol ")")))))))
(deftest test-ejecutar-asignacion
(testing "Al recibir una asignacion y un amb y devuelve el amb actualizado"
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 5}]
(ejecutar-asignacion '(X = 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 5}]
(ejecutar-asignacion '(X = 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 3}]
(ejecutar-asignacion '(X = X + 1) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X$ "HOLA MUNDO"}]
(ejecutar-asignacion '(X$ = X$ + " MUNDO") ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X$ "HOLA"}])))))
(deftest test-continuar-linea
(testing "Al recibir un amb devuelve el resultado correcto"
(is (= [nil [(list '(10 (PRINT X)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}]]
(continuar-linea [(list '(10 (PRINT X)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}])))
(is (= [:omitir-restante [(list '(10 (PRINT X)) '(15 (GOSUB 100) (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 1] [] [] [] 0 {}]]
(continuar-linea [(list '(10 (PRINT X)) '(15 (GOSUB 100) (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [[15 2]] [] [] 0 {}])))))
(deftest test-aridad
(testing "Al recibir las sentencias correspondientes devuelve la aridad correcta"
(is (= 0
(aridad 'THEN)))
(is (= 1
(aridad 'SIN)))
(is (= 2
(aridad '*)))
(is (= 2
(aridad 'MID$)))
(is (= 3
(aridad 'MID3$)))))
| true |
(ns tp.core-test
(:require [clojure.test :refer :all]
[tp.basic :refer :all]))
(deftest testPalabrasReservadas
(testing "Al Preguntarse Si Las Siguientes Palabras Son Reservadas El Resultado Es El Indicado"
(is (= false (palabra-reservada? 'SPACE)))
(is (= true (palabra-reservada? 'REM)))))
(deftest testOperadores
(testing "Al Preguntarse Si Las Siguientes Simbolos Son Operadores El Resultado Es El Indicado"
(is (= false (operador? (symbol "%"))))
(is (= true (operador? '+)))))
(deftest testVariableFloat
(testing "Al preguntarse si la variable es del tipo float se devuelve el resultado correcto"
(is (= false (variable-float? 'X%)))
(is (= false (variable-float? 'X$)))
(is (= true (variable-float? 'X)))))
(deftest testVariableInteger
(testing "Al preguntarse si la variable es del tipo integer se devuelve el resultado correcto"
(is (= true (variable-integer? 'X%)))
(is (= false (variable-integer? 'X$)))
(is (= false (variable-integer? 'X)))))
(deftest testVariableString
(testing "Al preguntarse si la variable es del tipo string se devuelve el resultado correcto"
(is (= false (variable-string? 'X%)))
(is (= true (variable-string? 'X$)))
(is (= false (variable-string? 'X)))))
(deftest testeliminarCeroDecimal
(testing "Al eliminar el cero decimal de los siguientes ejemplos el valor es el esperado"
(is (= 1.5 (eliminar-cero-decimal 1.5)))
(is (= 'A (eliminar-cero-decimal 'A)))
(is (= 1 (eliminar-cero-decimal 1.0)))
(is (= 1.5 (eliminar-cero-decimal 1.50)))))
(deftest testeliminarCeroEntero
(testing "Al eliminar el cero entero de los siguientes ejemplos el valor es el esperado"
(is (= nil (eliminar-cero-entero nil)))
(is (= "A" (eliminar-cero-entero 'A)))
(is (= "0" (eliminar-cero-entero 0)))
(is (= "1.5" (eliminar-cero-entero 1.5)))
(is (= "1" (eliminar-cero-entero 1)))
(is (= "-1" (eliminar-cero-entero -1)))
(is (= "-1.5" (eliminar-cero-entero -1.5)))
(is (= ".5" (eliminar-cero-entero 0.5)))
(is (= "-.5" (eliminar-cero-entero -0.5)))))
(deftest test-anular-invalidos
(testing "Al ingresar una sentencia se anulan los invalidos"
(is (= '(IF X nil * Y < 12 THEN LET nil X = 0)
(anular-invalidos '(IF X & * Y < 12 THEN LET ! X = 0))))))
(deftest test-cargar-linea
(testing "Al recibir una linea de codigo y un ambiente retorna el ambiente correctamente actualizado"
(is (= '[((10 (PRINT X))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(10 (PRINT X)) [() [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(20 (X = 100)) ['((10 (PRINT X))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (15 (X = X + 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(15 (X = X + 1)) ['((10 (PRINT X)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X)) (15 (X = X - 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}]
(cargar-linea '(15 (X = X - 1)) ['((10 (PRINT X)) (15 (X = X + 1)) (20 (X = 100))) [:ejecucion-inmediata 0] [] [] [] 0 {}])))))
(deftest test-eliminar-rem
(testing "Al recibir una representacion intermedia elimina las sentencias REM correctamente"
(is (= '((10 (PRINT X)) (20 (DATA HOLA)) (100 (DATA MUNDO , 10 , 20)))
(eliminar-rem '((10 (PRINT X) (REM ESTE NO) (DATA 30)) (20 (DATA HOLA)) (100 (DATA MUNDO , 10 , 20))))))
(is (= '((10 (PRINT X) (DATA 30)) (20) (100 (DATA MUNDO , 10 , 20)))
(eliminar-rem '((10 (PRINT X) (DATA 30)) (20 (REM HOLA)) (100 (DATA MUNDO , 10 , 20))))))))
(deftest test-expandir-nexts
(testing "Al recibir una secuencia de sentencias expande los nexts correctamente"
(is (= '((PRINT 1) (NEXT A) (NEXT B))
(expandir-nexts (list '(PRINT 1) (list 'NEXT 'A (symbol ",") 'B)))))
(is (= '(10 (PRINT X) (NEXT A))
(expandir-nexts (list 10 '(PRINT X) '(NEXT A)))))
(is (= '(10 (PRINT X) (PRINT Y))
(expandir-nexts '(10 (PRINT X) (PRINT Y)))))
(is (= '(10 (PRINT Y) (NEXT A) (DATA HOLA))
(expandir-nexts '(10 (PRINT Y) (NEXT A) (DATA HOLA)))))
(is (= '(10 (PRINT Y) (NEXT A) (NEXT B) (DATA HOLA))
(expandir-nexts (list 10 '(PRINT Y) (list 'NEXT 'A (symbol ",") 'B) '(DATA HOLA)))))
(is (= '((NEXT A) (NEXT B) (PRINT 1))
(expandir-nexts (list (list 'NEXT 'A (symbol ",") 'B) '(PRINT 1)))))
(is (= '((NEXT A) (PRINT 1))
(expandir-nexts '((NEXT A) (PRINT 1)))))))
(deftest test-contar-sentencias
(testing "Al recibir un nro-linea y un amb cuenta las sentencias de esa linea correctamente"
(is (= 2
(contar-sentencias 10 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= 1
(contar-sentencias 15 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= 2
(contar-sentencias 20 [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))))
(deftest test-buscar-lineas-restantes
(testing "Al recibir un ambiente devuelve una lista con las lineas restantes de la siguiente forma"
(is (= nil
(buscar-lineas-restantes [() [:ejecucion-inmediata 0] [] [] [] 0 {}])))
(is (= nil
(buscar-lineas-restantes ['((PRINT X) (PRINT Y)) [:ejecucion-inmediata 2] [] [] [] 0 {}])))
(is (= (list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 2] [] [] [] 0 {}])))
(is (= (list '(10 (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 1] [] [] [] 0 {}])))
(is (= (list '(10) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [10 0] [] [] [] 0 {}])))
(is (= (list '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 1] [] [] [] 0 {}])))
(is (= (list '(15) (list 20 (list 'NEXT 'I (symbol ",") 'J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 0] [] [] [] 0 {}])))
(is (= '((20 (NEXT I) (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}])))
(is (= '((20 (NEXT I) (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 2] [] [] [] 0 {}])))
(is (= '((20 (NEXT J)))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 1] [] [] [] 0 {}])))
(is (= '((20))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 0] [] [] [] 0 {}])))
(is (= '((20))
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 -1] [] [] [] 0 {}])))
(is (= nil
(buscar-lineas-restantes [(list '(10 (PRINT X) (PRINT Y)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [25 0] [] [] [] 0 {}])))))
(deftest test-preprocesar-expresion
(testing "Al recibir una expresion y el ambiente remplaza correctamente los valores"
(is (= '("HOLA" + " PI:NAME:<NAME>END_PI" + "")
(preprocesar-expresion '(X$ + " MUNDO" + Z$) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X$ "HOLA"}])))
(is (= '(5 + 0 / 2 * 0)
(preprocesar-expresion '(X + . / Y% * Z) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 5 Y% 2}])))))
(deftest test-desambiguar
(testing "Al desambiguar las siguientes expresiones el resultado es correcto"
(is (= (list '-u 2 '* (symbol "(") '-u 3 '+ 5 '- (symbol "(") 2 '/ 7 (symbol ")") (symbol ")"))
(desambiguar (list '- 2 '* (symbol "(") '- 3 '+ 5 '- (symbol "(") '+ 2 '/ 7 (symbol ")") (symbol ")")))))
(is (= (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ")")))))
(is (= (list 'MID3$ (symbol "(") 1 (symbol ",") 2 (symbol ",") 3 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") 2 (symbol ",") 3 (symbol ")")))))
(is (= (list 'MID3$ (symbol "(") 1 (symbol ",") '-u 2 '+ 'K (symbol ",") 3 (symbol ")"))
(desambiguar (list 'MID$ (symbol "(") 1 (symbol ",") '- 2 '+ 'K (symbol ",") 3 (symbol ")")))))))
(deftest test-ejecutar-asignacion
(testing "Al recibir una asignacion y un amb y devuelve el amb actualizado"
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 5}]
(ejecutar-asignacion '(X = 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 {}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 5}]
(ejecutar-asignacion '(X = 5) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X 3}]
(ejecutar-asignacion '(X = X + 1) ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X 2}])))
(is (= '[((10 (PRINT X))) [10 1] [] [] [] 0 {X$ "HOLA MUNDO"}]
(ejecutar-asignacion '(X$ = X$ + " MUNDO") ['((10 (PRINT X))) [10 1] [] [] [] 0 '{X$ "HOLA"}])))))
(deftest test-continuar-linea
(testing "Al recibir un amb devuelve el resultado correcto"
(is (= [nil [(list '(10 (PRINT X)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}]]
(continuar-linea [(list '(10 (PRINT X)) '(15 (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [] [] [] 0 {}])))
(is (= [:omitir-restante [(list '(10 (PRINT X)) '(15 (GOSUB 100) (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [15 1] [] [] [] 0 {}]]
(continuar-linea [(list '(10 (PRINT X)) '(15 (GOSUB 100) (X = X + 1)) (list 20 (list 'NEXT 'I (symbol ",") 'J))) [20 3] [[15 2]] [] [] 0 {}])))))
(deftest test-aridad
(testing "Al recibir las sentencias correspondientes devuelve la aridad correcta"
(is (= 0
(aridad 'THEN)))
(is (= 1
(aridad 'SIN)))
(is (= 2
(aridad '*)))
(is (= 2
(aridad 'MID$)))
(is (= 3
(aridad 'MID3$)))))
|
[
{
"context": " :all]))\n\n(def request {:path \"/greetings\" :body \"Mike,Joe,John,Steve\"})\n\n(defn makeRequest [] \n (tinyweb-instance req",
"end": 294,
"score": 0.8793648481369019,
"start": 275,
"tag": "NAME",
"value": "Mike,Joe,John,Steve"
}
] |
src/test/clojure/com/github/dwiechert/clojure/tinyweb/exampleTest.clj
|
DWiechert/functional-programming-patterns
| 0 |
(ns com.github.dwiechert.clojure.tinyweb.exampleTest
(:require [clojure.test :refer :all])
(:require [com.github.dwiechert.clojure.tinyweb.core :refer :all])
(:require [com.github.dwiechert.clojure.tinyweb.example :refer :all]))
(def request {:path "/greetings" :body "Mike,Joe,John,Steve"})
(defn makeRequest []
(tinyweb-instance request))
(deftest test
(testing "Tinyweb"
(let [response (makeRequest)]
(is (= 200 (response :status-code)))
(not (= "" (response :body))))))
|
116647
|
(ns com.github.dwiechert.clojure.tinyweb.exampleTest
(:require [clojure.test :refer :all])
(:require [com.github.dwiechert.clojure.tinyweb.core :refer :all])
(:require [com.github.dwiechert.clojure.tinyweb.example :refer :all]))
(def request {:path "/greetings" :body "<NAME>"})
(defn makeRequest []
(tinyweb-instance request))
(deftest test
(testing "Tinyweb"
(let [response (makeRequest)]
(is (= 200 (response :status-code)))
(not (= "" (response :body))))))
| true |
(ns com.github.dwiechert.clojure.tinyweb.exampleTest
(:require [clojure.test :refer :all])
(:require [com.github.dwiechert.clojure.tinyweb.core :refer :all])
(:require [com.github.dwiechert.clojure.tinyweb.example :refer :all]))
(def request {:path "/greetings" :body "PI:NAME:<NAME>END_PI"})
(defn makeRequest []
(tinyweb-instance request))
(deftest test
(testing "Tinyweb"
(let [response (makeRequest)]
(is (= 200 (response :status-code)))
(not (= "" (response :body))))))
|
[
{
"context": "-text \"grimm\"))\n\n;; Complete Sherlock Holmes\n;; by Arthur Conan Doyle\n(def sherlock-text (get-text \"sherlock\"))\n\n;; Les",
"end": 492,
"score": 0.9999096989631653,
"start": 474,
"tag": "NAME",
"value": "Arthur Conan Doyle"
},
{
"context": "xt (get-text \"sherlock\"))\n\n;; Les Miserables\n;; by Victor Hugo\n;; Translated by Isabel F. Hapgood\n(def les-mis-t",
"end": 571,
"score": 0.9999051094055176,
"start": 560,
"tag": "NAME",
"value": "Victor Hugo"
},
{
"context": " Les Miserables\n;; by Victor Hugo\n;; Translated by Isabel F. Hapgood\n(def les-mis-text (get-text \"les_mis\"))\n\n;; Metam",
"end": 606,
"score": 0.9999032020568848,
"start": 589,
"tag": "NAME",
"value": "Isabel F. Hapgood"
},
{
"context": "text (get-text \"les_mis\"))\n\n;; Metamorphosis\n;; by Franz Kafka\n(def metamorphosis-text (get-text \"metamorphosis\"",
"end": 682,
"score": 0.9998978972434998,
"start": 671,
"tag": "NAME",
"value": "Franz Kafka"
},
{
"context": "t (get-text \"metamorphosis\"))\n\n;; The Prince\n;; by Nicolo Machiavelli\n(def prince-text (get-text \"prince\"))\n\n;; The Adv",
"end": 774,
"score": 0.9999043941497803,
"start": 756,
"tag": "NAME",
"value": "Nicolo Machiavelli"
},
{
"context": " \"prince\"))\n\n;; The Adventures of Tom Sawyer\n;; by Mark Twain (Samuel Clemens)\n(def tom-sawyer-text (get-text \"",
"end": 862,
"score": 0.9999014735221863,
"start": 852,
"tag": "NAME",
"value": "Mark Twain"
},
{
"context": ";; The Adventures of Tom Sawyer\n;; by Mark Twain (Samuel Clemens)\n(def tom-sawyer-text (get-text \"tom_sawyer\"))\n\n;",
"end": 878,
"score": 0.9998095631599426,
"start": 864,
"tag": "NAME",
"value": "Samuel Clemens"
},
{
"context": "er\"))\n\n;; The Adventures of Huckleberry Finn\n;; by Mark Twain (Samuel Clemens)\n(def huck-finn-text (get-text \"h",
"end": 981,
"score": 0.9998846054077148,
"start": 971,
"tag": "NAME",
"value": "Mark Twain"
},
{
"context": " Adventures of Huckleberry Finn\n;; by Mark Twain (Samuel Clemens)\n(def huck-finn-text (get-text \"huck_finn\"))\n\n;; ",
"end": 997,
"score": 0.9997345209121704,
"start": 983,
"tag": "NAME",
"value": "Samuel Clemens"
}
] |
src/clj/exploring_data/classics.clj
|
KevinGreene/exploring-data
| 1 |
(ns exploring-data.classics
(:require [opennlp.nlp :as nlp]
[opennlp.treebank :as treebank]
[stemmers.core]
[stemmers.porter]
[incanter.stats :refer [levenshtein-distance]]))
(defn get-text [name]
(-> (str "resources/writings/" name ".txt")
(slurp)
(clojure.string/replace #"\r\n" " ")))
;; Complete Fairy Tales
;; by the Brothers Grimm
(def grimm-text (get-text "grimm"))
;; Complete Sherlock Holmes
;; by Arthur Conan Doyle
(def sherlock-text (get-text "sherlock"))
;; Les Miserables
;; by Victor Hugo
;; Translated by Isabel F. Hapgood
(def les-mis-text (get-text "les_mis"))
;; Metamorphosis
;; by Franz Kafka
(def metamorphosis-text (get-text "metamorphosis"))
;; The Prince
;; by Nicolo Machiavelli
(def prince-text (get-text "prince"))
;; The Adventures of Tom Sawyer
;; by Mark Twain (Samuel Clemens)
(def tom-sawyer-text (get-text "tom_sawyer"))
;; The Adventures of Huckleberry Finn
;; by Mark Twain (Samuel Clemens)
(def huck-finn-text (get-text "huck_finn"))
;; Consider typing word for word what is said
;; or pulling your favorite script or book off the internet
;; Try Project Gutenberg
;; Some basic functions based on the given training data
;; Parses sentences from a given text
(def get-sentences (nlp/make-sentence-detector "resources/nlp_data/en-sent.bin"))
(comment
;; It's a fairly inexpensive function
;; But can have some trouble with things that aren't prose
(take 100 (get-sentences sherlock-text))
)
;; Parses strings (tokens) from a given text
(def tokenize (nlp/make-tokenizer "resources/nlp_data/en-token.bin"))
(comment
(tokenize "Here is an example")
;; Note that periods are separate
;; And this takes more than the amount of time you really need for the first ten
(take 10 (tokenize sherlock-text))
;; We can just take the 100 characters or so of Sherlock
;; As it has short tokens
(->> (take 100 sherlock-text)
(apply str)
(tokenize)
(take 10))
)
;; Tag a list of tokens with the presumed type
;; Types can be found here: http://www.clips.ua.ac.be/pages/mbsp-tags
(def pos-tag (nlp/make-pos-tagger "resources/nlp_data/en-pos-maxent.bin"))
(comment
(pos-tag (tokenize "This is a test sentence to demonstrate part of speech tagging."))
)
;; Determine what, in a list of tokens, are likely Proper Names
(def name-find (nlp/make-name-finder "resources/nlp_data/en-ner-person.bin"))
;; Chunk the functions into phrases
;; Chunk tags can be found here: http://www.clips.ua.ac.be/pages/mbsp-tags
(def chunker (treebank/make-treebank-chunker "resources/nlp_data/en-chunker.bin"))
;; Function to check for various frequencies
(defn get-frequency-wordtypes [text]
(->> (tokenize text)
(pos-tag)
(map second)
(frequencies)))
(comment
(def sherlock-frequency (get-frequency-wordtypes sherlock-text))
;; Can't always trust pos-tag
(meta (pos-tag (tokenize "Verbing nouns weirds language")))
;; Try with various speech I've said, you've said, or random discussions
;; Note: People get surprisingly defensive when you tell them they talk in a way
;; that isn't parsed correctly
(let [this-thing (chunker (pos-tag (tokenize "So, we'll try a different example. In which we hope things are adequately complex.")))
meta-thing (:probabilities (meta this-thing))]
(map vector this-thing meta-thing))
)
(comment
;; We can use stemmers to get to the essence of the word
;; Good for searching
(stemmers.core/stems (seq (take 10 (tokenize (apply str (take 5000 sherlock-text))))))
;; We can use the levenshtein distance for similarities
;; Good for typos
(levenshtein-distance "kitten" "mittens")
)
|
56686
|
(ns exploring-data.classics
(:require [opennlp.nlp :as nlp]
[opennlp.treebank :as treebank]
[stemmers.core]
[stemmers.porter]
[incanter.stats :refer [levenshtein-distance]]))
(defn get-text [name]
(-> (str "resources/writings/" name ".txt")
(slurp)
(clojure.string/replace #"\r\n" " ")))
;; Complete Fairy Tales
;; by the Brothers Grimm
(def grimm-text (get-text "grimm"))
;; Complete Sherlock Holmes
;; by <NAME>
(def sherlock-text (get-text "sherlock"))
;; Les Miserables
;; by <NAME>
;; Translated by <NAME>
(def les-mis-text (get-text "les_mis"))
;; Metamorphosis
;; by <NAME>
(def metamorphosis-text (get-text "metamorphosis"))
;; The Prince
;; by <NAME>
(def prince-text (get-text "prince"))
;; The Adventures of Tom Sawyer
;; by <NAME> (<NAME>)
(def tom-sawyer-text (get-text "tom_sawyer"))
;; The Adventures of Huckleberry Finn
;; by <NAME> (<NAME>)
(def huck-finn-text (get-text "huck_finn"))
;; Consider typing word for word what is said
;; or pulling your favorite script or book off the internet
;; Try Project Gutenberg
;; Some basic functions based on the given training data
;; Parses sentences from a given text
(def get-sentences (nlp/make-sentence-detector "resources/nlp_data/en-sent.bin"))
(comment
;; It's a fairly inexpensive function
;; But can have some trouble with things that aren't prose
(take 100 (get-sentences sherlock-text))
)
;; Parses strings (tokens) from a given text
(def tokenize (nlp/make-tokenizer "resources/nlp_data/en-token.bin"))
(comment
(tokenize "Here is an example")
;; Note that periods are separate
;; And this takes more than the amount of time you really need for the first ten
(take 10 (tokenize sherlock-text))
;; We can just take the 100 characters or so of Sherlock
;; As it has short tokens
(->> (take 100 sherlock-text)
(apply str)
(tokenize)
(take 10))
)
;; Tag a list of tokens with the presumed type
;; Types can be found here: http://www.clips.ua.ac.be/pages/mbsp-tags
(def pos-tag (nlp/make-pos-tagger "resources/nlp_data/en-pos-maxent.bin"))
(comment
(pos-tag (tokenize "This is a test sentence to demonstrate part of speech tagging."))
)
;; Determine what, in a list of tokens, are likely Proper Names
(def name-find (nlp/make-name-finder "resources/nlp_data/en-ner-person.bin"))
;; Chunk the functions into phrases
;; Chunk tags can be found here: http://www.clips.ua.ac.be/pages/mbsp-tags
(def chunker (treebank/make-treebank-chunker "resources/nlp_data/en-chunker.bin"))
;; Function to check for various frequencies
(defn get-frequency-wordtypes [text]
(->> (tokenize text)
(pos-tag)
(map second)
(frequencies)))
(comment
(def sherlock-frequency (get-frequency-wordtypes sherlock-text))
;; Can't always trust pos-tag
(meta (pos-tag (tokenize "Verbing nouns weirds language")))
;; Try with various speech I've said, you've said, or random discussions
;; Note: People get surprisingly defensive when you tell them they talk in a way
;; that isn't parsed correctly
(let [this-thing (chunker (pos-tag (tokenize "So, we'll try a different example. In which we hope things are adequately complex.")))
meta-thing (:probabilities (meta this-thing))]
(map vector this-thing meta-thing))
)
(comment
;; We can use stemmers to get to the essence of the word
;; Good for searching
(stemmers.core/stems (seq (take 10 (tokenize (apply str (take 5000 sherlock-text))))))
;; We can use the levenshtein distance for similarities
;; Good for typos
(levenshtein-distance "kitten" "mittens")
)
| true |
(ns exploring-data.classics
(:require [opennlp.nlp :as nlp]
[opennlp.treebank :as treebank]
[stemmers.core]
[stemmers.porter]
[incanter.stats :refer [levenshtein-distance]]))
(defn get-text [name]
(-> (str "resources/writings/" name ".txt")
(slurp)
(clojure.string/replace #"\r\n" " ")))
;; Complete Fairy Tales
;; by the Brothers Grimm
(def grimm-text (get-text "grimm"))
;; Complete Sherlock Holmes
;; by PI:NAME:<NAME>END_PI
(def sherlock-text (get-text "sherlock"))
;; Les Miserables
;; by PI:NAME:<NAME>END_PI
;; Translated by PI:NAME:<NAME>END_PI
(def les-mis-text (get-text "les_mis"))
;; Metamorphosis
;; by PI:NAME:<NAME>END_PI
(def metamorphosis-text (get-text "metamorphosis"))
;; The Prince
;; by PI:NAME:<NAME>END_PI
(def prince-text (get-text "prince"))
;; The Adventures of Tom Sawyer
;; by PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)
(def tom-sawyer-text (get-text "tom_sawyer"))
;; The Adventures of Huckleberry Finn
;; by PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)
(def huck-finn-text (get-text "huck_finn"))
;; Consider typing word for word what is said
;; or pulling your favorite script or book off the internet
;; Try Project Gutenberg
;; Some basic functions based on the given training data
;; Parses sentences from a given text
(def get-sentences (nlp/make-sentence-detector "resources/nlp_data/en-sent.bin"))
(comment
;; It's a fairly inexpensive function
;; But can have some trouble with things that aren't prose
(take 100 (get-sentences sherlock-text))
)
;; Parses strings (tokens) from a given text
(def tokenize (nlp/make-tokenizer "resources/nlp_data/en-token.bin"))
(comment
(tokenize "Here is an example")
;; Note that periods are separate
;; And this takes more than the amount of time you really need for the first ten
(take 10 (tokenize sherlock-text))
;; We can just take the 100 characters or so of Sherlock
;; As it has short tokens
(->> (take 100 sherlock-text)
(apply str)
(tokenize)
(take 10))
)
;; Tag a list of tokens with the presumed type
;; Types can be found here: http://www.clips.ua.ac.be/pages/mbsp-tags
(def pos-tag (nlp/make-pos-tagger "resources/nlp_data/en-pos-maxent.bin"))
(comment
(pos-tag (tokenize "This is a test sentence to demonstrate part of speech tagging."))
)
;; Determine what, in a list of tokens, are likely Proper Names
(def name-find (nlp/make-name-finder "resources/nlp_data/en-ner-person.bin"))
;; Chunk the functions into phrases
;; Chunk tags can be found here: http://www.clips.ua.ac.be/pages/mbsp-tags
(def chunker (treebank/make-treebank-chunker "resources/nlp_data/en-chunker.bin"))
;; Function to check for various frequencies
(defn get-frequency-wordtypes [text]
(->> (tokenize text)
(pos-tag)
(map second)
(frequencies)))
(comment
(def sherlock-frequency (get-frequency-wordtypes sherlock-text))
;; Can't always trust pos-tag
(meta (pos-tag (tokenize "Verbing nouns weirds language")))
;; Try with various speech I've said, you've said, or random discussions
;; Note: People get surprisingly defensive when you tell them they talk in a way
;; that isn't parsed correctly
(let [this-thing (chunker (pos-tag (tokenize "So, we'll try a different example. In which we hope things are adequately complex.")))
meta-thing (:probabilities (meta this-thing))]
(map vector this-thing meta-thing))
)
(comment
;; We can use stemmers to get to the essence of the word
;; Good for searching
(stemmers.core/stems (seq (take 10 (tokenize (apply str (take 5000 sherlock-text))))))
;; We can use the levenshtein distance for similarities
;; Good for typos
(levenshtein-distance "kitten" "mittens")
)
|
[
{
"context": ";; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and\n;; distri",
"end": 30,
"score": 0.9998567700386047,
"start": 17,
"tag": "NAME",
"value": "Stuart Sierra"
}
] |
output/conjure_deps/toolsnamespace/v0v3v1/clojure/tools/namespace/parse.cljc
|
Olical/conjure-deps
| 4 |
;; Copyright (c) Stuart Sierra, 2012. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.parse
(:require #?(:clj [conjure-deps.toolsreader.v1v3v2.clojure.tools.reader :as reader]
:cljs [conjure-deps.toolsreader.v1v3v2.cljs.tools.reader :as reader])
[clojure.set :as set]))
(defn comment?
"Returns true if form is a (comment ...)"
[form]
(and (list? form) (= 'comment (first form))))
(defn ns-decl?
"Returns true if form is a (ns ...) declaration."
[form]
(and (list? form) (= 'ns (first form))))
(def clj-read-opts
"Map of options for tools.reader/read allowing reader conditionals
with the :clj feature enabled."
{:read-cond :allow
:features #{:clj}})
(def cljs-read-opts
"Map of options for tools.reader/read allowing reader conditionals
with the :cljs feature enabled."
{:read-cond :allow
:features #{:cljs}})
(defn read-ns-decl
"Attempts to read a (ns ...) declaration from a reader, and returns
the unevaluated form. Returns the first top-level ns form found.
Returns nil if ns declaration cannot be found. Throws exception on
invalid syntax.
Note that read can execute code (controlled by
tools.reader/*read-eval*), and as such should be used only with
trusted sources. read-opts is passed through to tools.reader/read,
defaults to clj-read-opts"
([rdr]
(read-ns-decl rdr nil))
([rdr read-opts]
(let [opts (assoc (or read-opts clj-read-opts)
:eof ::eof)]
(loop []
(let [form (reader/read opts rdr)]
(cond
(ns-decl? form) form
(= ::eof form) nil
:else (recur)))))))
;;; Parsing dependencies
(defn- prefix-spec?
"Returns true if form represents a libspec prefix list like
(prefix name1 name1) or [com.example.prefix [name1 :as name1]]"
[form]
(and (sequential? form) ; should be a list, but often is not
(symbol? (first form))
(not-any? keyword? form)
(< 1 (count form)))) ; not a bare vector like [foo]
(defn- option-spec?
"Returns true if form represents a libspec vector containing optional
keyword arguments like [namespace :as alias] or
[namespace :refer (x y)] or just [namespace]"
[form]
(and (sequential? form) ; should be a vector, but often is not
(symbol? (first form))
(or (keyword? (second form)) ; vector like [foo :as f]
(= 1 (count form))))) ; bare vector like [foo]
(defn- deps-from-libspec [prefix form]
(cond (prefix-spec? form)
(mapcat (fn [f] (deps-from-libspec
(symbol (str (when prefix (str prefix "."))
(first form)))
f))
(rest form))
(option-spec? form)
(deps-from-libspec prefix (first form))
(symbol? form)
(list (symbol (str (when prefix (str prefix ".")) form)))
(keyword? form) ; Some people write (:require ... :reload-all)
nil
:else
(throw (ex-info "Unparsable namespace form"
{:reason ::unparsable-ns-form
:form form}))))
(def ^:private ns-clause-head-names
"Set of symbol/keyword names which can appear as the head of a
clause in the ns form."
#{"use" "require"})
(def ^:private ns-clause-heads
"Set of all symbols and keywords which can appear at the head of a
dependency clause in the ns form."
(set (mapcat (fn [name] (list (keyword name)
(symbol name)))
ns-clause-head-names)))
(defn- deps-from-ns-form [form]
(when (and (sequential? form) ; should be list but sometimes is not
(contains? ns-clause-heads (first form)))
(mapcat #(deps-from-libspec nil %) (rest form))))
(defn name-from-ns-decl
"Given an (ns...) declaration form (unevaluated), returns the name
of the namespace as a symbol."
[decl]
(second decl))
(defn deps-from-ns-decl
"Given an (ns...) declaration form (unevaluated), returns a set of
symbols naming the dependencies of that namespace. Handles :use and
:require clauses but not :load."
[decl]
(set (mapcat deps-from-ns-form decl)))
|
72056
|
;; Copyright (c) <NAME>, 2012. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.parse
(:require #?(:clj [conjure-deps.toolsreader.v1v3v2.clojure.tools.reader :as reader]
:cljs [conjure-deps.toolsreader.v1v3v2.cljs.tools.reader :as reader])
[clojure.set :as set]))
(defn comment?
"Returns true if form is a (comment ...)"
[form]
(and (list? form) (= 'comment (first form))))
(defn ns-decl?
"Returns true if form is a (ns ...) declaration."
[form]
(and (list? form) (= 'ns (first form))))
(def clj-read-opts
"Map of options for tools.reader/read allowing reader conditionals
with the :clj feature enabled."
{:read-cond :allow
:features #{:clj}})
(def cljs-read-opts
"Map of options for tools.reader/read allowing reader conditionals
with the :cljs feature enabled."
{:read-cond :allow
:features #{:cljs}})
(defn read-ns-decl
"Attempts to read a (ns ...) declaration from a reader, and returns
the unevaluated form. Returns the first top-level ns form found.
Returns nil if ns declaration cannot be found. Throws exception on
invalid syntax.
Note that read can execute code (controlled by
tools.reader/*read-eval*), and as such should be used only with
trusted sources. read-opts is passed through to tools.reader/read,
defaults to clj-read-opts"
([rdr]
(read-ns-decl rdr nil))
([rdr read-opts]
(let [opts (assoc (or read-opts clj-read-opts)
:eof ::eof)]
(loop []
(let [form (reader/read opts rdr)]
(cond
(ns-decl? form) form
(= ::eof form) nil
:else (recur)))))))
;;; Parsing dependencies
(defn- prefix-spec?
"Returns true if form represents a libspec prefix list like
(prefix name1 name1) or [com.example.prefix [name1 :as name1]]"
[form]
(and (sequential? form) ; should be a list, but often is not
(symbol? (first form))
(not-any? keyword? form)
(< 1 (count form)))) ; not a bare vector like [foo]
(defn- option-spec?
"Returns true if form represents a libspec vector containing optional
keyword arguments like [namespace :as alias] or
[namespace :refer (x y)] or just [namespace]"
[form]
(and (sequential? form) ; should be a vector, but often is not
(symbol? (first form))
(or (keyword? (second form)) ; vector like [foo :as f]
(= 1 (count form))))) ; bare vector like [foo]
(defn- deps-from-libspec [prefix form]
(cond (prefix-spec? form)
(mapcat (fn [f] (deps-from-libspec
(symbol (str (when prefix (str prefix "."))
(first form)))
f))
(rest form))
(option-spec? form)
(deps-from-libspec prefix (first form))
(symbol? form)
(list (symbol (str (when prefix (str prefix ".")) form)))
(keyword? form) ; Some people write (:require ... :reload-all)
nil
:else
(throw (ex-info "Unparsable namespace form"
{:reason ::unparsable-ns-form
:form form}))))
(def ^:private ns-clause-head-names
"Set of symbol/keyword names which can appear as the head of a
clause in the ns form."
#{"use" "require"})
(def ^:private ns-clause-heads
"Set of all symbols and keywords which can appear at the head of a
dependency clause in the ns form."
(set (mapcat (fn [name] (list (keyword name)
(symbol name)))
ns-clause-head-names)))
(defn- deps-from-ns-form [form]
(when (and (sequential? form) ; should be list but sometimes is not
(contains? ns-clause-heads (first form)))
(mapcat #(deps-from-libspec nil %) (rest form))))
(defn name-from-ns-decl
"Given an (ns...) declaration form (unevaluated), returns the name
of the namespace as a symbol."
[decl]
(second decl))
(defn deps-from-ns-decl
"Given an (ns...) declaration form (unevaluated), returns a set of
symbols naming the dependencies of that namespace. Handles :use and
:require clauses but not :load."
[decl]
(set (mapcat deps-from-ns-form decl)))
| true |
;; Copyright (c) PI:NAME:<NAME>END_PI, 2012. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(ns conjure-deps.toolsnamespace.v0v3v1.clojure.tools.namespace.parse
(:require #?(:clj [conjure-deps.toolsreader.v1v3v2.clojure.tools.reader :as reader]
:cljs [conjure-deps.toolsreader.v1v3v2.cljs.tools.reader :as reader])
[clojure.set :as set]))
(defn comment?
"Returns true if form is a (comment ...)"
[form]
(and (list? form) (= 'comment (first form))))
(defn ns-decl?
"Returns true if form is a (ns ...) declaration."
[form]
(and (list? form) (= 'ns (first form))))
(def clj-read-opts
"Map of options for tools.reader/read allowing reader conditionals
with the :clj feature enabled."
{:read-cond :allow
:features #{:clj}})
(def cljs-read-opts
"Map of options for tools.reader/read allowing reader conditionals
with the :cljs feature enabled."
{:read-cond :allow
:features #{:cljs}})
(defn read-ns-decl
"Attempts to read a (ns ...) declaration from a reader, and returns
the unevaluated form. Returns the first top-level ns form found.
Returns nil if ns declaration cannot be found. Throws exception on
invalid syntax.
Note that read can execute code (controlled by
tools.reader/*read-eval*), and as such should be used only with
trusted sources. read-opts is passed through to tools.reader/read,
defaults to clj-read-opts"
([rdr]
(read-ns-decl rdr nil))
([rdr read-opts]
(let [opts (assoc (or read-opts clj-read-opts)
:eof ::eof)]
(loop []
(let [form (reader/read opts rdr)]
(cond
(ns-decl? form) form
(= ::eof form) nil
:else (recur)))))))
;;; Parsing dependencies
(defn- prefix-spec?
"Returns true if form represents a libspec prefix list like
(prefix name1 name1) or [com.example.prefix [name1 :as name1]]"
[form]
(and (sequential? form) ; should be a list, but often is not
(symbol? (first form))
(not-any? keyword? form)
(< 1 (count form)))) ; not a bare vector like [foo]
(defn- option-spec?
"Returns true if form represents a libspec vector containing optional
keyword arguments like [namespace :as alias] or
[namespace :refer (x y)] or just [namespace]"
[form]
(and (sequential? form) ; should be a vector, but often is not
(symbol? (first form))
(or (keyword? (second form)) ; vector like [foo :as f]
(= 1 (count form))))) ; bare vector like [foo]
(defn- deps-from-libspec [prefix form]
(cond (prefix-spec? form)
(mapcat (fn [f] (deps-from-libspec
(symbol (str (when prefix (str prefix "."))
(first form)))
f))
(rest form))
(option-spec? form)
(deps-from-libspec prefix (first form))
(symbol? form)
(list (symbol (str (when prefix (str prefix ".")) form)))
(keyword? form) ; Some people write (:require ... :reload-all)
nil
:else
(throw (ex-info "Unparsable namespace form"
{:reason ::unparsable-ns-form
:form form}))))
(def ^:private ns-clause-head-names
"Set of symbol/keyword names which can appear as the head of a
clause in the ns form."
#{"use" "require"})
(def ^:private ns-clause-heads
"Set of all symbols and keywords which can appear at the head of a
dependency clause in the ns form."
(set (mapcat (fn [name] (list (keyword name)
(symbol name)))
ns-clause-head-names)))
(defn- deps-from-ns-form [form]
(when (and (sequential? form) ; should be list but sometimes is not
(contains? ns-clause-heads (first form)))
(mapcat #(deps-from-libspec nil %) (rest form))))
(defn name-from-ns-decl
"Given an (ns...) declaration form (unevaluated), returns the name
of the namespace as a symbol."
[decl]
(second decl))
(defn deps-from-ns-decl
"Given an (ns...) declaration form (unevaluated), returns a set of
symbols naming the dependencies of that namespace. Handles :use and
:require clauses but not :load."
[decl]
(set (mapcat deps-from-ns-form decl)))
|
[
{
"context": "Type \\\"Patient\\\"\n :name [{:family \\\"Doe\\\", :given [\\\"John\\\"]}]}}\n :match {:by sty/match",
"end": 1783,
"score": 0.999574601650238,
"start": 1780,
"tag": "NAME",
"value": "Doe"
},
{
"context": " :name [{:family \\\"Doe\\\", :given [\\\"John\\\"]}]}}\n :match {:by sty/matcho\n :stat",
"end": 1801,
"score": 0.9997749924659729,
"start": 1797,
"tag": "NAME",
"value": "John"
},
{
"context": "0\\\"\n ;; :basic-auth {:user \\\"user?\\\" :password \\\"password?\\\"}\n ;; :auth-token \\\"????\\\"\n }\n\n}\n\" ns))\n\n(defn",
"end": 2446,
"score": 0.9969696998596191,
"start": 2438,
"tag": "PASSWORD",
"value": "password"
}
] |
src/stresty/operations/gen.clj
|
HealthSamurai/stresty
| 22 |
(ns stresty.operations.gen
(:require [clojure.string :as str])
(:import
(java.io File)
(java.nio.file Files Path Paths OpenOption FileVisitOption LinkOption)
(java.nio.file.attribute FileAttribute)
(java.net URI)))
(set! *warn-on-reflection* true)
(defn get-path [ns]
(->> (str/split ns #"\.")
(into [])))
(comment
(get-path "aidbox.tests")
(Paths/get ".tmp" (into-array ["myproj" "ns"]))
(Files/createDirectories (Paths/get ".tmp" (into-array ["myproj" "ns"])) (into-array FileAttribute []))
(.toString (.toAbsolutePath (Paths/get ".tmp" (into-array ["myproj" "ns" "case.edn"]))))
(spit (.toString (.toAbsolutePath (Paths/get ".tmp" (into-array ["myproj" "ns" "case.edn"]))))
"{}"))
(defn path [home pth]
(Paths/get home (into-array String (into [] pth))))
(defn exists? [pth]
(Files/exists pth (into-array LinkOption [])))
(defn write [^Path pth content]
(let [file (.toString (.toAbsolutePath pth))]
(if (exists? pth)
(println "Skip generation! File" file "already exists.")
(spit file content))))
(defn mkdirs [^Path pth]
(Files/createDirectories pth (into-array FileAttribute [])))
(defn walk [^Path pth]
(when (exists? pth)
(iterator-seq (.iterator (Files/walk pth (into-array FileVisitOption []))))))
(defn rmdir [^Path pth]
(doseq [^Path p (->> (walk pth)
(sort-by (fn [^Path x] (.toAbsolutePath x)))
(reverse))]
(println "rm" p)
(.delete ^File (.toFile p))))
(defn gen-case [ns]
(format "{ns %s
import #{sty}
case
{:zen/tags #{sty/case}
:steps
[{:id :first-step
:desc \"Crate Patient\"
:do {:act sty/http
:method :post
:url \"/Patient\"
:body {:resourceType \"Patient\"
:name [{:family \"Doe\", :given [\"John\"]}]}}
:match {:by sty/matcho
:status sty/ok?
:body {:id sty/string?}}}
{:id :second-step
:do {:act sty/print
:path [:first-step :body]}}
{:id :third-step
:do {:act sty/http
:method :get
:url (str \"/Patient/\" (get-in sty/state [:first-step :body :id]))}
:match {:by sty/matcho
:status sty/ok?
:body {:name (get-in sty/state [:first-step :body :name])}}}
]}}" ns))
(defn gen-env [ns]
(format "
{ns envs
import #{
sty
%s
}
env
{:zen/tags #{sty/env}
:base-url \"http://localhost:8080\"
;; :basic-auth {:user \"user?\" :password \"password?\"}
;; :auth-token \"????\"
}
}
" ns))
(defn generate [ztx opts]
(println "Generate " opts)
(if-let [proj (:project opts)]
(let [home (get-in @ztx [:paths 0])
proj-path (get-path proj)
dir-path (path home proj-path)
env-path (path home ["envs.edn"])
case-path (path home (conj proj-path "case.edn"))]
(println "mkdirs" dir-path)
(mkdirs dir-path)
(println "create" (str (.toAbsolutePath ^Path case-path)))
(write case-path (gen-case (str proj ".case")))
(println "create" (str (.toAbsolutePath ^Path env-path)))
(write env-path (gen-env (str proj ".case"))))
(println "Parameter --project is required")))
|
46833
|
(ns stresty.operations.gen
(:require [clojure.string :as str])
(:import
(java.io File)
(java.nio.file Files Path Paths OpenOption FileVisitOption LinkOption)
(java.nio.file.attribute FileAttribute)
(java.net URI)))
(set! *warn-on-reflection* true)
(defn get-path [ns]
(->> (str/split ns #"\.")
(into [])))
(comment
(get-path "aidbox.tests")
(Paths/get ".tmp" (into-array ["myproj" "ns"]))
(Files/createDirectories (Paths/get ".tmp" (into-array ["myproj" "ns"])) (into-array FileAttribute []))
(.toString (.toAbsolutePath (Paths/get ".tmp" (into-array ["myproj" "ns" "case.edn"]))))
(spit (.toString (.toAbsolutePath (Paths/get ".tmp" (into-array ["myproj" "ns" "case.edn"]))))
"{}"))
(defn path [home pth]
(Paths/get home (into-array String (into [] pth))))
(defn exists? [pth]
(Files/exists pth (into-array LinkOption [])))
(defn write [^Path pth content]
(let [file (.toString (.toAbsolutePath pth))]
(if (exists? pth)
(println "Skip generation! File" file "already exists.")
(spit file content))))
(defn mkdirs [^Path pth]
(Files/createDirectories pth (into-array FileAttribute [])))
(defn walk [^Path pth]
(when (exists? pth)
(iterator-seq (.iterator (Files/walk pth (into-array FileVisitOption []))))))
(defn rmdir [^Path pth]
(doseq [^Path p (->> (walk pth)
(sort-by (fn [^Path x] (.toAbsolutePath x)))
(reverse))]
(println "rm" p)
(.delete ^File (.toFile p))))
(defn gen-case [ns]
(format "{ns %s
import #{sty}
case
{:zen/tags #{sty/case}
:steps
[{:id :first-step
:desc \"Crate Patient\"
:do {:act sty/http
:method :post
:url \"/Patient\"
:body {:resourceType \"Patient\"
:name [{:family \"<NAME>\", :given [\"<NAME>\"]}]}}
:match {:by sty/matcho
:status sty/ok?
:body {:id sty/string?}}}
{:id :second-step
:do {:act sty/print
:path [:first-step :body]}}
{:id :third-step
:do {:act sty/http
:method :get
:url (str \"/Patient/\" (get-in sty/state [:first-step :body :id]))}
:match {:by sty/matcho
:status sty/ok?
:body {:name (get-in sty/state [:first-step :body :name])}}}
]}}" ns))
(defn gen-env [ns]
(format "
{ns envs
import #{
sty
%s
}
env
{:zen/tags #{sty/env}
:base-url \"http://localhost:8080\"
;; :basic-auth {:user \"user?\" :password \"<PASSWORD>?\"}
;; :auth-token \"????\"
}
}
" ns))
(defn generate [ztx opts]
(println "Generate " opts)
(if-let [proj (:project opts)]
(let [home (get-in @ztx [:paths 0])
proj-path (get-path proj)
dir-path (path home proj-path)
env-path (path home ["envs.edn"])
case-path (path home (conj proj-path "case.edn"))]
(println "mkdirs" dir-path)
(mkdirs dir-path)
(println "create" (str (.toAbsolutePath ^Path case-path)))
(write case-path (gen-case (str proj ".case")))
(println "create" (str (.toAbsolutePath ^Path env-path)))
(write env-path (gen-env (str proj ".case"))))
(println "Parameter --project is required")))
| true |
(ns stresty.operations.gen
(:require [clojure.string :as str])
(:import
(java.io File)
(java.nio.file Files Path Paths OpenOption FileVisitOption LinkOption)
(java.nio.file.attribute FileAttribute)
(java.net URI)))
(set! *warn-on-reflection* true)
(defn get-path [ns]
(->> (str/split ns #"\.")
(into [])))
(comment
(get-path "aidbox.tests")
(Paths/get ".tmp" (into-array ["myproj" "ns"]))
(Files/createDirectories (Paths/get ".tmp" (into-array ["myproj" "ns"])) (into-array FileAttribute []))
(.toString (.toAbsolutePath (Paths/get ".tmp" (into-array ["myproj" "ns" "case.edn"]))))
(spit (.toString (.toAbsolutePath (Paths/get ".tmp" (into-array ["myproj" "ns" "case.edn"]))))
"{}"))
(defn path [home pth]
(Paths/get home (into-array String (into [] pth))))
(defn exists? [pth]
(Files/exists pth (into-array LinkOption [])))
(defn write [^Path pth content]
(let [file (.toString (.toAbsolutePath pth))]
(if (exists? pth)
(println "Skip generation! File" file "already exists.")
(spit file content))))
(defn mkdirs [^Path pth]
(Files/createDirectories pth (into-array FileAttribute [])))
(defn walk [^Path pth]
(when (exists? pth)
(iterator-seq (.iterator (Files/walk pth (into-array FileVisitOption []))))))
(defn rmdir [^Path pth]
(doseq [^Path p (->> (walk pth)
(sort-by (fn [^Path x] (.toAbsolutePath x)))
(reverse))]
(println "rm" p)
(.delete ^File (.toFile p))))
(defn gen-case [ns]
(format "{ns %s
import #{sty}
case
{:zen/tags #{sty/case}
:steps
[{:id :first-step
:desc \"Crate Patient\"
:do {:act sty/http
:method :post
:url \"/Patient\"
:body {:resourceType \"Patient\"
:name [{:family \"PI:NAME:<NAME>END_PI\", :given [\"PI:NAME:<NAME>END_PI\"]}]}}
:match {:by sty/matcho
:status sty/ok?
:body {:id sty/string?}}}
{:id :second-step
:do {:act sty/print
:path [:first-step :body]}}
{:id :third-step
:do {:act sty/http
:method :get
:url (str \"/Patient/\" (get-in sty/state [:first-step :body :id]))}
:match {:by sty/matcho
:status sty/ok?
:body {:name (get-in sty/state [:first-step :body :name])}}}
]}}" ns))
(defn gen-env [ns]
(format "
{ns envs
import #{
sty
%s
}
env
{:zen/tags #{sty/env}
:base-url \"http://localhost:8080\"
;; :basic-auth {:user \"user?\" :password \"PI:PASSWORD:<PASSWORD>END_PI?\"}
;; :auth-token \"????\"
}
}
" ns))
(defn generate [ztx opts]
(println "Generate " opts)
(if-let [proj (:project opts)]
(let [home (get-in @ztx [:paths 0])
proj-path (get-path proj)
dir-path (path home proj-path)
env-path (path home ["envs.edn"])
case-path (path home (conj proj-path "case.edn"))]
(println "mkdirs" dir-path)
(mkdirs dir-path)
(println "create" (str (.toAbsolutePath ^Path case-path)))
(write case-path (gen-case (str proj ".case")))
(println "create" (str (.toAbsolutePath ^Path env-path)))
(write env-path (gen-env (str proj ".case"))))
(println "Parameter --project is required")))
|
[
{
"context": " {:user [[:custom-user-1 {:spec-gen {:user-name \"Captain Crunch\"}}]\n [:custom-user-2 {:sp",
"end": 318,
"score": 0.9982316493988037,
"start": 304,
"tag": "NAME",
"value": "Captain Crunch"
}
] |
demo/src/specmonstah_demo/examples/queries.cljs
|
plexus/specmonstah
| 346 |
(ns specmonstah-demo.examples.queries
(:require [shadow.resource :as rc]))
(def queries
[{:name "specify usernames"
:description "Specmonstah generates a lot of data for you, but you have the power to customize any of it."
:query {:user [[:custom-user-1 {:spec-gen {:user-name "Captain Crunch"}}]
[:custom-user-2 {:spec-gen {:id 100}}]]}}
{:name "multiple ents"
:description "Generate 3 todos. Try generating more or fewer."
:query {:todo [[3]]}}
{:name ":coll constraint"
:description "Projects store multiple todo list ids under :todo-list-ids."
:query {:project [[:_ {:refs {:todo-list-ids 3}}]]}}
{:name ":uniq constraint"
:description "Users can't watch the same todo list twice. Therefore, when generating todo list watches, also generate unique todo lists to watch."
:query {:todo-list-watch [[3]]}}])
|
11130
|
(ns specmonstah-demo.examples.queries
(:require [shadow.resource :as rc]))
(def queries
[{:name "specify usernames"
:description "Specmonstah generates a lot of data for you, but you have the power to customize any of it."
:query {:user [[:custom-user-1 {:spec-gen {:user-name "<NAME>"}}]
[:custom-user-2 {:spec-gen {:id 100}}]]}}
{:name "multiple ents"
:description "Generate 3 todos. Try generating more or fewer."
:query {:todo [[3]]}}
{:name ":coll constraint"
:description "Projects store multiple todo list ids under :todo-list-ids."
:query {:project [[:_ {:refs {:todo-list-ids 3}}]]}}
{:name ":uniq constraint"
:description "Users can't watch the same todo list twice. Therefore, when generating todo list watches, also generate unique todo lists to watch."
:query {:todo-list-watch [[3]]}}])
| true |
(ns specmonstah-demo.examples.queries
(:require [shadow.resource :as rc]))
(def queries
[{:name "specify usernames"
:description "Specmonstah generates a lot of data for you, but you have the power to customize any of it."
:query {:user [[:custom-user-1 {:spec-gen {:user-name "PI:NAME:<NAME>END_PI"}}]
[:custom-user-2 {:spec-gen {:id 100}}]]}}
{:name "multiple ents"
:description "Generate 3 todos. Try generating more or fewer."
:query {:todo [[3]]}}
{:name ":coll constraint"
:description "Projects store multiple todo list ids under :todo-list-ids."
:query {:project [[:_ {:refs {:todo-list-ids 3}}]]}}
{:name ":uniq constraint"
:description "Users can't watch the same todo list twice. Therefore, when generating todo list watches, also generate unique todo lists to watch."
:query {:todo-list-watch [[3]]}}])
|
[
{
"context": "-ms 200)\n(def source-url \"https://github.com/dmotz/cellf\")\n(def home-url \"http://oxism.com\")\n(de",
"end": 515,
"score": 0.9909548163414001,
"start": 510,
"tag": "USERNAME",
"value": "dmotz"
},
{
"context": "me-url \"http://oxism.com\")\n(def ls-key \"cellf/ok\")\n(def canvas-ref \"capture-canvas\")\n(def video-",
"end": 589,
"score": 0.9990142583847046,
"start": 581,
"tag": "KEY",
"value": "cellf/ok"
},
{
"context": "t js/document \"canvas\")\n e-key \"oncanplay\"]\n (doto canvas\n (aset \"width\" ",
"end": 7934,
"score": 0.9964901804924011,
"start": 7925,
"tag": "KEY",
"value": "oncanplay"
}
] |
src/cellf/core.cljs
|
dmotz/cellf
| 7 |
(ns ^:figwheel-always cellf.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [<! >! take! put! alts! chan timeout]]
[cellf.media :as media]
[cellf.strings :refer [strings]])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
(enable-console-print!)
(def default-size 3)
(def capture-size 250)
(def tick-ms 150)
(def resize-ms 200)
(def source-url "https://github.com/dmotz/cellf")
(def home-url "http://oxism.com")
(def ls-key "cellf/ok")
(def canvas-ref "capture-canvas")
(def video-ref "vid")
(defonce img-cache (atom []))
(defn sq [n]
(* n n))
(defn t3d [x y]
(str "translate3d(" x "%," y "%,0)"))
(defn promise-chan []
(let [c (chan)]
(take!
c
#(go-loop []
(>! c %)
(recur)))
c))
(defn capture-move [{:keys [ctx vid-node canvas-node vid-w vid-h]} cells]
(.drawImage
ctx
vid-node
(/ (- vid-w vid-h) 2)
0
vid-h
vid-h
0
0
capture-size
capture-size)
(let [img-data (.toDataURL canvas-node "image/jpeg" 1)
img-el (js/Image.)
pc (promise-chan)]
(swap! img-cache conj pc)
(doto img-el
(aset "src" img-data)
(aset
"onload"
(fn []
(js-delete img-el "onload")
(put! pc img-el))))
{:cells cells :image img-data}))
(defn order [grid]
(->>
grid
(sort-by second)
(map first)))
(defn inversions [grid]
(let [cells (order grid)]
(->>
grid
count
range
(map
(fn [n]
(->>
cells
(drop n)
(filter #(< % (nth cells n)))
count)))
(reduce +))))
(defn blank-at-row [grid size]
(js/Math.floor (/ (:empty grid) size)))
(def solvable?
(memoize
(fn [grid size]
(let [even-inversions? (even? (inversions grid))]
(or
(and (odd? size) even-inversions?)
(and
(even? size)
(= even-inversions? (odd? (blank-at-row grid size)))))))))
(defn make-cell-list [size]
(->
size
sq
dec
range
vec
(conj :empty)))
(defn make-cells [size win-state]
(let [shuffled (zipmap (make-cell-list size) (shuffle (range (sq size))))]
(if (or
(= shuffled win-state)
(not (solvable? shuffled size)))
(recur size win-state)
shuffled)))
(defn make-win-state [size]
(zipmap (make-cell-list size) (range (sq size))))
(defn make-game
([app size]
(make-game app size tick-ms))
([app size speed]
(let [win-state (make-win-state size)
cells (make-cells size win-state)]
{:moves [(capture-move app cells)]
:tick 0
:tick-ms speed
:grid-size size
:cells cells
:win-state win-state})))
(def get-cell-xy (juxt mod quot))
(defn get-cell-style [app i]
(let [size (:grid-size app)
pct (str (/ 100 size) \%)
px (/ (:grid-px app) size)
[x y] (get-cell-xy i size)]
#js {:transform (t3d (* 100 x) (* 100 y))
:width pct
:height pct
:lineHeight (str px "px")
:fontSize (/ px 10)}))
(defn get-bg-transform [{:keys [grid-size vid-ratio vid-offset]} i]
(if (= i :empty)
nil
(let [size grid-size
pct (/ 100 size)
[x y] (get-cell-xy i size)]
#js {:height (str (* size 100) \%)
:transform (t3d
(- (+ (/ (* x pct) vid-ratio) vid-offset))
(- (* pct y)))})))
(defn adj? [app i]
(let [{size :grid-size {emp :empty} :cells} app
emp' (inc emp)]
(cond
(= i (- emp size)) \d
(= i (+ emp size)) \u
(and (= i emp') (pos? (mod emp' size))) \l
(and (= i (dec emp)) (pos? (mod emp size))) \r
:else false)))
(defn swap-cell [cells n]
(let [current-idx (cells n)
empty-idx (:empty cells)]
(into
{}
(map
(fn [[k idx]]
(if (= k :empty)
[:empty current-idx]
(if (= k n) [k empty-idx] [k idx])))
cells))))
(defn move! [{:keys [moves] :as app} n]
(let [new-layout (swap-cell (:cells app) n)]
(om/update! app :cells new-layout)
(om/update! app :moves (conj moves (capture-move app new-layout)))))
(defn new-game! [app size speed]
(reset! img-cache [])
(om/update! app (merge app (make-game app size speed))))
(defn set-vid-src [owner stream]
(aset (om/get-node owner video-ref) "srcObject" stream))
(defn cell [{:keys [stream n idx] :as app} owner]
(reify
om/IDidMount
(did-mount [_]
(when (not= n :empty)
(.setAttribute (om/get-node owner video-ref) "playsinline" "")
(set-vid-src owner stream)))
om/IDidUpdate
(did-update [_ prev-props _]
(when (and (not= n :empty) (not= n (:n prev-props)))
(set-vid-src owner stream)))
om/IRender
(render [_]
(when (not= n :empty)
(let [adj (adj? app idx)]
(dom/div
#js {:react-key n
:className (str "cell" (when adj (str " adjacent-" adj)))
:style (get-cell-style app idx)
:onClick #(when adj (move! app n))}
(dom/video #js {:autoPlay true
:muted true
:style (get-bg-transform app n)
:ref video-ref})
(dom/label nil (inc n))))))))
(defn grid [{:keys [cells grid-px show-nums] :as app}]
(om/component
(apply
dom/div
#js {:className (str "grid" (when show-nums " show-nums"))
:style #js {:width grid-px :height grid-px}}
(map
(fn [[n idx]]
(om/build cell (merge app {:n n :idx idx})))
cells))))
(defn set-grid-size! [app size]
{:pre [(integer? size) (> size 1) (< size 10)]}
(new-game! app size (:tick-ms @app)))
(defn set-tick-ms! [app ms]
(om/update! app :tick-ms ms))
(defn get-max-grid-px []
(min (- js/innerWidth (* capture-size 1.2)) js/innerHeight))
(declare playback-ctx)
(defn paint-canvas! [{:keys [moves grid-size]} tick]
(go
(let [img (<! (@img-cache tick))
s (/ capture-size grid-size)]
(.fillRect playback-ctx 0 0 capture-size capture-size)
(doseq [[idx pos] (:cells (moves tick))]
(if-not (= idx :empty)
(let [[x1 y1] (get-cell-xy idx grid-size)
[x2 y2] (get-cell-xy pos grid-size)]
(.drawImage
playback-ctx
img
(* x1 s)
(* y1 s)
s
s
(* x2 s)
(* y2 s)
s
s))))
(.drawImage playback-ctx img 0 capture-size))))
(defonce app-state (atom {}))
(defn raf-step! [c]
(js/requestAnimationFrame #(put! c true (partial raf-step! c))))
(defonce raf-chan
(let [c (chan)]
(raf-step! c)
c))
(defonce tick-loop (atom nil))
(defn start! []
(swap! app-state merge (make-game @app-state default-size))
(when (nil? @tick-loop)
(reset! tick-loop
(go-loop [tick 0]
(<! (timeout (:tick-ms @app-state)))
(<! raf-chan)
(let [app @app-state
move-count (count (:moves app))
tick (if (>= tick move-count) 0 tick)]
(swap! app-state assoc :tick tick)
(<! (paint-canvas! app tick))
(if (or (zero? move-count) (= tick (dec move-count)))
(recur 0)
(recur (inc tick))))))))
(defn get-camera! [skip-howto?]
(swap! app-state assoc :camera-waiting? true)
(take!
(media/get-media)
(fn [{:keys [status data]}]
(if (= status :success)
(let [video (.createElement js/document "video")
canvas (.createElement js/document "canvas")
e-key "oncanplay"]
(doto canvas
(aset "width" capture-size)
(aset "height" capture-size))
(doto video
(.setAttribute "autoplay" "")
(.setAttribute "playsinline" "")
(.setAttribute "muted" "")
(aset "style" "position" "absolute")
(aset "style" "top" "0")
(aset "style" "left" "0")
(aset "style" "pointerEvents" "none")
(aset "style" "opacity" "0")
(aset
e-key
(fn []
(let [vw (.-videoWidth video)
vh (.-videoHeight video)]
(js-delete video e-key)
(swap!
app-state
merge
{:stream data
:grid-px (get-max-grid-px)
:vid-node video
:vid-w vw
:vid-h vh
:vid-ratio (/ vw vh)
:vid-offset (*
100
(/
(max 1 (.abs js/Math (- vw vh)))
(max 1 (* vw 2))))
:canvas-node canvas
:ctx (.getContext canvas "2d")
:show-about? (not skip-howto?)
:media-error nil})
(js/setTimeout start! 100)
(.setItem js/localStorage ls-key "1"))))
(aset "srcObject" data))
(.appendChild (.-body js/document) video))
(do
(swap! app-state assoc :media-error data :previous-grant? false)
(.clear js/localStorage))))))
(defn make-gif [app ms]
(om/update! app :gif-building? true)
(let [gif (js/GIF. #js {:workerScript "js/gif.worker.js" :quality 1})
canvas (.-canvas playback-ctx)]
(go
(dotimes [idx (count (:moves app))]
(<! (paint-canvas! app idx))
(.addFrame gif canvas #js {:delay ms :copy true}))
(doto gif
(.on "finished" (fn [data]
(om/update! app
:result-gif
(.createObjectURL js/URL data))
(om/update! app :gif-building? false)))
(.render)))))
(defn modal [{:keys [stream media-error show-about? result-gif cells win-state
grid-size tick-ms gif-building? camera-waiting?
previous-grant?] :as app}]
(let [winner? (and cells (= cells win-state))
no-stream? (not stream)]
(dom/div
#js {:className
(str "modal"
(when (or no-stream? media-error show-about? result-gif winner?)
" active"))}
(cond
media-error
(dom/div nil
(dom/h1 nil "!!!")
(if (= media-error :denied)
(:cam-denied strings)
(:cam-failed strings))
(apply dom/button
(if camera-waiting?
[#js {:className "wait"} "hold on"]
[#js {:onClick get-camera!} "try again"]))
(dom/button
#js {:onClick #(js/open source-url)}
"view cellf source"))
no-stream?
(if previous-grant?
(dom/div nil "One moment…")
(dom/div nil
(dom/h1 nil "Hi")
(dom/p nil (:intro1 strings))
(dom/p nil (:intro2 strings))
(apply dom/button
(if camera-waiting?
[#js {:className "wait"} "hold on"]
[#js {:onClick get-camera!} "✔ ok"]))))
result-gif
(dom/div nil
(dom/h1 nil "Your Cellf")
(dom/a
#js {:href result-gif
:download "cellf.gif"
:className "download"}
(dom/img #js {:src result-gif}))
(:gif-result strings)
(dom/button
#js {:onClick #(om/update! app :result-gif nil)}
"✔ done"))
winner?
(dom/div nil
(dom/h1 nil "You win!")
(:win-info strings)
(apply dom/button
(if gif-building?
[#js {:className "wait"} "hold on"]
[#js {:onClick #(make-gif app tick-ms)}
"make gif replay"]))
(dom/button
#js {:onClick #(set-grid-size! app grid-size)}
"new game"))
show-about?
(dom/div nil
(dom/h1 nil "How to play")
(dom/p nil (:how-to1 strings))
(dom/p nil (:how-to2 strings))
(dom/h1 nil "About Cellf")
(dom/p nil
(:about1 strings)
(dom/a #js {:href source-url} "open source")
(:about2 strings)
(dom/a #js {:href home-url} "oxism.com")
\.)
(dom/button
#js {:onClick #(om/update! app :show-about? false)}
"✔ got it"))))))
(om/root
(fn [{:keys [stream moves tick tick-ms grid-size show-nums gif-building?]
:as app}
owner]
(reify
om/IDidMount
(did-mount
[_]
(swap! app-state assoc :canvas-node (om/get-node owner canvas-ref))
(when (.getItem js/localStorage ls-key)
(swap! app-state assoc :previous-grant? true)
(get-camera! true))
(def playback-ctx
(let [ctx (-> (om/get-node owner "playback") (.getContext "2d"))]
(aset ctx "fillStyle" "#fff")
ctx))
(defonce resize-loop
(let [resize-chan (chan)]
(.addEventListener js/window "resize" #(put! resize-chan true))
(go-loop [open true]
(when open (<! resize-chan))
(let [throttle (timeout resize-ms)]
(if (= throttle (last (alts! [throttle resize-chan])))
(do
(swap! app-state assoc :grid-px (get-max-grid-px))
(recur true))
(recur false)))))))
om/IDidUpdate
(did-update
[_ prev-props _]
(when (and stream (not= (:stream prev-props) stream))
(set-vid-src owner stream)))
om/IRender
(render
[_]
(dom/div
nil
(dom/canvas #js {:ref canvas-ref :style #js {:display "none"}})
(modal app)
(dom/div
#js {:id "sidebar"
:className (when-not stream "hidden")
:style #js {:width capture-size}}
(dom/img #js {:src "img/cellf.svg" :alt "Cellf"})
(dom/h2 nil "find yourself")
(dom/canvas #js {:ref "playback"
:width capture-size
:height (* capture-size 2)})
(when stream
(dom/div nil
(dom/label
#js {:className "move-count"}
(str (inc tick) \/ (count moves)))
(dom/label
#js {:htmlFor "show-nums"}
"show numbers?")
(dom/input
#js {:id "show-nums"
:type "checkbox"
:checked show-nums
:onChange #(om/update!
app :show-nums (not show-nums))})
(dom/label
nil
(str "grid size (" grid-size \× grid-size ")")
(dom/em nil "(starts new game)"))
(dom/input #js {:type "range"
:value grid-size
:min "2"
:max "9"
:step "1"
:onChange
#(set-grid-size!
app
(js/parseInt
(.. % -target -value)))})
(dom/label nil "playback speed")
(dom/input
#js {:type "range"
:value (- tick-ms)
:min "-1000"
:max "-30"
:step "10"
:onChange #(set-tick-ms!
app
(- (js/parseInt
(.. % -target -value))))})
(apply dom/button
(if gif-building?
[#js {:className "wait"} "hold on"]
[#js {:onClick #(make-gif app tick-ms)}
"make gif"]))
(dom/button
#js {:onClick #(om/update! app :show-about? true)}
"help")
(dom/p nil
(dom/a
#js {:href source-url :target "_blank"}
"source")
(dom/span nil \/)
(dom/a
#js {:href home-url :target "_blank"}
"oxism")))))
(when stream (om/build grid app))))))
app-state
{:target (.getElementById js/document "app")})
|
24871
|
(ns ^:figwheel-always cellf.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [<! >! take! put! alts! chan timeout]]
[cellf.media :as media]
[cellf.strings :refer [strings]])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
(enable-console-print!)
(def default-size 3)
(def capture-size 250)
(def tick-ms 150)
(def resize-ms 200)
(def source-url "https://github.com/dmotz/cellf")
(def home-url "http://oxism.com")
(def ls-key "<KEY>")
(def canvas-ref "capture-canvas")
(def video-ref "vid")
(defonce img-cache (atom []))
(defn sq [n]
(* n n))
(defn t3d [x y]
(str "translate3d(" x "%," y "%,0)"))
(defn promise-chan []
(let [c (chan)]
(take!
c
#(go-loop []
(>! c %)
(recur)))
c))
(defn capture-move [{:keys [ctx vid-node canvas-node vid-w vid-h]} cells]
(.drawImage
ctx
vid-node
(/ (- vid-w vid-h) 2)
0
vid-h
vid-h
0
0
capture-size
capture-size)
(let [img-data (.toDataURL canvas-node "image/jpeg" 1)
img-el (js/Image.)
pc (promise-chan)]
(swap! img-cache conj pc)
(doto img-el
(aset "src" img-data)
(aset
"onload"
(fn []
(js-delete img-el "onload")
(put! pc img-el))))
{:cells cells :image img-data}))
(defn order [grid]
(->>
grid
(sort-by second)
(map first)))
(defn inversions [grid]
(let [cells (order grid)]
(->>
grid
count
range
(map
(fn [n]
(->>
cells
(drop n)
(filter #(< % (nth cells n)))
count)))
(reduce +))))
(defn blank-at-row [grid size]
(js/Math.floor (/ (:empty grid) size)))
(def solvable?
(memoize
(fn [grid size]
(let [even-inversions? (even? (inversions grid))]
(or
(and (odd? size) even-inversions?)
(and
(even? size)
(= even-inversions? (odd? (blank-at-row grid size)))))))))
(defn make-cell-list [size]
(->
size
sq
dec
range
vec
(conj :empty)))
(defn make-cells [size win-state]
(let [shuffled (zipmap (make-cell-list size) (shuffle (range (sq size))))]
(if (or
(= shuffled win-state)
(not (solvable? shuffled size)))
(recur size win-state)
shuffled)))
(defn make-win-state [size]
(zipmap (make-cell-list size) (range (sq size))))
(defn make-game
([app size]
(make-game app size tick-ms))
([app size speed]
(let [win-state (make-win-state size)
cells (make-cells size win-state)]
{:moves [(capture-move app cells)]
:tick 0
:tick-ms speed
:grid-size size
:cells cells
:win-state win-state})))
(def get-cell-xy (juxt mod quot))
(defn get-cell-style [app i]
(let [size (:grid-size app)
pct (str (/ 100 size) \%)
px (/ (:grid-px app) size)
[x y] (get-cell-xy i size)]
#js {:transform (t3d (* 100 x) (* 100 y))
:width pct
:height pct
:lineHeight (str px "px")
:fontSize (/ px 10)}))
(defn get-bg-transform [{:keys [grid-size vid-ratio vid-offset]} i]
(if (= i :empty)
nil
(let [size grid-size
pct (/ 100 size)
[x y] (get-cell-xy i size)]
#js {:height (str (* size 100) \%)
:transform (t3d
(- (+ (/ (* x pct) vid-ratio) vid-offset))
(- (* pct y)))})))
(defn adj? [app i]
(let [{size :grid-size {emp :empty} :cells} app
emp' (inc emp)]
(cond
(= i (- emp size)) \d
(= i (+ emp size)) \u
(and (= i emp') (pos? (mod emp' size))) \l
(and (= i (dec emp)) (pos? (mod emp size))) \r
:else false)))
(defn swap-cell [cells n]
(let [current-idx (cells n)
empty-idx (:empty cells)]
(into
{}
(map
(fn [[k idx]]
(if (= k :empty)
[:empty current-idx]
(if (= k n) [k empty-idx] [k idx])))
cells))))
(defn move! [{:keys [moves] :as app} n]
(let [new-layout (swap-cell (:cells app) n)]
(om/update! app :cells new-layout)
(om/update! app :moves (conj moves (capture-move app new-layout)))))
(defn new-game! [app size speed]
(reset! img-cache [])
(om/update! app (merge app (make-game app size speed))))
(defn set-vid-src [owner stream]
(aset (om/get-node owner video-ref) "srcObject" stream))
(defn cell [{:keys [stream n idx] :as app} owner]
(reify
om/IDidMount
(did-mount [_]
(when (not= n :empty)
(.setAttribute (om/get-node owner video-ref) "playsinline" "")
(set-vid-src owner stream)))
om/IDidUpdate
(did-update [_ prev-props _]
(when (and (not= n :empty) (not= n (:n prev-props)))
(set-vid-src owner stream)))
om/IRender
(render [_]
(when (not= n :empty)
(let [adj (adj? app idx)]
(dom/div
#js {:react-key n
:className (str "cell" (when adj (str " adjacent-" adj)))
:style (get-cell-style app idx)
:onClick #(when adj (move! app n))}
(dom/video #js {:autoPlay true
:muted true
:style (get-bg-transform app n)
:ref video-ref})
(dom/label nil (inc n))))))))
(defn grid [{:keys [cells grid-px show-nums] :as app}]
(om/component
(apply
dom/div
#js {:className (str "grid" (when show-nums " show-nums"))
:style #js {:width grid-px :height grid-px}}
(map
(fn [[n idx]]
(om/build cell (merge app {:n n :idx idx})))
cells))))
(defn set-grid-size! [app size]
{:pre [(integer? size) (> size 1) (< size 10)]}
(new-game! app size (:tick-ms @app)))
(defn set-tick-ms! [app ms]
(om/update! app :tick-ms ms))
(defn get-max-grid-px []
(min (- js/innerWidth (* capture-size 1.2)) js/innerHeight))
(declare playback-ctx)
(defn paint-canvas! [{:keys [moves grid-size]} tick]
(go
(let [img (<! (@img-cache tick))
s (/ capture-size grid-size)]
(.fillRect playback-ctx 0 0 capture-size capture-size)
(doseq [[idx pos] (:cells (moves tick))]
(if-not (= idx :empty)
(let [[x1 y1] (get-cell-xy idx grid-size)
[x2 y2] (get-cell-xy pos grid-size)]
(.drawImage
playback-ctx
img
(* x1 s)
(* y1 s)
s
s
(* x2 s)
(* y2 s)
s
s))))
(.drawImage playback-ctx img 0 capture-size))))
(defonce app-state (atom {}))
(defn raf-step! [c]
(js/requestAnimationFrame #(put! c true (partial raf-step! c))))
(defonce raf-chan
(let [c (chan)]
(raf-step! c)
c))
(defonce tick-loop (atom nil))
(defn start! []
(swap! app-state merge (make-game @app-state default-size))
(when (nil? @tick-loop)
(reset! tick-loop
(go-loop [tick 0]
(<! (timeout (:tick-ms @app-state)))
(<! raf-chan)
(let [app @app-state
move-count (count (:moves app))
tick (if (>= tick move-count) 0 tick)]
(swap! app-state assoc :tick tick)
(<! (paint-canvas! app tick))
(if (or (zero? move-count) (= tick (dec move-count)))
(recur 0)
(recur (inc tick))))))))
(defn get-camera! [skip-howto?]
(swap! app-state assoc :camera-waiting? true)
(take!
(media/get-media)
(fn [{:keys [status data]}]
(if (= status :success)
(let [video (.createElement js/document "video")
canvas (.createElement js/document "canvas")
e-key "<KEY>"]
(doto canvas
(aset "width" capture-size)
(aset "height" capture-size))
(doto video
(.setAttribute "autoplay" "")
(.setAttribute "playsinline" "")
(.setAttribute "muted" "")
(aset "style" "position" "absolute")
(aset "style" "top" "0")
(aset "style" "left" "0")
(aset "style" "pointerEvents" "none")
(aset "style" "opacity" "0")
(aset
e-key
(fn []
(let [vw (.-videoWidth video)
vh (.-videoHeight video)]
(js-delete video e-key)
(swap!
app-state
merge
{:stream data
:grid-px (get-max-grid-px)
:vid-node video
:vid-w vw
:vid-h vh
:vid-ratio (/ vw vh)
:vid-offset (*
100
(/
(max 1 (.abs js/Math (- vw vh)))
(max 1 (* vw 2))))
:canvas-node canvas
:ctx (.getContext canvas "2d")
:show-about? (not skip-howto?)
:media-error nil})
(js/setTimeout start! 100)
(.setItem js/localStorage ls-key "1"))))
(aset "srcObject" data))
(.appendChild (.-body js/document) video))
(do
(swap! app-state assoc :media-error data :previous-grant? false)
(.clear js/localStorage))))))
(defn make-gif [app ms]
(om/update! app :gif-building? true)
(let [gif (js/GIF. #js {:workerScript "js/gif.worker.js" :quality 1})
canvas (.-canvas playback-ctx)]
(go
(dotimes [idx (count (:moves app))]
(<! (paint-canvas! app idx))
(.addFrame gif canvas #js {:delay ms :copy true}))
(doto gif
(.on "finished" (fn [data]
(om/update! app
:result-gif
(.createObjectURL js/URL data))
(om/update! app :gif-building? false)))
(.render)))))
(defn modal [{:keys [stream media-error show-about? result-gif cells win-state
grid-size tick-ms gif-building? camera-waiting?
previous-grant?] :as app}]
(let [winner? (and cells (= cells win-state))
no-stream? (not stream)]
(dom/div
#js {:className
(str "modal"
(when (or no-stream? media-error show-about? result-gif winner?)
" active"))}
(cond
media-error
(dom/div nil
(dom/h1 nil "!!!")
(if (= media-error :denied)
(:cam-denied strings)
(:cam-failed strings))
(apply dom/button
(if camera-waiting?
[#js {:className "wait"} "hold on"]
[#js {:onClick get-camera!} "try again"]))
(dom/button
#js {:onClick #(js/open source-url)}
"view cellf source"))
no-stream?
(if previous-grant?
(dom/div nil "One moment…")
(dom/div nil
(dom/h1 nil "Hi")
(dom/p nil (:intro1 strings))
(dom/p nil (:intro2 strings))
(apply dom/button
(if camera-waiting?
[#js {:className "wait"} "hold on"]
[#js {:onClick get-camera!} "✔ ok"]))))
result-gif
(dom/div nil
(dom/h1 nil "Your Cellf")
(dom/a
#js {:href result-gif
:download "cellf.gif"
:className "download"}
(dom/img #js {:src result-gif}))
(:gif-result strings)
(dom/button
#js {:onClick #(om/update! app :result-gif nil)}
"✔ done"))
winner?
(dom/div nil
(dom/h1 nil "You win!")
(:win-info strings)
(apply dom/button
(if gif-building?
[#js {:className "wait"} "hold on"]
[#js {:onClick #(make-gif app tick-ms)}
"make gif replay"]))
(dom/button
#js {:onClick #(set-grid-size! app grid-size)}
"new game"))
show-about?
(dom/div nil
(dom/h1 nil "How to play")
(dom/p nil (:how-to1 strings))
(dom/p nil (:how-to2 strings))
(dom/h1 nil "About Cellf")
(dom/p nil
(:about1 strings)
(dom/a #js {:href source-url} "open source")
(:about2 strings)
(dom/a #js {:href home-url} "oxism.com")
\.)
(dom/button
#js {:onClick #(om/update! app :show-about? false)}
"✔ got it"))))))
(om/root
(fn [{:keys [stream moves tick tick-ms grid-size show-nums gif-building?]
:as app}
owner]
(reify
om/IDidMount
(did-mount
[_]
(swap! app-state assoc :canvas-node (om/get-node owner canvas-ref))
(when (.getItem js/localStorage ls-key)
(swap! app-state assoc :previous-grant? true)
(get-camera! true))
(def playback-ctx
(let [ctx (-> (om/get-node owner "playback") (.getContext "2d"))]
(aset ctx "fillStyle" "#fff")
ctx))
(defonce resize-loop
(let [resize-chan (chan)]
(.addEventListener js/window "resize" #(put! resize-chan true))
(go-loop [open true]
(when open (<! resize-chan))
(let [throttle (timeout resize-ms)]
(if (= throttle (last (alts! [throttle resize-chan])))
(do
(swap! app-state assoc :grid-px (get-max-grid-px))
(recur true))
(recur false)))))))
om/IDidUpdate
(did-update
[_ prev-props _]
(when (and stream (not= (:stream prev-props) stream))
(set-vid-src owner stream)))
om/IRender
(render
[_]
(dom/div
nil
(dom/canvas #js {:ref canvas-ref :style #js {:display "none"}})
(modal app)
(dom/div
#js {:id "sidebar"
:className (when-not stream "hidden")
:style #js {:width capture-size}}
(dom/img #js {:src "img/cellf.svg" :alt "Cellf"})
(dom/h2 nil "find yourself")
(dom/canvas #js {:ref "playback"
:width capture-size
:height (* capture-size 2)})
(when stream
(dom/div nil
(dom/label
#js {:className "move-count"}
(str (inc tick) \/ (count moves)))
(dom/label
#js {:htmlFor "show-nums"}
"show numbers?")
(dom/input
#js {:id "show-nums"
:type "checkbox"
:checked show-nums
:onChange #(om/update!
app :show-nums (not show-nums))})
(dom/label
nil
(str "grid size (" grid-size \× grid-size ")")
(dom/em nil "(starts new game)"))
(dom/input #js {:type "range"
:value grid-size
:min "2"
:max "9"
:step "1"
:onChange
#(set-grid-size!
app
(js/parseInt
(.. % -target -value)))})
(dom/label nil "playback speed")
(dom/input
#js {:type "range"
:value (- tick-ms)
:min "-1000"
:max "-30"
:step "10"
:onChange #(set-tick-ms!
app
(- (js/parseInt
(.. % -target -value))))})
(apply dom/button
(if gif-building?
[#js {:className "wait"} "hold on"]
[#js {:onClick #(make-gif app tick-ms)}
"make gif"]))
(dom/button
#js {:onClick #(om/update! app :show-about? true)}
"help")
(dom/p nil
(dom/a
#js {:href source-url :target "_blank"}
"source")
(dom/span nil \/)
(dom/a
#js {:href home-url :target "_blank"}
"oxism")))))
(when stream (om/build grid app))))))
app-state
{:target (.getElementById js/document "app")})
| true |
(ns ^:figwheel-always cellf.core
(:require [om.core :as om :include-macros true]
[om.dom :as dom :include-macros true]
[cljs.core.async :refer [<! >! take! put! alts! chan timeout]]
[cellf.media :as media]
[cellf.strings :refer [strings]])
(:require-macros [cljs.core.async.macros :refer [go go-loop]]))
(enable-console-print!)
(def default-size 3)
(def capture-size 250)
(def tick-ms 150)
(def resize-ms 200)
(def source-url "https://github.com/dmotz/cellf")
(def home-url "http://oxism.com")
(def ls-key "PI:KEY:<KEY>END_PI")
(def canvas-ref "capture-canvas")
(def video-ref "vid")
(defonce img-cache (atom []))
(defn sq [n]
(* n n))
(defn t3d [x y]
(str "translate3d(" x "%," y "%,0)"))
(defn promise-chan []
(let [c (chan)]
(take!
c
#(go-loop []
(>! c %)
(recur)))
c))
(defn capture-move [{:keys [ctx vid-node canvas-node vid-w vid-h]} cells]
(.drawImage
ctx
vid-node
(/ (- vid-w vid-h) 2)
0
vid-h
vid-h
0
0
capture-size
capture-size)
(let [img-data (.toDataURL canvas-node "image/jpeg" 1)
img-el (js/Image.)
pc (promise-chan)]
(swap! img-cache conj pc)
(doto img-el
(aset "src" img-data)
(aset
"onload"
(fn []
(js-delete img-el "onload")
(put! pc img-el))))
{:cells cells :image img-data}))
(defn order [grid]
(->>
grid
(sort-by second)
(map first)))
(defn inversions [grid]
(let [cells (order grid)]
(->>
grid
count
range
(map
(fn [n]
(->>
cells
(drop n)
(filter #(< % (nth cells n)))
count)))
(reduce +))))
(defn blank-at-row [grid size]
(js/Math.floor (/ (:empty grid) size)))
(def solvable?
(memoize
(fn [grid size]
(let [even-inversions? (even? (inversions grid))]
(or
(and (odd? size) even-inversions?)
(and
(even? size)
(= even-inversions? (odd? (blank-at-row grid size)))))))))
(defn make-cell-list [size]
(->
size
sq
dec
range
vec
(conj :empty)))
(defn make-cells [size win-state]
(let [shuffled (zipmap (make-cell-list size) (shuffle (range (sq size))))]
(if (or
(= shuffled win-state)
(not (solvable? shuffled size)))
(recur size win-state)
shuffled)))
(defn make-win-state [size]
(zipmap (make-cell-list size) (range (sq size))))
(defn make-game
([app size]
(make-game app size tick-ms))
([app size speed]
(let [win-state (make-win-state size)
cells (make-cells size win-state)]
{:moves [(capture-move app cells)]
:tick 0
:tick-ms speed
:grid-size size
:cells cells
:win-state win-state})))
(def get-cell-xy (juxt mod quot))
(defn get-cell-style [app i]
(let [size (:grid-size app)
pct (str (/ 100 size) \%)
px (/ (:grid-px app) size)
[x y] (get-cell-xy i size)]
#js {:transform (t3d (* 100 x) (* 100 y))
:width pct
:height pct
:lineHeight (str px "px")
:fontSize (/ px 10)}))
(defn get-bg-transform [{:keys [grid-size vid-ratio vid-offset]} i]
(if (= i :empty)
nil
(let [size grid-size
pct (/ 100 size)
[x y] (get-cell-xy i size)]
#js {:height (str (* size 100) \%)
:transform (t3d
(- (+ (/ (* x pct) vid-ratio) vid-offset))
(- (* pct y)))})))
(defn adj? [app i]
(let [{size :grid-size {emp :empty} :cells} app
emp' (inc emp)]
(cond
(= i (- emp size)) \d
(= i (+ emp size)) \u
(and (= i emp') (pos? (mod emp' size))) \l
(and (= i (dec emp)) (pos? (mod emp size))) \r
:else false)))
(defn swap-cell [cells n]
(let [current-idx (cells n)
empty-idx (:empty cells)]
(into
{}
(map
(fn [[k idx]]
(if (= k :empty)
[:empty current-idx]
(if (= k n) [k empty-idx] [k idx])))
cells))))
(defn move! [{:keys [moves] :as app} n]
(let [new-layout (swap-cell (:cells app) n)]
(om/update! app :cells new-layout)
(om/update! app :moves (conj moves (capture-move app new-layout)))))
(defn new-game! [app size speed]
(reset! img-cache [])
(om/update! app (merge app (make-game app size speed))))
(defn set-vid-src [owner stream]
(aset (om/get-node owner video-ref) "srcObject" stream))
(defn cell [{:keys [stream n idx] :as app} owner]
(reify
om/IDidMount
(did-mount [_]
(when (not= n :empty)
(.setAttribute (om/get-node owner video-ref) "playsinline" "")
(set-vid-src owner stream)))
om/IDidUpdate
(did-update [_ prev-props _]
(when (and (not= n :empty) (not= n (:n prev-props)))
(set-vid-src owner stream)))
om/IRender
(render [_]
(when (not= n :empty)
(let [adj (adj? app idx)]
(dom/div
#js {:react-key n
:className (str "cell" (when adj (str " adjacent-" adj)))
:style (get-cell-style app idx)
:onClick #(when adj (move! app n))}
(dom/video #js {:autoPlay true
:muted true
:style (get-bg-transform app n)
:ref video-ref})
(dom/label nil (inc n))))))))
(defn grid [{:keys [cells grid-px show-nums] :as app}]
(om/component
(apply
dom/div
#js {:className (str "grid" (when show-nums " show-nums"))
:style #js {:width grid-px :height grid-px}}
(map
(fn [[n idx]]
(om/build cell (merge app {:n n :idx idx})))
cells))))
(defn set-grid-size! [app size]
{:pre [(integer? size) (> size 1) (< size 10)]}
(new-game! app size (:tick-ms @app)))
(defn set-tick-ms! [app ms]
(om/update! app :tick-ms ms))
(defn get-max-grid-px []
(min (- js/innerWidth (* capture-size 1.2)) js/innerHeight))
(declare playback-ctx)
(defn paint-canvas! [{:keys [moves grid-size]} tick]
(go
(let [img (<! (@img-cache tick))
s (/ capture-size grid-size)]
(.fillRect playback-ctx 0 0 capture-size capture-size)
(doseq [[idx pos] (:cells (moves tick))]
(if-not (= idx :empty)
(let [[x1 y1] (get-cell-xy idx grid-size)
[x2 y2] (get-cell-xy pos grid-size)]
(.drawImage
playback-ctx
img
(* x1 s)
(* y1 s)
s
s
(* x2 s)
(* y2 s)
s
s))))
(.drawImage playback-ctx img 0 capture-size))))
(defonce app-state (atom {}))
(defn raf-step! [c]
(js/requestAnimationFrame #(put! c true (partial raf-step! c))))
(defonce raf-chan
(let [c (chan)]
(raf-step! c)
c))
(defonce tick-loop (atom nil))
(defn start! []
(swap! app-state merge (make-game @app-state default-size))
(when (nil? @tick-loop)
(reset! tick-loop
(go-loop [tick 0]
(<! (timeout (:tick-ms @app-state)))
(<! raf-chan)
(let [app @app-state
move-count (count (:moves app))
tick (if (>= tick move-count) 0 tick)]
(swap! app-state assoc :tick tick)
(<! (paint-canvas! app tick))
(if (or (zero? move-count) (= tick (dec move-count)))
(recur 0)
(recur (inc tick))))))))
(defn get-camera! [skip-howto?]
(swap! app-state assoc :camera-waiting? true)
(take!
(media/get-media)
(fn [{:keys [status data]}]
(if (= status :success)
(let [video (.createElement js/document "video")
canvas (.createElement js/document "canvas")
e-key "PI:KEY:<KEY>END_PI"]
(doto canvas
(aset "width" capture-size)
(aset "height" capture-size))
(doto video
(.setAttribute "autoplay" "")
(.setAttribute "playsinline" "")
(.setAttribute "muted" "")
(aset "style" "position" "absolute")
(aset "style" "top" "0")
(aset "style" "left" "0")
(aset "style" "pointerEvents" "none")
(aset "style" "opacity" "0")
(aset
e-key
(fn []
(let [vw (.-videoWidth video)
vh (.-videoHeight video)]
(js-delete video e-key)
(swap!
app-state
merge
{:stream data
:grid-px (get-max-grid-px)
:vid-node video
:vid-w vw
:vid-h vh
:vid-ratio (/ vw vh)
:vid-offset (*
100
(/
(max 1 (.abs js/Math (- vw vh)))
(max 1 (* vw 2))))
:canvas-node canvas
:ctx (.getContext canvas "2d")
:show-about? (not skip-howto?)
:media-error nil})
(js/setTimeout start! 100)
(.setItem js/localStorage ls-key "1"))))
(aset "srcObject" data))
(.appendChild (.-body js/document) video))
(do
(swap! app-state assoc :media-error data :previous-grant? false)
(.clear js/localStorage))))))
(defn make-gif [app ms]
(om/update! app :gif-building? true)
(let [gif (js/GIF. #js {:workerScript "js/gif.worker.js" :quality 1})
canvas (.-canvas playback-ctx)]
(go
(dotimes [idx (count (:moves app))]
(<! (paint-canvas! app idx))
(.addFrame gif canvas #js {:delay ms :copy true}))
(doto gif
(.on "finished" (fn [data]
(om/update! app
:result-gif
(.createObjectURL js/URL data))
(om/update! app :gif-building? false)))
(.render)))))
(defn modal [{:keys [stream media-error show-about? result-gif cells win-state
grid-size tick-ms gif-building? camera-waiting?
previous-grant?] :as app}]
(let [winner? (and cells (= cells win-state))
no-stream? (not stream)]
(dom/div
#js {:className
(str "modal"
(when (or no-stream? media-error show-about? result-gif winner?)
" active"))}
(cond
media-error
(dom/div nil
(dom/h1 nil "!!!")
(if (= media-error :denied)
(:cam-denied strings)
(:cam-failed strings))
(apply dom/button
(if camera-waiting?
[#js {:className "wait"} "hold on"]
[#js {:onClick get-camera!} "try again"]))
(dom/button
#js {:onClick #(js/open source-url)}
"view cellf source"))
no-stream?
(if previous-grant?
(dom/div nil "One moment…")
(dom/div nil
(dom/h1 nil "Hi")
(dom/p nil (:intro1 strings))
(dom/p nil (:intro2 strings))
(apply dom/button
(if camera-waiting?
[#js {:className "wait"} "hold on"]
[#js {:onClick get-camera!} "✔ ok"]))))
result-gif
(dom/div nil
(dom/h1 nil "Your Cellf")
(dom/a
#js {:href result-gif
:download "cellf.gif"
:className "download"}
(dom/img #js {:src result-gif}))
(:gif-result strings)
(dom/button
#js {:onClick #(om/update! app :result-gif nil)}
"✔ done"))
winner?
(dom/div nil
(dom/h1 nil "You win!")
(:win-info strings)
(apply dom/button
(if gif-building?
[#js {:className "wait"} "hold on"]
[#js {:onClick #(make-gif app tick-ms)}
"make gif replay"]))
(dom/button
#js {:onClick #(set-grid-size! app grid-size)}
"new game"))
show-about?
(dom/div nil
(dom/h1 nil "How to play")
(dom/p nil (:how-to1 strings))
(dom/p nil (:how-to2 strings))
(dom/h1 nil "About Cellf")
(dom/p nil
(:about1 strings)
(dom/a #js {:href source-url} "open source")
(:about2 strings)
(dom/a #js {:href home-url} "oxism.com")
\.)
(dom/button
#js {:onClick #(om/update! app :show-about? false)}
"✔ got it"))))))
(om/root
(fn [{:keys [stream moves tick tick-ms grid-size show-nums gif-building?]
:as app}
owner]
(reify
om/IDidMount
(did-mount
[_]
(swap! app-state assoc :canvas-node (om/get-node owner canvas-ref))
(when (.getItem js/localStorage ls-key)
(swap! app-state assoc :previous-grant? true)
(get-camera! true))
(def playback-ctx
(let [ctx (-> (om/get-node owner "playback") (.getContext "2d"))]
(aset ctx "fillStyle" "#fff")
ctx))
(defonce resize-loop
(let [resize-chan (chan)]
(.addEventListener js/window "resize" #(put! resize-chan true))
(go-loop [open true]
(when open (<! resize-chan))
(let [throttle (timeout resize-ms)]
(if (= throttle (last (alts! [throttle resize-chan])))
(do
(swap! app-state assoc :grid-px (get-max-grid-px))
(recur true))
(recur false)))))))
om/IDidUpdate
(did-update
[_ prev-props _]
(when (and stream (not= (:stream prev-props) stream))
(set-vid-src owner stream)))
om/IRender
(render
[_]
(dom/div
nil
(dom/canvas #js {:ref canvas-ref :style #js {:display "none"}})
(modal app)
(dom/div
#js {:id "sidebar"
:className (when-not stream "hidden")
:style #js {:width capture-size}}
(dom/img #js {:src "img/cellf.svg" :alt "Cellf"})
(dom/h2 nil "find yourself")
(dom/canvas #js {:ref "playback"
:width capture-size
:height (* capture-size 2)})
(when stream
(dom/div nil
(dom/label
#js {:className "move-count"}
(str (inc tick) \/ (count moves)))
(dom/label
#js {:htmlFor "show-nums"}
"show numbers?")
(dom/input
#js {:id "show-nums"
:type "checkbox"
:checked show-nums
:onChange #(om/update!
app :show-nums (not show-nums))})
(dom/label
nil
(str "grid size (" grid-size \× grid-size ")")
(dom/em nil "(starts new game)"))
(dom/input #js {:type "range"
:value grid-size
:min "2"
:max "9"
:step "1"
:onChange
#(set-grid-size!
app
(js/parseInt
(.. % -target -value)))})
(dom/label nil "playback speed")
(dom/input
#js {:type "range"
:value (- tick-ms)
:min "-1000"
:max "-30"
:step "10"
:onChange #(set-tick-ms!
app
(- (js/parseInt
(.. % -target -value))))})
(apply dom/button
(if gif-building?
[#js {:className "wait"} "hold on"]
[#js {:onClick #(make-gif app tick-ms)}
"make gif"]))
(dom/button
#js {:onClick #(om/update! app :show-about? true)}
"help")
(dom/p nil
(dom/a
#js {:href source-url :target "_blank"}
"source")
(dom/span nil \/)
(dom/a
#js {:href home-url :target "_blank"}
"oxism")))))
(when stream (om/build grid app))))))
app-state
{:target (.getElementById js/document "app")})
|
[
{
"context": "files])))\n; (map #(str \"Hello \" % \"!\" ) [\"Ford\" \"Arthur\" \"Tricia\"])\n; (map #(str \"Hello ",
"end": 2043,
"score": 0.9993875026702881,
"start": 2039,
"tag": "NAME",
"value": "Ford"
},
{
"context": "))\n; (map #(str \"Hello \" % \"!\" ) [\"Ford\" \"Arthur\" \"Tricia\"])\n; (map #(str \"Hello \" % \"!\" )",
"end": 2052,
"score": 0.9997135996818542,
"start": 2046,
"tag": "NAME",
"value": "Arthur"
},
{
"context": " (map #(str \"Hello \" % \"!\" ) [\"Ford\" \"Arthur\" \"Tricia\"])\n; (map #(str \"Hello \" % \"!\" ) (apply m",
"end": 2061,
"score": 0.9996282458305359,
"start": 2055,
"tag": "NAME",
"value": "Tricia"
}
] |
src/sober_adnetwork/routes/advertiser.clj
|
atschx/sober-adnetwork
| 0 |
(ns sober-adnetwork.routes.advertiser
(:require
[compojure.core :refer :all]
[ring.util.response :as resp]
[ring.middleware.multipart-params :as mp]
[noir.session :as session]
[sober-adnetwork.models.offers :as offers]
[sober-adnetwork.models.offer-attachments :as offers-attch]
[sober-adnetwork.views.advertiser
[offer :as offer]]
))
;;; 不变性 很重要!!!
;(def current-uid (delay (session/get :uid)))
;;; 读取变量中的值不一定正确
;@current-uid
(defroutes advertiser-routes
;; 当前advertiser 已创建的 offer 列表
(GET "/advertiser" []
(if-let [uid (session/get :uid)]
(offer/offer-list uid)
(resp/redirect "/signin")
))
;; 添加新的 offer
(GET "/offer/add" [] (offer/add-offer))
;; 移除crsf的token,增加当前操作人
(POST "/offer/create" [& params]
(do
(offers/create
(dissoc
(merge params {:created_by (session/get :uid) :updated_by (session/get :uid)}) :__anti-forgery-token))
(resp/redirect "/advertiser")))
;; offer的创建者可以删除 offer
(GET "/offer/:id/delete" [id]
(do (offers/delete id)
(resp/redirect "/advertiser")))
;; offer 上传相关附件资源
(GET "/offer/:id/upload" [id] (offer/upload-attch id))
(mp/wrap-multipart-params
(POST "/offer/:id/upload" {params :params multi-params :multipart-params}
(println (str "原生请求参数:" params))
(println (str "offer_id:" (:id params)))
(println (str "offer_attch:" (dissoc params :__anti-forgery-token)))
; (apply map vector (get-in params [:files]))
(println (count (:files params)))
;; 此处需要进行类型判断
(println (type (:files params)))
; (println (str (get-in params [:files])))
; clojure.lang.PersistentArrayMap
; (map )
(offers-attch/restore-attachements (assoc (first (:files params)) :offer_id (:id params)))
; (map #(offers-attch/restore-attachements %) (apply map vector (get-in params [:files])))
; (map #(str "Hello " % "!" ) ["Ford" "Arthur" "Tricia"])
; (map #(str "Hello " % "!" ) (apply map vector (:files params)))
; (map #(offers-attch/restore-attachements %) (:files params))
; (map #(offer-table-item %) (offers/offer-list advertiser-id))
; (offers-attch/restore-attachements (first (map #(merge % :offer_id (:id params)) (:files params))))
; (map #(offers-attch/restore-attachements %) (map #(merge % {:offer_id (:id params)}) (:files params)))
; 文件重命名
(resp/redirect "/advertiser"))
)
)
|
84008
|
(ns sober-adnetwork.routes.advertiser
(:require
[compojure.core :refer :all]
[ring.util.response :as resp]
[ring.middleware.multipart-params :as mp]
[noir.session :as session]
[sober-adnetwork.models.offers :as offers]
[sober-adnetwork.models.offer-attachments :as offers-attch]
[sober-adnetwork.views.advertiser
[offer :as offer]]
))
;;; 不变性 很重要!!!
;(def current-uid (delay (session/get :uid)))
;;; 读取变量中的值不一定正确
;@current-uid
(defroutes advertiser-routes
;; 当前advertiser 已创建的 offer 列表
(GET "/advertiser" []
(if-let [uid (session/get :uid)]
(offer/offer-list uid)
(resp/redirect "/signin")
))
;; 添加新的 offer
(GET "/offer/add" [] (offer/add-offer))
;; 移除crsf的token,增加当前操作人
(POST "/offer/create" [& params]
(do
(offers/create
(dissoc
(merge params {:created_by (session/get :uid) :updated_by (session/get :uid)}) :__anti-forgery-token))
(resp/redirect "/advertiser")))
;; offer的创建者可以删除 offer
(GET "/offer/:id/delete" [id]
(do (offers/delete id)
(resp/redirect "/advertiser")))
;; offer 上传相关附件资源
(GET "/offer/:id/upload" [id] (offer/upload-attch id))
(mp/wrap-multipart-params
(POST "/offer/:id/upload" {params :params multi-params :multipart-params}
(println (str "原生请求参数:" params))
(println (str "offer_id:" (:id params)))
(println (str "offer_attch:" (dissoc params :__anti-forgery-token)))
; (apply map vector (get-in params [:files]))
(println (count (:files params)))
;; 此处需要进行类型判断
(println (type (:files params)))
; (println (str (get-in params [:files])))
; clojure.lang.PersistentArrayMap
; (map )
(offers-attch/restore-attachements (assoc (first (:files params)) :offer_id (:id params)))
; (map #(offers-attch/restore-attachements %) (apply map vector (get-in params [:files])))
; (map #(str "Hello " % "!" ) ["<NAME>" "<NAME>" "<NAME>"])
; (map #(str "Hello " % "!" ) (apply map vector (:files params)))
; (map #(offers-attch/restore-attachements %) (:files params))
; (map #(offer-table-item %) (offers/offer-list advertiser-id))
; (offers-attch/restore-attachements (first (map #(merge % :offer_id (:id params)) (:files params))))
; (map #(offers-attch/restore-attachements %) (map #(merge % {:offer_id (:id params)}) (:files params)))
; 文件重命名
(resp/redirect "/advertiser"))
)
)
| true |
(ns sober-adnetwork.routes.advertiser
(:require
[compojure.core :refer :all]
[ring.util.response :as resp]
[ring.middleware.multipart-params :as mp]
[noir.session :as session]
[sober-adnetwork.models.offers :as offers]
[sober-adnetwork.models.offer-attachments :as offers-attch]
[sober-adnetwork.views.advertiser
[offer :as offer]]
))
;;; 不变性 很重要!!!
;(def current-uid (delay (session/get :uid)))
;;; 读取变量中的值不一定正确
;@current-uid
(defroutes advertiser-routes
;; 当前advertiser 已创建的 offer 列表
(GET "/advertiser" []
(if-let [uid (session/get :uid)]
(offer/offer-list uid)
(resp/redirect "/signin")
))
;; 添加新的 offer
(GET "/offer/add" [] (offer/add-offer))
;; 移除crsf的token,增加当前操作人
(POST "/offer/create" [& params]
(do
(offers/create
(dissoc
(merge params {:created_by (session/get :uid) :updated_by (session/get :uid)}) :__anti-forgery-token))
(resp/redirect "/advertiser")))
;; offer的创建者可以删除 offer
(GET "/offer/:id/delete" [id]
(do (offers/delete id)
(resp/redirect "/advertiser")))
;; offer 上传相关附件资源
(GET "/offer/:id/upload" [id] (offer/upload-attch id))
(mp/wrap-multipart-params
(POST "/offer/:id/upload" {params :params multi-params :multipart-params}
(println (str "原生请求参数:" params))
(println (str "offer_id:" (:id params)))
(println (str "offer_attch:" (dissoc params :__anti-forgery-token)))
; (apply map vector (get-in params [:files]))
(println (count (:files params)))
;; 此处需要进行类型判断
(println (type (:files params)))
; (println (str (get-in params [:files])))
; clojure.lang.PersistentArrayMap
; (map )
(offers-attch/restore-attachements (assoc (first (:files params)) :offer_id (:id params)))
; (map #(offers-attch/restore-attachements %) (apply map vector (get-in params [:files])))
; (map #(str "Hello " % "!" ) ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])
; (map #(str "Hello " % "!" ) (apply map vector (:files params)))
; (map #(offers-attch/restore-attachements %) (:files params))
; (map #(offer-table-item %) (offers/offer-list advertiser-id))
; (offers-attch/restore-attachements (first (map #(merge % :offer_id (:id params)) (:files params))))
; (map #(offers-attch/restore-attachements %) (map #(merge % {:offer_id (:id params)}) (:files params)))
; 文件重命名
(resp/redirect "/advertiser"))
)
)
|
[
{
"context": "views namespace.\n;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.\n;;\n;; Licensed und",
"end": 91,
"score": 0.9966863393783569,
"start": 88,
"tag": "NAME",
"value": "F.M"
},
{
"context": "amespace.\n;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.\n;;\n;; Licensed under the Apache L",
"end": 109,
"score": 0.9823204874992371,
"start": 94,
"tag": "NAME",
"value": "Filip) de Waard"
},
{
"context": "right 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 123,
"score": 0.9999321699142456,
"start": 111,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
test/clj/vix/test/views.clj
|
fmw/vix
| 22 |
;; test/vix/test/views.clj tests for views namespace.
;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <[email protected]>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns vix.test.views
(:require [net.cgrand.enlive-html :as html])
(:use [vix.views] :reload)
(:use [clojure.test]))
(deftemplates dummy-tpl
{:en (java.io.StringReader. "<p id=\"msg\">message goes here</p>")
:nl (java.io.StringReader. "<div id=\"msg\">message goes here</div>")}
[msg]
[:#msg] (html/content msg))
(deftest test-deftemplates
(is (= (apply str (dummy-tpl :en "Hello, world!"))
"<html><body><p id=\"msg\">Hello, world!</p></body></html>"))
(is (= (apply str (dummy-tpl :nl "Hello, world!"))
"<html><body><div id=\"msg\">Hello, world!</div></body></html>"))
(is (= (dummy-tpl :qq "Hello, world!")
nil)))
(deftest test-make-pagination-uri
(testing "test :next links"
(are [last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
expected-uri]
(= (make-pagination-uri "en"
"whisky"
last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
:next)
expected-uri)
;; get a :next link on page 0 to page 1
;; first-doc: {:index {:doc-id 0 :score 1.0}}
{:index {:doc-id 4 :score 0.81}}
nil
nil
nil
nil
true
(str "/en/search?q=whisky&after-doc-id=4&after-score=0.81")
;; get a :next link on page 1 to page 2
;; first-doc: {:index {:doc-id 5 :score 0.8}}
{:index {:doc-id 9 :score 0.61}}
[]
[]
4
0.81
false
(str "/en/search?q=whisky&after-doc-id=9&after-score=0.61&"
"pp-aid[]=4&"
"pp-as[]=0.81")
;; get a :next link on page 2 to page 3
;; first-doc: {:index {:doc-id 10 :score 0.6}}
{:index {:doc-id 14 :score 0.41}}
[4]
[0.81]
9
0.61
false
(str "/en/search?q=whisky&after-doc-id=14&after-score=0.41&"
"pp-aid[]=4&pp-aid[]=9&"
"pp-as[]=0.81&pp-as[]=0.61")
;; get a :next link on page 3 to page 4
;; first-doc: {:index {:doc-id 15 :score 0.4}}
{:index {:doc-id 19 :score 0.21}}
[4 9]
[0.81 0.61]
14
0.41
false
(str "/en/search?q=whisky&after-doc-id=19&after-score=0.21&"
"pp-aid[]=4&pp-aid[]=9&pp-aid[]=14&"
"pp-as[]=0.81&pp-as[]=0.61&pp-as[]=0.41")))
(testing "test :previous links"
(are [last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
expected-uri]
(= (make-pagination-uri "en"
"whisky"
last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
:previous)
expected-uri)
;; get a :previous link on page 0 to page -1
;; first-doc: {:index {:doc-id 0 :score 1.0}}
{:index {:doc-id 4 :score 0.81}}
nil
nil
nil
nil
true
nil ;; shouldn't return a link
;; get a :next link on page 1 to page 0
;; first-doc: {:index {:doc-id 5 :score 0.8}}
{:index {:doc-id 9 :score 0.61}}
[]
[]
4
0.81
false
"/en/search?q=whisky"
;; get a :next link on page 2 to page 1
;; first-doc: {:index {:doc-id 10 :score 0.6}}
{:index {:doc-id 14 :score 0.41}}
[4]
[0.81]
9
0.61
false
"/en/search?q=whisky&after-doc-id=4&after-score=0.81"
;; get a :next link on page 3 to page 2
;; first-doc: {:index {:doc-id 15 :score 0.4}}
{:index {:doc-id 19 :score 0.21}}
[4 9]
[0.81 0.61]
14
0.41
false
(str "/en/search?q=whisky&after-doc-id=9&after-score=0.61&"
"pp-aid[]=4&"
"pp-as[]=0.81")
;; get a :next link on page 4 to page 3
;; first-doc: {:index {:doc-id 20 :score 0.2}}
{:index {:doc-id 24 :score 0.01}}
[4 9 14]
[0.81 0.61 0.41]
19
0.21
false
(str "/en/search?q=whisky&after-doc-id=14&after-score=0.41&"
"pp-aid[]=4&pp-aid[]=9&"
"pp-as[]=0.81&pp-as[]=0.61"))))
(deftest test-login-page-template
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (login-page-template "You need to log in!"))))]
(is (= (html/text (first (html/select resource [:#status-message])))
"You need to log in!"))))
(deftest test-admin-template
(is (= (html/html-resource (java.io.StringReader.
(slurp "src/templates/en/admin.html")))
(html/html-resource (java.io.StringReader.
(apply str (admin-template {})))))))
(comment
(deftest test-layout
(let [dummy-main (html/html-resource
(java.io.StringReader.
"<p id=\"dummy-resource\">Added</p>"))
default-resource (html/html-resource
(java.io.StringReader.
(slurp "src/templates/layout.html")))
resource (html/html-resource
(java.io.StringReader.
(apply str (layout {:title "foo"
:main dummy-main}))))]
(is (= (html/text (first (html/select resource [:title])))
"foo"))
(is (= (html/text (first (html/select resource [:#page-title])))
"foo"))
(is (= (html/text (first (html/select resource [:#dummy-resource])))
"Added"))
(testing "test without a :title"
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (layout {:main dummy-main}))))
default-title (html/text
(first (html/select default-resource [:title])))]
;; make sure the original template title is unchanged
(is (= (html/text (first (html/select resource [:title])))
default-title))
;; the #page-title div should be empty
(is (= (and (list? (html/select resource [:#page-title]))
(= (count (html/select resource [:#page-title])) 0))))
;; but the :main resource should still be added to the template
(is (= (html/text (first (html/select resource [:#dummy-resource])))
"Added"))))
(testing "test without any arguments"
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (layout {}))))]
(is (= (first
(:content
(first (html/select resource [:#main-page]))))
"\n \n \n ")))))))
(comment
(deftest test-article-model
(testing "test with title link as true"
(let [am (article-model {:slug "/en/blog/first"
:title "first"
:content "Welcome!"}
(clj-time.core/date-time 2012 2 3 16 39 07 232)
true)]
(is (= (first
(html/attr-values
(first (html/select am [:h4 :a])) :href))
"/en/blog/first"))
(are [selector value]
(= (html/text (first (html/select am selector))) value)
[:.month] "2"
[:.day] "3"
[:.year] "2012"
[:.hour] "16"
[:.minute] "39"
[:div.content] "Welcome!"))))
(testing "test with title link as false"
(let [am (article-model {:slug "/en/blog/first"
:title "first"
:content "Welcome!"}
(clj-time.core/date-time 2012 2 3 16 39 07 232)
false)]
(is (= (count (html/select am [:h4 :a])) 0)))))
(comment
(deftest test-blog-frontpage-view
(let [default-title (html/text
(first
(html/select
(html/html-resource
(java.io.StringReader.
(slurp "src/templates/layout.html")))
[:title])))
resource (html/html-resource
(java.io.StringReader.
(apply str
(blog-frontpage-view
{:documents
[{:title "0"
:slug "/blog/0"
:content "zero"
:published "2012-02-03T16:39:07.232Z"}
{:title "1"
:slug "/blog/1"
:content "one"
:published "2012-02-03T16:39:07.232Z"}
{:title "2"
:slug "/blog/2"
:content "two"
:published "2012-02-03T16:39:07.232Z"}]}
"Europe/Amsterdam"))))]
(testing "test if the title is correctly omitted"
(is (= (html/text (first (html/select resource [:title])))
default-title))
(is (= (and (list? (html/select resource [:#page-title]))
(= (count (html/select resource [:#page-title])) 0)))))
(testing "test if the title links are added correctly"
(are [n v]
(is (= (first (html/attr-values
(nth (html/select resource [:h4 :a]) n) :href))
v))
0 "/blog/0"
1 "/blog/1"
2 "/blog/2")
(are [n v]
(is (= (html/text (nth (html/select resource [:h4 :a]) n))
v))
0 "0"
1 "1"
2 "2"))
(testing "test if the content is added correctly"
(are [n v]
(is (= (html/text (nth (html/select resource [:div.content]) n))
v))
0 "zero"
1 "one"
2 "two"))
(testing "test if the datetime is added correctly"
(are [n v]
(is (= (html/text (nth (html/select resource [:.month]) n))
v))
0 "2"
1 "2"
2 "2")
(are [n v]
(is (= (html/text (nth (html/select resource [:.day]) n))
v))
0 "3"
1 "3"
2 "3")
(are [n v]
(is (= (html/text (nth (html/select resource [:.year]) n))
v))
0 "2012"
1 "2012"
2 "2012")
(are [n v]
(is (= (html/text (nth (html/select resource [:.hour]) n))
v))
0 "17"
1 "17"
2 "17")
(are [n v]
(is (= (html/text (nth (html/select resource [:.minute]) n))
v))
0 "39"
1 "39"
2 "39")))))
(comment
(deftest test-blog-article-view
(let [resource (html/html-resource
(java.io.StringReader.
(apply str
(blog-article-view
{:title "0"
:slug "/blog/0"
:content "zero"
:published "2012-02-03T16:39:07.232Z"}
"Europe/Amsterdam"))))]
(testing "test if the title is added correctly"
(is (= (html/text (first (html/select resource [:title])))
"0"))
(is (= (html/text (first (html/select resource [:#page-title])))
"0")))
(testing "test if the title link is omitted correctly"
(is (= (count (html/select resource [:h4 :a])) 0)))
(testing "test if the article values are set correctly"
(is (= (html/text (first (html/select resource [:div.content])))
"zero"))
(is (= (html/text (first (html/select resource [:.month]))) "2"))
(is (= (html/text (first (html/select resource [:.day]))) "3"))
(is (= (html/text (first (html/select resource [:.year]))) "2012"))
(is (= (html/text (first (html/select resource [:.hour]))) "17"))
(is (= (html/text (first (html/select resource [:.minute])))
"39"))))))
(deftest test-search-result-model
(is (= (:href
(:attrs
(first
(:content
(first
(search-result-model :en {:title "foo" :slug "/foo"}))))))
"/foo"))
(is (= (first
(:content
(first
(:content
(first
(search-result-model :en {:title "foo" :slug "/foo"}))))))
"foo")))
(deftest test-search-results-view
;; this is tested thoroughly elsewhere, so just
;; want to make sure there are no exceptions
(is (not (nil? (search-results-view "en"
5
{}
"whisky"
nil
nil
nil
nil
true
{})))))
|
60468
|
;; test/vix/test/views.clj tests for views namespace.
;; Copyright 2011-2012, Vixu.com, <NAME>. (<NAME> <<EMAIL>>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns vix.test.views
(:require [net.cgrand.enlive-html :as html])
(:use [vix.views] :reload)
(:use [clojure.test]))
(deftemplates dummy-tpl
{:en (java.io.StringReader. "<p id=\"msg\">message goes here</p>")
:nl (java.io.StringReader. "<div id=\"msg\">message goes here</div>")}
[msg]
[:#msg] (html/content msg))
(deftest test-deftemplates
(is (= (apply str (dummy-tpl :en "Hello, world!"))
"<html><body><p id=\"msg\">Hello, world!</p></body></html>"))
(is (= (apply str (dummy-tpl :nl "Hello, world!"))
"<html><body><div id=\"msg\">Hello, world!</div></body></html>"))
(is (= (dummy-tpl :qq "Hello, world!")
nil)))
(deftest test-make-pagination-uri
(testing "test :next links"
(are [last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
expected-uri]
(= (make-pagination-uri "en"
"whisky"
last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
:next)
expected-uri)
;; get a :next link on page 0 to page 1
;; first-doc: {:index {:doc-id 0 :score 1.0}}
{:index {:doc-id 4 :score 0.81}}
nil
nil
nil
nil
true
(str "/en/search?q=whisky&after-doc-id=4&after-score=0.81")
;; get a :next link on page 1 to page 2
;; first-doc: {:index {:doc-id 5 :score 0.8}}
{:index {:doc-id 9 :score 0.61}}
[]
[]
4
0.81
false
(str "/en/search?q=whisky&after-doc-id=9&after-score=0.61&"
"pp-aid[]=4&"
"pp-as[]=0.81")
;; get a :next link on page 2 to page 3
;; first-doc: {:index {:doc-id 10 :score 0.6}}
{:index {:doc-id 14 :score 0.41}}
[4]
[0.81]
9
0.61
false
(str "/en/search?q=whisky&after-doc-id=14&after-score=0.41&"
"pp-aid[]=4&pp-aid[]=9&"
"pp-as[]=0.81&pp-as[]=0.61")
;; get a :next link on page 3 to page 4
;; first-doc: {:index {:doc-id 15 :score 0.4}}
{:index {:doc-id 19 :score 0.21}}
[4 9]
[0.81 0.61]
14
0.41
false
(str "/en/search?q=whisky&after-doc-id=19&after-score=0.21&"
"pp-aid[]=4&pp-aid[]=9&pp-aid[]=14&"
"pp-as[]=0.81&pp-as[]=0.61&pp-as[]=0.41")))
(testing "test :previous links"
(are [last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
expected-uri]
(= (make-pagination-uri "en"
"whisky"
last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
:previous)
expected-uri)
;; get a :previous link on page 0 to page -1
;; first-doc: {:index {:doc-id 0 :score 1.0}}
{:index {:doc-id 4 :score 0.81}}
nil
nil
nil
nil
true
nil ;; shouldn't return a link
;; get a :next link on page 1 to page 0
;; first-doc: {:index {:doc-id 5 :score 0.8}}
{:index {:doc-id 9 :score 0.61}}
[]
[]
4
0.81
false
"/en/search?q=whisky"
;; get a :next link on page 2 to page 1
;; first-doc: {:index {:doc-id 10 :score 0.6}}
{:index {:doc-id 14 :score 0.41}}
[4]
[0.81]
9
0.61
false
"/en/search?q=whisky&after-doc-id=4&after-score=0.81"
;; get a :next link on page 3 to page 2
;; first-doc: {:index {:doc-id 15 :score 0.4}}
{:index {:doc-id 19 :score 0.21}}
[4 9]
[0.81 0.61]
14
0.41
false
(str "/en/search?q=whisky&after-doc-id=9&after-score=0.61&"
"pp-aid[]=4&"
"pp-as[]=0.81")
;; get a :next link on page 4 to page 3
;; first-doc: {:index {:doc-id 20 :score 0.2}}
{:index {:doc-id 24 :score 0.01}}
[4 9 14]
[0.81 0.61 0.41]
19
0.21
false
(str "/en/search?q=whisky&after-doc-id=14&after-score=0.41&"
"pp-aid[]=4&pp-aid[]=9&"
"pp-as[]=0.81&pp-as[]=0.61"))))
(deftest test-login-page-template
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (login-page-template "You need to log in!"))))]
(is (= (html/text (first (html/select resource [:#status-message])))
"You need to log in!"))))
(deftest test-admin-template
(is (= (html/html-resource (java.io.StringReader.
(slurp "src/templates/en/admin.html")))
(html/html-resource (java.io.StringReader.
(apply str (admin-template {})))))))
(comment
(deftest test-layout
(let [dummy-main (html/html-resource
(java.io.StringReader.
"<p id=\"dummy-resource\">Added</p>"))
default-resource (html/html-resource
(java.io.StringReader.
(slurp "src/templates/layout.html")))
resource (html/html-resource
(java.io.StringReader.
(apply str (layout {:title "foo"
:main dummy-main}))))]
(is (= (html/text (first (html/select resource [:title])))
"foo"))
(is (= (html/text (first (html/select resource [:#page-title])))
"foo"))
(is (= (html/text (first (html/select resource [:#dummy-resource])))
"Added"))
(testing "test without a :title"
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (layout {:main dummy-main}))))
default-title (html/text
(first (html/select default-resource [:title])))]
;; make sure the original template title is unchanged
(is (= (html/text (first (html/select resource [:title])))
default-title))
;; the #page-title div should be empty
(is (= (and (list? (html/select resource [:#page-title]))
(= (count (html/select resource [:#page-title])) 0))))
;; but the :main resource should still be added to the template
(is (= (html/text (first (html/select resource [:#dummy-resource])))
"Added"))))
(testing "test without any arguments"
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (layout {}))))]
(is (= (first
(:content
(first (html/select resource [:#main-page]))))
"\n \n \n ")))))))
(comment
(deftest test-article-model
(testing "test with title link as true"
(let [am (article-model {:slug "/en/blog/first"
:title "first"
:content "Welcome!"}
(clj-time.core/date-time 2012 2 3 16 39 07 232)
true)]
(is (= (first
(html/attr-values
(first (html/select am [:h4 :a])) :href))
"/en/blog/first"))
(are [selector value]
(= (html/text (first (html/select am selector))) value)
[:.month] "2"
[:.day] "3"
[:.year] "2012"
[:.hour] "16"
[:.minute] "39"
[:div.content] "Welcome!"))))
(testing "test with title link as false"
(let [am (article-model {:slug "/en/blog/first"
:title "first"
:content "Welcome!"}
(clj-time.core/date-time 2012 2 3 16 39 07 232)
false)]
(is (= (count (html/select am [:h4 :a])) 0)))))
(comment
(deftest test-blog-frontpage-view
(let [default-title (html/text
(first
(html/select
(html/html-resource
(java.io.StringReader.
(slurp "src/templates/layout.html")))
[:title])))
resource (html/html-resource
(java.io.StringReader.
(apply str
(blog-frontpage-view
{:documents
[{:title "0"
:slug "/blog/0"
:content "zero"
:published "2012-02-03T16:39:07.232Z"}
{:title "1"
:slug "/blog/1"
:content "one"
:published "2012-02-03T16:39:07.232Z"}
{:title "2"
:slug "/blog/2"
:content "two"
:published "2012-02-03T16:39:07.232Z"}]}
"Europe/Amsterdam"))))]
(testing "test if the title is correctly omitted"
(is (= (html/text (first (html/select resource [:title])))
default-title))
(is (= (and (list? (html/select resource [:#page-title]))
(= (count (html/select resource [:#page-title])) 0)))))
(testing "test if the title links are added correctly"
(are [n v]
(is (= (first (html/attr-values
(nth (html/select resource [:h4 :a]) n) :href))
v))
0 "/blog/0"
1 "/blog/1"
2 "/blog/2")
(are [n v]
(is (= (html/text (nth (html/select resource [:h4 :a]) n))
v))
0 "0"
1 "1"
2 "2"))
(testing "test if the content is added correctly"
(are [n v]
(is (= (html/text (nth (html/select resource [:div.content]) n))
v))
0 "zero"
1 "one"
2 "two"))
(testing "test if the datetime is added correctly"
(are [n v]
(is (= (html/text (nth (html/select resource [:.month]) n))
v))
0 "2"
1 "2"
2 "2")
(are [n v]
(is (= (html/text (nth (html/select resource [:.day]) n))
v))
0 "3"
1 "3"
2 "3")
(are [n v]
(is (= (html/text (nth (html/select resource [:.year]) n))
v))
0 "2012"
1 "2012"
2 "2012")
(are [n v]
(is (= (html/text (nth (html/select resource [:.hour]) n))
v))
0 "17"
1 "17"
2 "17")
(are [n v]
(is (= (html/text (nth (html/select resource [:.minute]) n))
v))
0 "39"
1 "39"
2 "39")))))
(comment
(deftest test-blog-article-view
(let [resource (html/html-resource
(java.io.StringReader.
(apply str
(blog-article-view
{:title "0"
:slug "/blog/0"
:content "zero"
:published "2012-02-03T16:39:07.232Z"}
"Europe/Amsterdam"))))]
(testing "test if the title is added correctly"
(is (= (html/text (first (html/select resource [:title])))
"0"))
(is (= (html/text (first (html/select resource [:#page-title])))
"0")))
(testing "test if the title link is omitted correctly"
(is (= (count (html/select resource [:h4 :a])) 0)))
(testing "test if the article values are set correctly"
(is (= (html/text (first (html/select resource [:div.content])))
"zero"))
(is (= (html/text (first (html/select resource [:.month]))) "2"))
(is (= (html/text (first (html/select resource [:.day]))) "3"))
(is (= (html/text (first (html/select resource [:.year]))) "2012"))
(is (= (html/text (first (html/select resource [:.hour]))) "17"))
(is (= (html/text (first (html/select resource [:.minute])))
"39"))))))
(deftest test-search-result-model
(is (= (:href
(:attrs
(first
(:content
(first
(search-result-model :en {:title "foo" :slug "/foo"}))))))
"/foo"))
(is (= (first
(:content
(first
(:content
(first
(search-result-model :en {:title "foo" :slug "/foo"}))))))
"foo")))
(deftest test-search-results-view
;; this is tested thoroughly elsewhere, so just
;; want to make sure there are no exceptions
(is (not (nil? (search-results-view "en"
5
{}
"whisky"
nil
nil
nil
nil
true
{})))))
| true |
;; test/vix/test/views.clj tests for views namespace.
;; Copyright 2011-2012, Vixu.com, PI:NAME:<NAME>END_PI. (PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns vix.test.views
(:require [net.cgrand.enlive-html :as html])
(:use [vix.views] :reload)
(:use [clojure.test]))
(deftemplates dummy-tpl
{:en (java.io.StringReader. "<p id=\"msg\">message goes here</p>")
:nl (java.io.StringReader. "<div id=\"msg\">message goes here</div>")}
[msg]
[:#msg] (html/content msg))
(deftest test-deftemplates
(is (= (apply str (dummy-tpl :en "Hello, world!"))
"<html><body><p id=\"msg\">Hello, world!</p></body></html>"))
(is (= (apply str (dummy-tpl :nl "Hello, world!"))
"<html><body><div id=\"msg\">Hello, world!</div></body></html>"))
(is (= (dummy-tpl :qq "Hello, world!")
nil)))
(deftest test-make-pagination-uri
(testing "test :next links"
(are [last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
expected-uri]
(= (make-pagination-uri "en"
"whisky"
last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
:next)
expected-uri)
;; get a :next link on page 0 to page 1
;; first-doc: {:index {:doc-id 0 :score 1.0}}
{:index {:doc-id 4 :score 0.81}}
nil
nil
nil
nil
true
(str "/en/search?q=whisky&after-doc-id=4&after-score=0.81")
;; get a :next link on page 1 to page 2
;; first-doc: {:index {:doc-id 5 :score 0.8}}
{:index {:doc-id 9 :score 0.61}}
[]
[]
4
0.81
false
(str "/en/search?q=whisky&after-doc-id=9&after-score=0.61&"
"pp-aid[]=4&"
"pp-as[]=0.81")
;; get a :next link on page 2 to page 3
;; first-doc: {:index {:doc-id 10 :score 0.6}}
{:index {:doc-id 14 :score 0.41}}
[4]
[0.81]
9
0.61
false
(str "/en/search?q=whisky&after-doc-id=14&after-score=0.41&"
"pp-aid[]=4&pp-aid[]=9&"
"pp-as[]=0.81&pp-as[]=0.61")
;; get a :next link on page 3 to page 4
;; first-doc: {:index {:doc-id 15 :score 0.4}}
{:index {:doc-id 19 :score 0.21}}
[4 9]
[0.81 0.61]
14
0.41
false
(str "/en/search?q=whisky&after-doc-id=19&after-score=0.21&"
"pp-aid[]=4&pp-aid[]=9&pp-aid[]=14&"
"pp-as[]=0.81&pp-as[]=0.61&pp-as[]=0.41")))
(testing "test :previous links"
(are [last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
expected-uri]
(= (make-pagination-uri "en"
"whisky"
last-doc
pp-after-doc-id
pp-after-score
after-doc-id
after-score
first-page?
:previous)
expected-uri)
;; get a :previous link on page 0 to page -1
;; first-doc: {:index {:doc-id 0 :score 1.0}}
{:index {:doc-id 4 :score 0.81}}
nil
nil
nil
nil
true
nil ;; shouldn't return a link
;; get a :next link on page 1 to page 0
;; first-doc: {:index {:doc-id 5 :score 0.8}}
{:index {:doc-id 9 :score 0.61}}
[]
[]
4
0.81
false
"/en/search?q=whisky"
;; get a :next link on page 2 to page 1
;; first-doc: {:index {:doc-id 10 :score 0.6}}
{:index {:doc-id 14 :score 0.41}}
[4]
[0.81]
9
0.61
false
"/en/search?q=whisky&after-doc-id=4&after-score=0.81"
;; get a :next link on page 3 to page 2
;; first-doc: {:index {:doc-id 15 :score 0.4}}
{:index {:doc-id 19 :score 0.21}}
[4 9]
[0.81 0.61]
14
0.41
false
(str "/en/search?q=whisky&after-doc-id=9&after-score=0.61&"
"pp-aid[]=4&"
"pp-as[]=0.81")
;; get a :next link on page 4 to page 3
;; first-doc: {:index {:doc-id 20 :score 0.2}}
{:index {:doc-id 24 :score 0.01}}
[4 9 14]
[0.81 0.61 0.41]
19
0.21
false
(str "/en/search?q=whisky&after-doc-id=14&after-score=0.41&"
"pp-aid[]=4&pp-aid[]=9&"
"pp-as[]=0.81&pp-as[]=0.61"))))
(deftest test-login-page-template
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (login-page-template "You need to log in!"))))]
(is (= (html/text (first (html/select resource [:#status-message])))
"You need to log in!"))))
(deftest test-admin-template
(is (= (html/html-resource (java.io.StringReader.
(slurp "src/templates/en/admin.html")))
(html/html-resource (java.io.StringReader.
(apply str (admin-template {})))))))
(comment
(deftest test-layout
(let [dummy-main (html/html-resource
(java.io.StringReader.
"<p id=\"dummy-resource\">Added</p>"))
default-resource (html/html-resource
(java.io.StringReader.
(slurp "src/templates/layout.html")))
resource (html/html-resource
(java.io.StringReader.
(apply str (layout {:title "foo"
:main dummy-main}))))]
(is (= (html/text (first (html/select resource [:title])))
"foo"))
(is (= (html/text (first (html/select resource [:#page-title])))
"foo"))
(is (= (html/text (first (html/select resource [:#dummy-resource])))
"Added"))
(testing "test without a :title"
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (layout {:main dummy-main}))))
default-title (html/text
(first (html/select default-resource [:title])))]
;; make sure the original template title is unchanged
(is (= (html/text (first (html/select resource [:title])))
default-title))
;; the #page-title div should be empty
(is (= (and (list? (html/select resource [:#page-title]))
(= (count (html/select resource [:#page-title])) 0))))
;; but the :main resource should still be added to the template
(is (= (html/text (first (html/select resource [:#dummy-resource])))
"Added"))))
(testing "test without any arguments"
(let [resource (html/html-resource
(java.io.StringReader.
(apply str (layout {}))))]
(is (= (first
(:content
(first (html/select resource [:#main-page]))))
"\n \n \n ")))))))
(comment
(deftest test-article-model
(testing "test with title link as true"
(let [am (article-model {:slug "/en/blog/first"
:title "first"
:content "Welcome!"}
(clj-time.core/date-time 2012 2 3 16 39 07 232)
true)]
(is (= (first
(html/attr-values
(first (html/select am [:h4 :a])) :href))
"/en/blog/first"))
(are [selector value]
(= (html/text (first (html/select am selector))) value)
[:.month] "2"
[:.day] "3"
[:.year] "2012"
[:.hour] "16"
[:.minute] "39"
[:div.content] "Welcome!"))))
(testing "test with title link as false"
(let [am (article-model {:slug "/en/blog/first"
:title "first"
:content "Welcome!"}
(clj-time.core/date-time 2012 2 3 16 39 07 232)
false)]
(is (= (count (html/select am [:h4 :a])) 0)))))
(comment
(deftest test-blog-frontpage-view
(let [default-title (html/text
(first
(html/select
(html/html-resource
(java.io.StringReader.
(slurp "src/templates/layout.html")))
[:title])))
resource (html/html-resource
(java.io.StringReader.
(apply str
(blog-frontpage-view
{:documents
[{:title "0"
:slug "/blog/0"
:content "zero"
:published "2012-02-03T16:39:07.232Z"}
{:title "1"
:slug "/blog/1"
:content "one"
:published "2012-02-03T16:39:07.232Z"}
{:title "2"
:slug "/blog/2"
:content "two"
:published "2012-02-03T16:39:07.232Z"}]}
"Europe/Amsterdam"))))]
(testing "test if the title is correctly omitted"
(is (= (html/text (first (html/select resource [:title])))
default-title))
(is (= (and (list? (html/select resource [:#page-title]))
(= (count (html/select resource [:#page-title])) 0)))))
(testing "test if the title links are added correctly"
(are [n v]
(is (= (first (html/attr-values
(nth (html/select resource [:h4 :a]) n) :href))
v))
0 "/blog/0"
1 "/blog/1"
2 "/blog/2")
(are [n v]
(is (= (html/text (nth (html/select resource [:h4 :a]) n))
v))
0 "0"
1 "1"
2 "2"))
(testing "test if the content is added correctly"
(are [n v]
(is (= (html/text (nth (html/select resource [:div.content]) n))
v))
0 "zero"
1 "one"
2 "two"))
(testing "test if the datetime is added correctly"
(are [n v]
(is (= (html/text (nth (html/select resource [:.month]) n))
v))
0 "2"
1 "2"
2 "2")
(are [n v]
(is (= (html/text (nth (html/select resource [:.day]) n))
v))
0 "3"
1 "3"
2 "3")
(are [n v]
(is (= (html/text (nth (html/select resource [:.year]) n))
v))
0 "2012"
1 "2012"
2 "2012")
(are [n v]
(is (= (html/text (nth (html/select resource [:.hour]) n))
v))
0 "17"
1 "17"
2 "17")
(are [n v]
(is (= (html/text (nth (html/select resource [:.minute]) n))
v))
0 "39"
1 "39"
2 "39")))))
(comment
(deftest test-blog-article-view
(let [resource (html/html-resource
(java.io.StringReader.
(apply str
(blog-article-view
{:title "0"
:slug "/blog/0"
:content "zero"
:published "2012-02-03T16:39:07.232Z"}
"Europe/Amsterdam"))))]
(testing "test if the title is added correctly"
(is (= (html/text (first (html/select resource [:title])))
"0"))
(is (= (html/text (first (html/select resource [:#page-title])))
"0")))
(testing "test if the title link is omitted correctly"
(is (= (count (html/select resource [:h4 :a])) 0)))
(testing "test if the article values are set correctly"
(is (= (html/text (first (html/select resource [:div.content])))
"zero"))
(is (= (html/text (first (html/select resource [:.month]))) "2"))
(is (= (html/text (first (html/select resource [:.day]))) "3"))
(is (= (html/text (first (html/select resource [:.year]))) "2012"))
(is (= (html/text (first (html/select resource [:.hour]))) "17"))
(is (= (html/text (first (html/select resource [:.minute])))
"39"))))))
(deftest test-search-result-model
(is (= (:href
(:attrs
(first
(:content
(first
(search-result-model :en {:title "foo" :slug "/foo"}))))))
"/foo"))
(is (= (first
(:content
(first
(:content
(first
(search-result-model :en {:title "foo" :slug "/foo"}))))))
"foo")))
(deftest test-search-results-view
;; this is tested thoroughly elsewhere, so just
;; want to make sure there are no exceptions
(is (not (nil? (search-results-view "en"
5
{}
"whisky"
nil
nil
nil
nil
true
{})))))
|
[
{
"context": "ula-widgets.utils :as utils]))\n\n(def panel-key\n :app-panel-widget)\n\n(def panel-path\n [:panels panel-k",
"end": 136,
"score": 0.5183499455451965,
"start": 133,
"tag": "KEY",
"value": "app"
},
{
"context": "widgets.utils :as utils]))\n\n(def panel-key\n :app-panel-widget)\n\n(def panel-path\n [:panels panel-key])\n\n",
"end": 142,
"score": 0.5299286246299744,
"start": 137,
"tag": "KEY",
"value": "panel"
}
] |
packages/reagent/src/cljs/nebula_widgets/kitchen_sink/panels/app_panel_widget/common.cljs
|
mt0erfztxt/nebula-widgets
| 0 |
(ns nebula-widgets.kitchen-sink.panels.app-panel-widget.common
(:require
[nebula-widgets.utils :as utils]))
(def panel-key
:app-panel-widget)
(def panel-path
[:panels panel-key])
(def panel-path->keyword
(apply partial utils/path->keyword panel-path))
(def knobs
(utils/expand-paths
[:footer
:header
:layout
[:sidebars
[:left :collapsed :exists :gutter :size]
[:right :collapsed :exists :gutter :size]]
:toolbars]))
|
80454
|
(ns nebula-widgets.kitchen-sink.panels.app-panel-widget.common
(:require
[nebula-widgets.utils :as utils]))
(def panel-key
:<KEY>-<KEY>-widget)
(def panel-path
[:panels panel-key])
(def panel-path->keyword
(apply partial utils/path->keyword panel-path))
(def knobs
(utils/expand-paths
[:footer
:header
:layout
[:sidebars
[:left :collapsed :exists :gutter :size]
[:right :collapsed :exists :gutter :size]]
:toolbars]))
| true |
(ns nebula-widgets.kitchen-sink.panels.app-panel-widget.common
(:require
[nebula-widgets.utils :as utils]))
(def panel-key
:PI:KEY:<KEY>END_PI-PI:KEY:<KEY>END_PI-widget)
(def panel-path
[:panels panel-key])
(def panel-path->keyword
(apply partial utils/path->keyword panel-path))
(def knobs
(utils/expand-paths
[:footer
:header
:layout
[:sidebars
[:left :collapsed :exists :gutter :size]
[:right :collapsed :exists :gutter :size]]
:toolbars]))
|
[
{
"context": "h core libraries.\"\n :url \"https://www.github.com/ddossot/clatch\"\n :license {:name \"The MIT License (MIT)\"",
"end": 137,
"score": 0.9992143511772156,
"start": 130,
"tag": "USERNAME",
"value": "ddossot"
},
{
"context": "ses/MIT\"\n :comments \"Copyright (c) 2015 David Dossot\"}\n\n :plugins [[lein-modules \"0.3.11\"]]\n\n :profi",
"end": 296,
"score": 0.9998835325241089,
"start": 284,
"tag": "NAME",
"value": "David Dossot"
}
] |
clatch-core/project.clj
|
ddossot/clatch
| 0 |
(defproject net.dossot.clatch/clatch-core "1.0.0-SNAPSHOT"
:description "Clatch core libraries."
:url "https://www.github.com/ddossot/clatch"
:license {:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"
:comments "Copyright (c) 2015 David Dossot"}
:plugins [[lein-modules "0.3.11"]]
:profiles {:dev {:dependencies [[com.badlogicgames.gdx/gdx-backend-lwjgl :gdx-version]]
:eastwood {:exclude-namespaces [clatch]
:config-files ["eastwood-config.clj"]}}}
:dependencies
[
[org.clojure/clojure :clj-version]
[play-clj "0.4.7" :exclusions [com.badlogicgames.gdx/gdx]]
[prismatic/schema "1.0.0"]
[manifold "0.1.1-alpha3"]
[potemkin "0.4.1"]
])
|
77940
|
(defproject net.dossot.clatch/clatch-core "1.0.0-SNAPSHOT"
:description "Clatch core libraries."
:url "https://www.github.com/ddossot/clatch"
:license {:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"
:comments "Copyright (c) 2015 <NAME>"}
:plugins [[lein-modules "0.3.11"]]
:profiles {:dev {:dependencies [[com.badlogicgames.gdx/gdx-backend-lwjgl :gdx-version]]
:eastwood {:exclude-namespaces [clatch]
:config-files ["eastwood-config.clj"]}}}
:dependencies
[
[org.clojure/clojure :clj-version]
[play-clj "0.4.7" :exclusions [com.badlogicgames.gdx/gdx]]
[prismatic/schema "1.0.0"]
[manifold "0.1.1-alpha3"]
[potemkin "0.4.1"]
])
| true |
(defproject net.dossot.clatch/clatch-core "1.0.0-SNAPSHOT"
:description "Clatch core libraries."
:url "https://www.github.com/ddossot/clatch"
:license {:name "The MIT License (MIT)"
:url "http://opensource.org/licenses/MIT"
:comments "Copyright (c) 2015 PI:NAME:<NAME>END_PI"}
:plugins [[lein-modules "0.3.11"]]
:profiles {:dev {:dependencies [[com.badlogicgames.gdx/gdx-backend-lwjgl :gdx-version]]
:eastwood {:exclude-namespaces [clatch]
:config-files ["eastwood-config.clj"]}}}
:dependencies
[
[org.clojure/clojure :clj-version]
[play-clj "0.4.7" :exclusions [com.badlogicgames.gdx/gdx]]
[prismatic/schema "1.0.0"]
[manifold "0.1.1-alpha3"]
[potemkin "0.4.1"]
])
|
[
{
"context": "nd the latest version here:\n;; https://github.com/BetterThanTomorrow/dram/blob/dev/drams/welcome_to_clojure.clj\n\n(comm",
"end": 1985,
"score": 0.9975467324256897,
"start": 1967,
"tag": "USERNAME",
"value": "BetterThanTomorrow"
},
{
"context": " ;; among the commands.)\n ;; https://github.com/clojure-emacs/clj-refactor.el/wiki/cljr-unwind-all\n\n ;; There ",
"end": 31666,
"score": 0.998670756816864,
"start": 31653,
"tag": "USERNAME",
"value": "clojure-emacs"
},
{
"context": " (* 2 3) => 6 \n\n ;; See ”Threading with Style” by Stuart Sierra\n ;; for idiomatic use of the threading facilitie",
"end": 33208,
"score": 0.9985038042068481,
"start": 33195,
"tag": "NAME",
"value": "Stuart Sierra"
},
{
"context": "ad lead\n :members members})\n\n (lead+members \"Dave Mustain\"\n \"Marty Friedman\"\n ",
"end": 43994,
"score": 0.9998694658279419,
"start": 43982,
"tag": "NAME",
"value": "Dave Mustain"
},
{
"context": "\n\n (lead+members \"Dave Mustain\"\n \"Marty Friedman\"\n \"Nick Menza\"\n \"Da",
"end": 44027,
"score": 0.9998636245727539,
"start": 44013,
"tag": "NAME",
"value": "Marty Friedman"
},
{
"context": " \"Marty Friedman\"\n \"Nick Menza\"\n \"David Ellefson\")\n\n ;; == Multi",
"end": 44056,
"score": 0.9998741149902344,
"start": 44046,
"tag": "NAME",
"value": "Nick Menza"
},
{
"context": "an\"\n \"Nick Menza\"\n \"David Ellefson\")\n\n ;; == Multi-arity ==\n ;; Clojure supports f",
"end": 44089,
"score": 0.9998666644096375,
"start": 44075,
"tag": "NAME",
"value": "David Ellefson"
},
{
"context": "}}))\n\n (def bob-coords-fn (named-coords-factory \"Bob\"))\n (def fred-coords-fn (named-coords-factory \"F",
"end": 47684,
"score": 0.982029378414154,
"start": 47681,
"tag": "NAME",
"value": "Bob"
},
{
"context": "b\"))\n (def fred-coords-fn (named-coords-factory \"Fred\"))\n\n (bob-coords-fn 0 0)\n (fred-coords-fn 5 5)\n",
"end": 47737,
"score": 0.9971696138381958,
"start": 47733,
"tag": "NAME",
"value": "Fred"
},
{
"context": "fact in Clojure reducing is so important that\n ;; Rich Hickey has added a whole library with reducers\n ;; pack",
"end": 58918,
"score": 0.9998555183410645,
"start": 58907,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "ce/reducers\n ;; Again, the Functional Design duo, Nate Jones, and\n ;; Christoph Neumann have examined this li",
"end": 59081,
"score": 0.9997852444648743,
"start": 59071,
"tag": "NAME",
"value": "Nate Jones"
},
{
"context": "n, the Functional Design duo, Nate Jones, and\n ;; Christoph Neumann have examined this library\n ;; a bit:\n ;; https",
"end": 59109,
"score": 0.999786913394928,
"start": 59092,
"tag": "NAME",
"value": "Christoph Neumann"
},
{
"context": "\n;; ... Instead we are picking up that Nate and\n;; Christoph mention three super important concepts\n;; in thos",
"end": 59449,
"score": 0.9464075565338135,
"start": 59440,
"tag": "NAME",
"value": "Christoph"
},
{
"context": " ;; (except in the name)\n\n (def universa {:one {\"Alice\" {:x 100\n :y 100\n ",
"end": 62491,
"score": 0.9997994899749756,
"start": 62486,
"tag": "NAME",
"value": "Alice"
},
{
"context": " :z 100}\n \"Bob\" {:x 100\n :y 100\n ",
"end": 62607,
"score": 0.9998155236244202,
"start": 62604,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :z 100}}\n :two {\"Alice\" {:x 100\n :y 100\n ",
"end": 62722,
"score": 0.9997917413711548,
"start": 62717,
"tag": "NAME",
"value": "Alice"
},
{
"context": " :z 100}\n \"Bob\" {:x 100\n :y 100\n ",
"end": 62838,
"score": 0.9996873140335083,
"start": 62835,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ne about\n ;; solving problems the Clojure way, by Rafal\n ;; Dittwald:\n ;; https://www.youtube.com/watch",
"end": 64097,
"score": 0.9992814064025879,
"start": 64092,
"tag": "NAME",
"value": "Rafal"
},
{
"context": ";; solving problems the Clojure way, by Rafal\n ;; Dittwald:\n ;; https://www.youtube.com/watch?v=vK1DazRK_a0",
"end": 64111,
"score": 0.9403252601623535,
"start": 64103,
"tag": "NAME",
"value": "Dittwald"
},
{
"context": "Clojure in the video\n\n ;; Of course, in the talk, Rafal is not only\n ;; pretending data is immutable. He",
"end": 64248,
"score": 0.9934256672859192,
"start": 64243,
"tag": "NAME",
"value": "Rafal"
}
] |
drams/welcome_to_clojure.clj
|
ieugen/dram
| 0 |
(ns welcome-to-clojure
(:require [clojure.repl :refer [source apropos dir pst doc find-doc]]
[clojure.string :as string]
[clojure.test :refer [is are]]))
;; Welcome to Clojure! ♥️
;; Start with loading this file.
;; Ctrl+Alt+C Enter
;; Then evaluate this expression with Alt+Enter:
"Hello World"
;; That's a concise Hello World for any language.
;; And note that there are no parens. 😀
;; This guide will try to give you a basic
;; understanding of the Clojure language. Basic in
;; the sense that it is not extensive. Basic in the
;; sense that it is foundational, building from first
;; principles in order to make the Clojure journey
;; you have ahead easier to comprehend.
;; With the foundations in place you'll have a good
;; chance of having the right gut feeling for how to
;; code something, how to formulate your questions,
;; how to search effectively for information, how to make
;; sense of code you stumble across, and so on.
;; There will be links here and there, ctrl/cmd-click
;; those to open them in a browser. Here's the first
;; such link;
;; https://clojure.org/guides/learn/syntax
;; There you can read more about the concepts
;; mentioned in this guide.
;; The way to use the guide is to read about the
;; concepts and evaluate the examples. Sometimes there
;; will be exercises in the text. Don't limit your
;; exercising to those, though. Please feel encouraged
;; to edit the examples, and add new code
;; and evaluate that. Evaluate this to warm up:
(comment
(str "Welcome"
" to "
"Clojure!"
" "
"♥️"))
;; Then see what happens if you throw in some numbers
;; here and there and evaluate again.
;; NB: This is work in progress...
;; When you fire up the Getting Started REPL the next
;; time, you will be presented with the option to
;; download new files or continue with the files you
;; have. You can also always find the latest version here:
;; https://github.com/BetterThanTomorrow/dram/blob/dev/drams/welcome_to_clojure.clj
(comment
;; = EXPRESSIONS =
;; In Clojure everything is an expression.
;; (There are no statements.) Unless there is
;; an error when evaluating an expression, there
;; is always a return value (which is sometimes `nil`).
;; An important aspect of this is that the result
;; of an expression is always the last form/expression
;; evaluated. E.g. if you have a function defined
;; like so:
(defn last-eval-wins []
(println 'side-effect-1)
1
(println 'side-effect-2)
2)
;; This defines a function named
;; `last-eval-wins`, taking no arguments, with four
;; expressions in its function body. (We'll return to
;; defining functions later.)
;; Calling the function
(last-eval-wins) ; <- Evaluate that 😄
;; will cause all four expressions in the function
;; body to be evaluated. The result of the call will
;; be the last expression that was evaluated.
;; In the output window you will also see the
;; `println` calls happening. They are also
;; expressions, evaluating to `nil`.
(println 'prints-this-evaluates-to-nil)
;; Expressions are composed from literals (evaluating
;; to themselves) and/or calls to either:
;; * special forms
;; * macros
;; * functions
;; ”Hello World” at the beginning of this guide is a
;; literal string (thus, it evaluates to itself).
;; More about literals in the next section.
;; Calls are written as lists with the called thing
;; as the first element.
(def foo "foo") ; Calls the special form `def`,
; evaluates to the var it creates
; (More on this later)
(for [x '(1 2 3) ; Calls the macro `for`
y '(:a :b)] ; (List comprehension)
[x y])
(str 1 2 3) ; Calls the function `str` with the
; arguments 1, 2, and 3.
)
(comment
;; = LITERALS =
;; Literals evaluate to themselves.
;; (Remember your friends:
;; Alt+Enter and Ctrl+Enter)
;; Numeric types
18 ; integer
-1.8 ; floating point
0.18e2 ; exponent
18.0M ; big decimal
18/324 ; ratio
18N ; big integer
0x12 ; hex
022 ; octal
2r10010 ; base 2
;; Character types
"hello" ; string
\e ; character
#"[0-9]+" ; regular expression
;; Symbols and idents
map ; symbol
+ ; symbol - most punctuation allowed
clojure.core/+ ; namespaced symbol
nil ; null/nil value (named in the LISP tradition)
true false ; booleans
:alpha ; keyword
:release/alpha ; namespaced keyword
::alpha ; namespaced keyword,
; in current namespace
;; == KEYWORDS ==
;; Keywords are start with a `:`. They are a thing
;; in themselves, often used as identifiers and as
;; keys in maps (more on maps later). Keywords are
;; very memory and speed efficient.
;; The same keyword is of course equal to itself
(= :foo :foo)
;; It is, however, also identical to itself
(identical? :foo :foo)
;; This means it is the same thing, occupying the
;; same (very tiny) place in memory.
;; Even if you construct a non-literal keyword
;; it remains identical to it's literal form
(identical? (keyword "foo") :foo)
;; This holds true for your whole Clojure program.
;; Keywords are global. There is namespace syntax
;; for them, so that you can have control of this.
;; Keywords are also functions, actually. But more
;; on that later. For now let it suffice to say
;; that keywords have a very special and important
;; role in most Clojure programs.
;; == STRINGS ==
;; Somewhere in between the atomic literals and
;; the collections we have strings. They are sometimes
;; treated as sequences (a cool abstraction I'll
;; talk more about).
;; Strings are enclosed by double quotes.
"A string can be
multi-line, but will contain any leading spaces."
"Write strings
like this, if leading spaces are no-no."
;; (The single quote is used for something else.
;; You'll see for what a bit later.)
)
(comment
;; = NAMESPACES =
;; Important as namespaces are, we won't dwell on
;; the subject very much in this guide. The official
;; docs make them the best justice:
;; https://clojure.org/reference/namespaces
;;
;; There are some things we really need to know
;; though...
;; Clojure symbols are defined in namespaces (With
;; the `def `special form) where they are reachable
;; from any other namespace.
(def foo-2 "foo")
;; Also know that there is such a thing as the
;; current namespace. (A bit like the current working
;; directory in the shell.) When you evaluated the
;; `def` form above, you'll saw where `foo-2` got
;; defined.
;; When evaluating a symbol from any namespace it
;; must have been defined, or the compiler will
;; complain, and throw
foo-3
;; The namespace also needs to have been created
some-namespace/foo
;; If you have loaded the `hello_repl.clj` file
;; the `hello-repl` namespace is created and its
;; top level symbols are defined (not the ones
;; hidden in `(comment ...)` forms, because the
;; `comment` macro ignores the body and just
;; evaluates to/returns `nil`)
hello-repl/greet
(hello-repl/greet "from the welcome-to-clojure namespace")
;; If those throw, you need to first load
;; `hello_repl.clj`, or at least evaluate its `ns`
;; form and the `greet` form.
;; It is not to recommend that you rely on some
;; namespace existing like this though. That makes
;; your code brittle. It is better to `require`
;; the namespace. If you haven't loaded it, you
;; can do that in the same go:
(require 'hello-paredit :reload)
hello-paredit/strict-greet
(hello-paredit/strict-greet "World")
;; For most Clojure code you write you will arrange
;; it into separate files with one namespace each,
;; and use the `ns` form (that starts most Clojure
;; files) to `:require` the needed namespaces, aliasing
;; them to something convenient and sometimes `:refer`
;; in some of their symbols so that you can use
;; them without the namespace prefix (which is the
;; text before the `/`, btw, in case that wasn't
;; obvious enough). Examine the `ns` form of this
;; file to see why these forms compile without
;; complaints:
(doc require) ; Check the output window
(string/split "foo:bar:baz" #":")
;; See also:
;; https://clojuredocs.org/clojure.core/ns
;; Keywords can also be namespaced, but they are
;; not really registered in a namespace, like
;; symbols are, so you can just use them, regardless
:foo-whatever
:whatever-namespace/foo
;; The notion about the current namespace exists
;; for keywords in that the double-colon prefix
;; expands to `:<current-namespace>/foo`:
::foo
;; This is important to know about. `:foo` will
;; refer to the same keyword regardless of from which
;; namespace it is used. `::foo` will not.
)
(comment
;; = COLLECTIONS =
;; Clojure has literal syntax for four collection types
;; They evaluate to themselves.
'(1 2 3) ; list (a quoted list, more about this below)
[1 2 3] ; vector
#{1 2 3} ; set
{:a 1 :b 2} ; map
;; They compose
{:foo [1 2]
:bar #{1 2}}
;; In Clojure we do most things with just these
;; collections. Literal collections and functions.
)
(comment
;; = FUNCTIONS =
;; So far you have been able to evaluate all examples.
;; It's because we quoted that list.
;; Actually lists look like so
(1 2 3)
;; But if you evaluate that, you'll get an error:
;; => class java.lang.Long cannot be cast to class
;; clojure.lang.IFn
;; (Of course, the linter already warned you.)
;; This is because the Clojure will try to call
;; `1` as a function. When evaluating unquoted lists
;; the first element in the list is regarded as being
;; in ”function position”. A Clojure program is data.
;; In fancier words, Clojure is homoiconic:
;; https://wiki.c2.com/?HomoiconicLanguages
;; This gives great macro power, more about that below.
;; Here are some lists with proper functions at
;; position 1:
(str 1 2 3 4 5 :foo)
(< 1 2 3 4 5)
(*)
(= "1"
(str "1")
(str \1))
(println "From Clojure with ♥️")
(reverse [5 4 3 2 1])
;; Everything after the first position is
;; handed to the function as arguments
;; Note: I'll be referring to literals, symbols, and
;; literal collections collectively as forms,
;; sometimes, sexprs:
;; https://en.wikipedia.org/wiki/S-expression
;; You define new functions and bind them to names
;; in the current namespace using the macro `defn`.
;; It's a very flexible macro. Here's a simple use:
(defn add2
[arg]
(+ arg 2))
;; It defines the function `add2` taking one argument.
;; The function body calls the core functions `+`
;; with the arguments `arg` and 2.
;; Evaluating the form will define it and you'll see:
;; => #'hello-clojure/add2
;; That's a var ”holding” the value of the function
;; You can now reference the var using the symbol
;; `add2`. Putting it in the function position of a
;; list with 3 in the first argument position and
;; evaluating the list gives us back what?
(add2 3)
;; Clojure has an extensive core library of functions
;; and macros. See: https://clojuredocs.org for a
;; community-driven Clojure core (and more) search engine.
)
(comment
;; = SPECIAL FORMS =
;; The core library is composed from the functions and macros
;; in the library itself. Bootstrapping the library is
;; a few (15-ish) built-in primitive forms,
;; aka ”special forms”.
;; You have met one of these special forms already:
(quote (1 2 3))
;; The doc hover of the symbol `quote` tells you that
;; it is a special form.
;; Wondering where you met this special form before?
;; I used the shorthand syntax for it then:
'(1 2 3)
;; Convince yourself they are the same with the `=` function:
(= (quote (1 2 3))
'(1 2 3))
;; Clojure has value semantics. Any data structures
;; that evaluate to the same data are equal,
;; no matter how deep or big the structures are.
(= [1 [1 #{1 {:a 1 :b '(:foo bar)}}]]
[1 [1 #{1 {:a (- 3 2) :b (quote (:foo bar))}}]])
;; ... but that was a detour, back to special forms.
;; Official docs:
;; https://clojure.org/reference/special_forms#_other_special_forms
;; A very important special form is `fn` (which is
;; actually four special forms, but anyway).
;; Without this form we can't define new functions.
;; The following form evaluates to a function which
;; adds 2 to its argument.
(fn [arg] (+ arg 2))
;; Calling the function with the argument 3:
((fn [arg] (+ arg 2)) 3)
;; Another special form is `def`. It defines things,
;; giving them namespaced names.
(def foo :foo)
;; ”Defining a thing” means that a var is created,
;; holding the value, and that a symbol is bound
;; to the var. Evaluating the symbol picks up the
;; value from the var it is bound to.
foo
;; The var can be accessed using the `var` special
;; form.
(var foo)
;; You will most often see the var-quote shorthand
#'foo
;; With these two special forms we can define functions
(def add2-2 (fn [arg] (+ arg 2)))
(add2-2 3)
;; This is what the macro `defn` does. You will most
;; often be defining functions like what we saw
;; earlier, (when discussing the function position of
;; a form):
(defn add2-3
[arg]
(+ arg 2))
;; We can use the function `macroexpand` to see that
;; what the macro produces:
(macroexpand '(defn add2-3
[arg]
(+ arg 2)))
;; Yet another super duper important special form:
(if 'test
'value-if-true
'value-if-false)
;; Rumour has it that all conditional constructs (macros)
;; are built using `if`. Try to imagine a programming
;; language without conditionals!
;; We'll return to `if` and conditionals.
;; == `let` ==
;; `let` is a special form that lets you bind values to
;; variables that will be used in the body of the form.
(let [x 1
y 2]
(str x y))
;; The bindings are provided as the first ”argument”,
;; in a vector. This is a pattern that is used by
;; other special forms and macros that let you define
;; bindings. It is similar to the lexical scope of other
;; programming languages (even if this rather is
;; structural). Sibling and parent forms do not
;; ”see” these bindings (they have no way they could
;; possibly reach it). Here's an example:
(do
(def x :namespace-x)
(println "`x` in `do` _before_ `let`: " x)
(let [x :let-x]
(println "`x` from `let`: " x))
(println "`x` in `do`, _after_ `let`: " x))
(println "`x` _outside_ `do`: " x)
;; As noted before in this guide, the `def` special
;; form defines things ”globally”, though namespaced.
;; If you have followed the instructions to examine
;; things mentioned here, for instance by
;; ctrl/cmd-clicking the `let` symbol in the code
;; snippets, you'll find that in `core.clj`, `let`
;; is defined as a macro. Never mind that. It is
;; actually referred to as a special form here
;; https://clojure.org/reference/special_forms#let
;; Let's (pun unintended) wrap the special forms section
;; up with noting that together with _how_ Clojure
;; reads and evaluates code, the special forms make up
;; the Clojure language itself. The next level och
;; building blocks are macros.
;; But let us investigate this thing with how code
;; is read first...
)
(comment
;; = THE READER =
;; https://clojure.org/reference/reader
;; The Clojure Reader is responsible for reading text,
;; making data from it, which is what the compiler gets.
;; The Reader is where literals, symbols, strings, lists,
;; vectors, maps, and sets are picked apart and
;; re-assembled, figuring out what is a function,
;; a macro or special form.
;; In doing this whitespace plays a key role and there
;; are also some extra syntax rules are in play.
;; == WHITESPACE ==
;; Most things you would think counts as whitespace
;; is whitespace, and then there is also that Clojure,
;; being a LISP, does not need commas to separate
;; list items. However, commas can be used for this
;; anyway, since commas are whitespace.
(= '(1 2 3)
'(1,2,3)
'(1, 2, 3)
'(1,,,,2,,,,3))
;; (There are no operators in Clojure, `=` is a
;; function. It will check for equality of all
;; arguments it is passed.)
;; == LINE COMMENTS ==
;; The Reader skips reading everything on a line from
;; a semicolon. This is unstructured comments in
;; that if you start a form
(range 1 ; 10)
;; and then place a line comment so that the closing
;; bracket of that form gets commented out, the
;; structure breaks.
)
;; ^ Healing the structure.
;; If you remove the semicolon on the opening form
;; above, make sure to also remove this closing paren.
;; Since everything on the line is ignored, you can
;; add as many semicolons as you want.
;;;;;;;;;; (skipped by the Reader)
;; It's common to use two semicolons to start a full
;; line comment.
;; == EXTRA SYNTAX ===
;; We've already seen the single quote
'something
;; Which is, as we have seen, transformed to
(quote something)
;; `quote` is needed to stop the Reader from treating
;; things as something that should be evaluated.
;; See what happens if you evaluate `something`
;; without the quoting:
something
;; as well as the difference between evaluating these:
(1 2 3 4)
'(1 2 3 4)
;; There are some more quoting, and even splicing
;; symbols, which I won't cover in this guide.
;; === Deref ===
;; Clojure also has reference types, we'll discuss
;; (briefly) the most common one, `atom`, later.
(def an-atom (atom [1 2 3]))
(type an-atom)
;; To access value from a reference:
(deref an-atom)
(type (deref an-atom))
;; Again, `deref` is used for dereferencing a lot
;; different reference types, including futures,
;; https://clojure.org/reference/refs
;; https://clojure.org/about/concurrent_programming
;; Anyway, `deref` is so common that there is
;; shorthand syntax for it
@an-atom
(= (deref an-atom)
@an-atom)
;; It's a common mistake to forget to deref
(first an-atom)
(first @an-atom)
;; === THE DISPATCHER (HASH SIGN) ===
;; That hash sign shows up now and then. It has a
;; special role. It is aka Dispatch. Depending on
;; what character is following it, different cool
;; things happen. Here follows some common ones:
;; Regular expressions have literal syntax, they are
;; written like strings, but with a hash sign in front
#"reg(?:ular )?exp(?:ression)?"
;; Regexps are handled by the host platform, so they
;; are Java regexps in this tutorial. If you
;; evaluated the above regexp, we can test it.
(re-seq *1 "regexp regular expression")
;; `*1` is a special symbol for a variable holding
;; the value of the last evaluation result. It might
;; be easier to get a regexp right by using it
;; directly:
(re-seq #"fooo*" "fo foo fooo")
(re-find #"fooo*" "fo foo fooo")
;; If the hash sign is followed by a `(`, the Reader
;; will start expecting a function body.
#(+ % 2)
;; This is special syntax for ”function literals”, a
;; way to specify a function. The example above is
;; equivalent to this anonymous function.
(fn [arg] (+ arg 2))
;; Nesting function literals is forbidden activity
;(#(+ % (#(- % 2) 3)))
;; (thankfully)
;; In addition to sets, regexps and function literals
;; we have seen var-quotes earlier in this guide
#'add2
;; There was also a brief discussion about `vars`.
;; You might want to revisit it and also read more
;; about it, because it is a very important concept.
;; https://clojure.org/reference/vars
;; There is a very useful hash-dispatcher which
;; is used to make the Reader ignore the next form
#_(println "The reader will not send this function call
to the compiler") "This is not ignored"
;; To test this select the ignore marker together with
;; the function call and the string, then use Ctrl+Enter,
;; to make Calva send it all to the Reader, which will
;; read it, ignore the function call, and only evaluate
;; the string.
;; Since #_ ignores the next form it is a structural
;; comment mechanism, often used to temporarily disable
;; some code or some data
(str "a" "b" #_(str 1 2 3 [4 5 6]) "c")
;; Ignore markers stack
(str "a" #_#_"b" (str 1 2 3 [4 5 6]) "c")
;; Note that the Reader _will_ read the ignored form.
;; If there are syntactic errors in there, the
;; Reader will get sad, complain, and stop reading.
;; Select from the marker up to and including the string
;; here and press Ctrl+Enter
;#_(#(+ % (#(- % 2) 3))) "foo"
;; Two more common #-variants you will see, and use,
;; are namespaced map keyword shorthand syntax and
;; tagged literals, aka, data readers. Let's start
;; with the former:
(= #:foo {:bar 'bar
:baz 'baz}
{:foo/bar 'bar
:foo/baz 'baz})
;; Unrelated to the #: There is another shorthand for
;; specifying namespaced keywords. Double colon
;; keywords get namespaced with the current namespace
::foo
(= ::foo :welcome-to-clojure/foo)
;; Tagged literals, then. It's a way to invoke functions
;; bound to the tags on the form following it.
;; https://clojure.org/reference/reader#tagged_literals
;; They are also referred to as data readers. You can
;; define your own. Here let it suffice with mentioning
;; the two build in ones.
;; #inst will convert the string it tags to an instance.
;; (I.e. an instance in time, not an instance in the
;; Object Orientation sense of the word.)
#inst "2018-03-28T10:48:00.000"
(type *1)
;; #uuid will make an UUID of the string it tags
#uuid "0000000-0000-0000-0000-000000000016"
(java.util.UUID/fromString "0000000-0000-0000-0000-000000000016")
;; You now know how to read (in the sense of you
;; being a Clojure Reader) most Clojure code.
;; That said, let's skip going into the syntax
;; sugar and special forms for making host platform
;; interop extra nice.
;; https://clojure.org/reference/java_interop
;; Just a sneak peek:
(.before #inst "2018-03-28T10:48:00.000"
#inst "2021-02-17T00:27:00.000")
;; This invokes the method `before` on the date
;; object for year 2018 giving it the date from
;; year 2021 as argument. You'll see some little
;; more Java interop in this guide and probably
;; notice how available the host platform is when
;; coding Clojure. The same goes for
;; ClojureScript and for Clojure CLR.
;; Repeating this important resource on the Reader:
;; https://clojure.org/reference/reader
;; And in addition to that, read about All Those
;; Weird Characters here:
;; https://clojure.org/guides/weird_characters
)
(comment
;; = MACROS =
;; Clojure has powerful data transformation
;; capabilities. We'll touch on that a bit later.
;; Here I want to highlight that this power can
;; be wielded for extending the language itself.
;; Since Clojure code is structured and code is
;; data, Clojure can be used to produce Clojure
;; code from Clojure code. It is similar to the
;; preprocessor facilitates that some languages
;; offer, like C's `#pragma`, but it is much more
;; convenient and powerful. A lot of what you
;; will learn to love and recognize as Clojure
;; is actually created with Clojure, as macros.
;; This guide is mostly concerned with letting you
;; know that macros are a thing, to help you to
;; quickly realize when you are using a macro rather
;; than a function. I.e. I will not go into the
;; subject of how to create macros.
;; The distinction is important, because even if
;; macro calls look a lot like function calls,
;; macros are not first class. They can't be
;; passed as arguments, or returned as results.
;; More about ”first class” in the section about
;; functions, later.
;; == `when` ==
;; Let's just briefly examine the macro`when`.
;; This macro helps with writing more readable code.
;; How? Let's say you want to conditionally evaluate
;; something. Above you learnt that there is
;; a special form named `if` that can be used for
;; this. Like so:
(if 'this-is-true
'evaluate-this
'else-evaluate-this)
;; Now say you don't have something to evaluate
;; in the else case. `if` allows you to write this
(if 'this-is-true
'evaluate-this)
;; Which is fine, but you will have to scan the
;; code a bit extra to see that there is no else
;; branch. Easy with this short example, but can
;; get pretty hairy in real code. To address this,
;; you could write:
(if 'this-is-true
'evaluate-this
nil)
;; But that is a bit silly, what if there was a
;; way to tell the human reading the code that
;; there is no else branch? There is!
(when 'this-is-true
'evaluate-this)
;; Let's look at how `when` is defined, you can
;; ctrl/cmd-click `when` to navigate to where
;; it is defined in Clojure `core.clj`.
;; You can also use the function `macroexpand`
(macroexpand '(when 'this-is-true
'evaluate-this))
;; You'll notice that `when` wraps the body in
;; a `(do ...)`, which is a special form that lets
;; you evaluate several expressions, returning the
;; results of the last one.
;; https://clojuredocs.org/clojure.core/do
;; `do` is handy when you want to have some side-
;; effect going, in addition to evaluating something.
;; In development this often happens when you
;; want to `println` something before the result
;; of the expression is evaluated and returned.
(do (println "The quick brown fox jumps over the lazy dog")
(+ 2 2))
;; The `when` macro let's you take advantage of that
;; there is only one branch, so you can do this
(when 'this-is-true
(println "The quick brown fox jumps over the lazy dog")
(+ 2 2))
;; Without `when` you would write:
(if 'this-is-true
(do
(println "The quick brown fox jumps over the lazy dog")
(+ 2 2)))
;; Here `when` saves us both the extra scanning for
;; the else-branch and the use of `do`.
;; As far as macros go, `when` is about as simple as
;; they get. From two built-in special forms,
;; `if` and `do`, it composes a form that helps us
;; write easy to write and easy to read code.
;; == `for` ==
;; The `for` macro really demonstrates how Clojure
;; can be extended using Clojure. You might think
;; it provides looping like the for loop in many
;; other languages, but in Clojure there are no for
;; loops. Instead `for` is about list comprehensions
;; (if you have Python experience, yes, that kind of
;; list comprehensions). Here's how to produce the
;; cartesian product of two vectors, `x` and `y`:
(for [x [1 2 3]
y [1 2 3 4]]
[x y])
;; If you recall the `let` form above, and how it
;; lets you bind variables to use in the body of the
;; form, this is similar, only that `x` and `y` will
;; get bound to each value in the sequences and the
;; body will get evaluated for all combinations of
;; `x` and `y`.
;; All values? Well, `for` also lets you filter the
;; results
(for [x [1 2 3]
y [1 2 3 4]
:when (not= x y)]
[x y])
;; You can bind variable names in the comprehension
;; to store intermediate calculations and generally
;; make code more readable
(for [x [1 2 3]
y [1 2 3 4]
:let [d' (- x y)
d (Math/abs d')]]
d)
;; Is the same as:
(for [x [1 2 3]
y [1 2 3 4]]
(Math/abs (- x y)))
;; Debatable what is more readable in this particular
;; case... ¯\_(ツ)_/¯
;; A note about the variable name `d'` above:
;; `d'` is just a symbol name like any other. The
;; single-quote has no special meaning unless it is
;; the first character
;; Filters and bindings can be used together.
;; Use both `:let` and `:when` to make this
;; comprehension return a list of all `[x y]` where
;; their sum is odd. The functions `+` and `odd?`
;; are your friends here.
(for [x [1 2 3]
y [1 2 3 4]]
[x y])
;; (Yes, it can be solved without `:let` or `:when`.
;; Humour me. 😎)
;; See https://www.youtube.com/watch?v=5lvV9ICwaMo for
;; a great primer on Clojure list comprehensions
;; See https://clojuredocs.org/clojure.core/for for
;; example usages and tips.
;; Note that even though `let` and `for` look like
;; functions, they are not. The compiler would not
;; like it if you are passing undefined symbols to a
;; function. This is legal code:
(let [abc 1]
2)
;; This isn't.
(str [abc 1]
1)
;; (Notice that the clj-kondo linter is marking the
;; first with a warning, and the second as an error)
;; Macros extend the Clojure compiler.
;; https://clojure.org/reference/macros
;; == Threading macros ==
;; Macros can totally rearrange your code. The
;; built-in ”threading” macros do this. Sometimes
;; when the nesting of function(-ish) calls get
;; deep it can get a bit hard to read and to keep
;; track of all the parens
(Math/abs
(apply -
(:d (zipmap
[:a :b :c :d]
(partition 2 [1 1 2 3 5 8 13 21])))))
;; You read Clojure from the innermost expression
;; and out, which gets easier with time, but an
;; experienced Clojure coder would still find it
;; easier to read this
(->> [1 1 2 3 5 8 13 21]
(partition 2)
(zipmap [:a :b :c :d])
:d
(apply -)
(Math/abs))
;; Let's read this together. The thread-last macro,
;; `->>` is used, it takes its first argument and
;; places it (threads it) as the last argument to
;; following function. The first such step in
;; isolation:
(->> [1 1 2 3 5 8 13 21]
(partition 2))
;; The first argument/element passed to `->>` is
;; `[1 1 2 3 5 8 13 21]`
;; This is inserted as the last element of the
;; function call `(partition 2)`, yielding:
(partition 2 [1 1 2 3 5 8 13 21])
;; This partitions the list into lists of
;; 2 elements => `((1 1) (2 3) (5 8) (13 21))`
;; This new list is then inserted (threaded)
;; as the last argument to the next function,
;; yielding:
(zipmap [:a :b :c :d] '((1 1) (2 3) (5 8) (13 21)))
;; Which ”zips” together a Clojure map using
;; the first list as keys and the second list
;; as values
;; => `{:a (1 1), :b (2 3), :c (5 8), :d (13 21)}`
;; This map is then threaded as the last argument
;; to the function `:d`
(:d '{:a (1 1), :b (2 3), :c (5 8), :d (13 21)})
;; (In clojure keywords are functions that look
;; themselves up in the map handed to them.)
;; => `(13 21)`
;; You know the drill by now, this is threaded
(apply - '(13 21))
;; Which applies the `-` function over the list
;; => `-8`
;; Then this is threaded to `Math/abs`
(Math/abs -8)
;; 🎉
;; (In many Clojure capable editors, including
;; Calva, there are commands for ”unwinding”
;; a thread, and for converting a nested
;; expressions into a thread. Search for ”thread”
;; among the commands.)
;; https://github.com/clojure-emacs/clj-refactor.el/wiki/cljr-unwind-all
;; There is also a thread-first macro
;; `->` https://clojuredocs.org/clojure.core/-%3E
;; Sometimes you neither want to thread first
;; of last. There is a macro for this too.
;; `as->` lets you bind a variable name to the
;; threaded thing and place it wherever you
;; fancy in each function call.
(as-> 15 foo
(range 1 foo 3)
(interpose ":" foo))
;; https://clojuredocs.org/clojure.core/as-%3E
;; It's common to utilize the fact that most characters
;; are available when naming Clojure symbols. I often
;; use `$` for this threading macro:
(as-> 15 $
(range 1 $ 3)
(interpose ":" $))
;; Others use other names 😄
(as-> 15 <>
(range 1 <> 3)
(interpose ":" <>))
;; I think emojis should be avoided, the official
;; docs only mention alphanumerics plus:
;; `*`, `+`, `!`, `-`, `_`, `'`, `?`, `<`, `>`, and `=`
;; (so not even `$`) but here goes:
(as-> 15 ❤️
(range 1 ❤️ 3)
(interpose ":" ❤️))
;; Other core threading macros are:
;; `cond->`, `cond->>`, `some->`, and `some->>`
;; https://clojuredocs.org/clojure.core/cond-%3E
;; Please feel encouraged to copy the examples
;; from ClojureDocs here and play with them.
;; Here's one:
(cond-> 1 ; we start with 1
true inc ; the condition is true so (inc 1) => 2
false (* 42) ; the condition is false so the operation is skipped
(= 2 2) (* 3)) ; (= 2 2) is true so (* 2 3) => 6
;; See ”Threading with Style” by Stuart Sierra
;; for idiomatic use of the threading facilities.
;; https://stuartsierra.com/2018/07/06/threading-with-style
)
;; With special forms, the special syntax of the Reader,
;; and macros, the foundations of what is the Clojure
;; language you use are laid. You can of course extend
;; the language further with libraries including macros
;; or create your own. However the core language, with
;; its macros is very expressive. Taking data oriented
;; approaches is often enough. Even to prefer, rather
;; than creating more macros.
;; On to flow control!
(comment
;; = Flow Control, Conditionals, Branching =
;; Clojure is richer than most languages in what it
;; offers us to let our programs flow the way we want
;; them to. Almost all the core library features for
;; this are implemented using the primitive (special
;; form) `if`. This is still the staple for us as
;; Clojure coders. It takes three forms as its
;; arguments:
;; 1. A condition to evaluate
;; 2. What to evaluate if the condition evaluates
;; to something true (truthy)
;; 3. The form to evaluate if the condition does not
;; evaluate to something truthy (the ”else” branch)
;; Roll this dice, some ten-twenty times, checking if
;; it is a six:
(if (= 6 (inc (rand-int 6)))
"One time out of six you get a six"
"Five times out of six you get something else")
;; Since there are no statements in Clojure `if` is
;; the equivalent to the ternary `if` expression you
;; find in C and many other languages:
;; test ? true-expression : false-expression
;; Pseudo code for our dice:
;; int(rand() * 6) + 1 == 6 ?
;; "One time out of six you get a six" :
;; "Five times out of six you get something else";
;; == The Search for Truth ==
;; Again, in Clojure we use expressions evaluating to
;; values. When examined for branching all values
;; are either truthy or falsy. In fact, almost all
;; values are truthy
(if true :truthy :falsy)
(if :foo :truthy :falsy)
(if '() :truthy :falsy)
(if 0 :truthy :falsy)
(if "" :truthy :falsy)
;; The only falsy values are `false` and `nil`
(if false :truthy :falsy)
(if nil :truthy :falsy)
(when false :truthy)
;; About that last one: `when` evaluates to `nil`
;; when the condition is falsy. Since `nil` is
;; falsy the above `when` expression would be
;; making the ”else” branch of an `if` to be
;; evaluated
(if (when false :truthy) :true :falsy)
;; (Super extra bad code, but anyway)
;; When only boolean truth or falsehood can cut
;; it for you, there is the `true?` function
(true? true)
(true? 0)
(true? '())
(true? nil)
(true? false)
;; Thus
(if (true? 0) :true :false)
;; == `when` ==
;; As mentioned before, `when` is a one-branch
;; `if`, only for the truthy branch, which is
;; wrapped in a `do` for you. Try this and then
;; try it replacing the `when` with an `if`:
(when :truthy
(println "That sounds true to me")
:truthy-for-you)
;; If the `when` condition is not truthy,
;; `nil` will be returned.
(when nil :true-enough?)
;; == `cond` ==
;; Since deeply nested if/else structures can be
;; hard to write, read, and maintain, Clojure core
;; offers several more constructs for flow control,
;; one very common such is the `cond` macro. It
;; takes pairs of condition/result forms, tests
;; each condition, if it is true, then the result
;; form is evaluated and ”returned”, short-circuiting
;; so that no more condition is tested.
(let [dice-roll (inc (rand-int 6))]
(cond
(= 6 dice-roll) "Six is as high as it gets"
(odd? dice-roll) (str "An odd roll " dice-roll " is")
:else (str "Not six, nor odd, instead: " dice-roll)))
;; The `:else` is just the keyword `:else` which
;; evaluates to itself and is truthy. It is the
;; conventional way to give your cond forms a
;; default value. Without a default clause, the
;; form would evaluate to `nil` for anything not-six
;; not-odd. Try it by placing two ignore markers
;; (`#_ #_`) in front of the `:else` keyword.
;; Gotta love ClojureDocs
;; https://clojuredocs.org/clojure.core/cond
;; Paste examples from there here and play around:
;; See also links to `cond->` info above
;; == `case` ==
;; A bit similar to `switch/case` constructs in
;; other languages, Clojure core has the `case`
;; macro which takes a test expression, followed by
;; zero or more clauses (pairs) of test constant/expr,
;; followed by an optional expr. (However, the body
;; after the test expression may not be empty.)
(let [test-str "foo bar"]
(case test-str
"foo bar" (str "That's very " :foo-bar)
"baz" :baz
(count test-str)))
;; The trailing expression, if any, is ”returned” as
;; the default value.
(let [test-str "foo bar"]
(case test-str
#_#_"foo bar" (str "That's very " :foo-bar)
"baz" :baz
(count test-str)))
;; If no clause matches and there is no default,
;; a run time error happens
(let [test-str "foo bar"]
(case test-str
#_#_"foo bar" (str "That's very " :foo-bar)
"baz" :baz
#_(count test-str)))
;; WATCH OUT! A test constant must be a compile
;; time literal, and the compiler won't help you
;; find bugs like this:
(let [test-int 2
two 2]
(case test-int
1 :one
two (str "That's not a literal 2")
(str test-int ": Probably not expected")))
;; https://clojuredocs.org/clojure.core/case
;; Paste some `case` examples here and experiment
;; The Functional Design in Clojure podcast has a
;; fantastic episode about branching
;; https://clojuredesign.club/episode/089-branching-out/
;; == Less branching is good, right? ==
;; The core library is rich with functions that
;; helps you avoid writing branching code. Instead
;; you provide the condition as a predicate.
;; An often used predicate function is `filter`
(filter even? [0 1 2 3 4 5 6 7 8 9 10 11 12])
;; and its ”sibling” `remove`
(remove odd? [0 1 2 3 4 5 6 7 8 9 10 11 12])
;; Filtering sequences of values is a common task
;; and your programming time can instead be used
;; to decide _how_ it should be filtered, by writing
;; the predicate. Sometimes you don't even need to
;; do that, Clojure core is rich with predicates
(zero? 0)
(even? 0)
(neg? 0)
(pos? 0)
(nat-int? 0)
(empty? "")
(empty? [])
(empty? (take 0 [1 2 3]))
(integer? -2/1)
(indexed? [1 2 3])
(indexed? '(1 2 3))
;; What's a predicate? For the purpose of this guide
;; A predicate is a function testing things for
;; truthiness. It is convention that these functions
;; end with `?`. Many take only one argument.
;; A handy predicate is `some?` which tests for
;; "somethingness”, if it is not `nil` it is
;; something
(some? nil)
(some? false)
(some? '())
;; You can use it to test for if something is `nil`
;; by wrapping it in a call to the `not` function
(not (some? nil))
(not (some? false))
;; You get the urge to define a function named `nil?`,
;; right? You don't have to
(nil? nil)
(nil? false)
;; Clojure core also contains predicates that take
;; a predicate plus a collection to apply it on.
;; Such as `every?`
(every? nat-int? [0 1 2])
(every? nat-int? [-1 0 1 2])
;; Check the docs for `nat-int? and come up
;; with some more lists to test, like
(every? nat-int? [0 1 2N]) ; 2N is not fixed precision
(doc nat-int?)
;; This pattern with functions that take functions
;; as argument is common in Clojure. It spans beyond
;; predicates. Functions that take functions as
;; arguments are referred to as ”higher order
;; functions”.
;; https://en.wikipedia.org/wiki/Higher-order_function
)
(comment
;; = Functions =
;; Before diving into higher order functions, let's
;; look at functions.Functions are first class
;; Clojure citizens and the main building blocks for
;; solving your business problems.
;; We have seen a few ways you can create functions.
;; Here's an anonymous function that returns the
;; integer given to it, unless it is divisible by
;; 15, in which case it returns "fizz buzz".
;; (Not the full Fizz Buzz problem by any means.)
(fn [n]
(if (zero? (mod n 15))
"fizz buzz"
n))
;; Let's define it (bind it to a symbol we can use)
(def fizz-buzz-1 (fn [n]
(if (zero? (mod n 15))
"fizz buzz"
n)))
(fizz-buzz-1 2)
(fizz-buzz-1 15)
;; There's a macro that lets us define and create
;; the function in one call
(defn fizz-buzz-2 [n]
(if (zero? (mod n 15))
"fizz buzz"
n))
(fizz-buzz-2 4)
;; `defn` lets us provide documentation for the
;; function
(defn fizz-buzz-3
"Says 'fizz buzz' if `n` is divisible by 15,
otherwise says `n`"
[n]
(if (zero? (mod n 15))
"fizz buzz"
n))
(doc fizz-buzz-3) ; (or hover `fizz-buzz-3`)
;; It is easy to place the doc string wrong,
;; especially since it is common to write the `defn`
;; form like we did with `fizz-buzz-2` above.
(defn fizz-buzz-4
[n]
"Says 'fizz buzz' if `n` is divisible by 15,
otherwise says `n`"
(if (zero? (mod n 15))
"fizz buzz"
n))
;; This specifies a fully valid function body, so
;; Clojure won't complain about it. But:
(doc fizz-buzz-4)
;; clj-kondo's default configuration will help you
;; spot these errors. However, it can't help with
;; this:
(defn only-the-last-eval-returns [x]
[1 x]
[2 x])
(only-the-last-eval-returns "foo")
;; It is easy enough to spot like this and also to
;; wonder why you would ever write a function that
;; way. Yet you probably will do this mistake,
;; especially if you ever write some Hiccup, which
;; is a super nice way of writing HTML with Clojure
;; data structures. It's used by the popular Reagent
;; library
;; https://purelyfunctional.tv/guide/reagent/#hiccup
;; When you do the mistake and finish your hour-long
;; bug hunt, you will hear this guide whisper
;; ”Called it!”
;; The argument binding vector of `fn` (and
;; therefore `defn`) binds each argument in order
;; to a name.
(defn coords->str [x y]
(str "x: " x ", y: " y))
;; == Variadic Functions ==
;; You can define functions that take an arbitrary
;; number of arguments by placing a `&` in front
;; of the last argument name. That binds the name
;; to a sequence that contains all the remaining
;; arguments.
(defn lead+members [lead & members]
{:lead lead
:members members})
(lead+members "Dave Mustain"
"Marty Friedman"
"Nick Menza"
"David Ellefson")
;; == Multi-arity ==
;; Clojure supports function signatures based on
;; the number of arguments. The `defn` macro lets
;; you define each arity as a separate list. This
;; is often used to provide default values
(defn hello
([] (hello "World"))
([s] (str "Hello " s "!")))
(hello)
(hello "Clojure Friend")
;; Or to create an ”identity” value for a function,
;; (A starting value that the rest of the operation
;; uses.) Say you want to add two x-y coordinates
(defn add-coords-1 [coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))})
(add-coords-1 {:x -2 :y 10}
{:x 4 :y 6})
;; What if the requirements were that if the
;; function is called with ne argument it should
;; add it to the origin? (See what I did there?
;; The identity value is where the function
;; should start, so start from the origin. 😎)
;; We can see that `add-coords-1` fails here
(add-coords-1 {:x -2 :y 10})
;; we need to add a one-arity
(defn add-coords-2
([coord]
(add-coords-2 {:x 0
:y 0}
coord))
([coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))}))
(add-coords-2 {:x -2 :y 10})
;; Now if called with no arguments it should
;; return the origin, because if you do not add
;; any coordinate you stay at the start.
;; Write a function `add-coords-3` that returns
;; the origin when called like this
(add-coords-3)
;; It should still handle to be called like this
(add-coords-3 {:x 3 :y 4})
(add-coords-3 {:x 2 :y 4}
{:x -4 :y -4})
;; It has to do with making the function compose
;; with other functions. E.g. the `apply` function
;; which is a higher order function that ”applies”
;; a function over a sequence. Right now we can
;; apply our `add-coords-2` function like this
(apply add-coords-2 [{:x 1 :y 1} {:x 4 :y 4}])
;; And like this
(apply add-coords-2 [{:x 1 :y 1}])
;; But not like this
(apply add-coords-2 [])
;; But the `add-coords-3` function you created can
(apply add-coords-3 [])
;; It will not handle an arbitrary long sequence
;; of coords, though. For that we would need one
;; more arity like so
(defn add-coords-4
;; add zero-arity from your `add-coords-3` here
;; add one-arity from your `add-coords-3` here
([coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))})
([coord-1 coord-2 & more-coords]
;; Implement this arity when you have learnt
;; about the higher order function `reduce`
))
(apply add-coords-4 [{:x 1 :y 1}
{:x 1 :y 1}
{:x 1 :y 1}
{:x -6 :y -6}])
;; Listen to Eric Normand explain in more detail
;; why the identity of a function is important:
;; https://lispcast.com/what-is-a-functions-identity/
;; == Closures ==
;; When you create functions on the fly, lambdas,
;; if you like, you use either the `fn` special
;; form directly, or by proxy with the `#()` syntax.
;; This creates a closure, like it does in JavaScript
;; and other languages. That is, these function can
;; access snapshots of variables with the values they
;; had when the function was created
(defn named-coords-factory [name]
(fn [x y] {:name name
:coords {:x x
:y y}}))
(def bob-coords-fn (named-coords-factory "Bob"))
(def fred-coords-fn (named-coords-factory "Fred"))
(bob-coords-fn 0 0)
(fred-coords-fn 5 5)
(bob-coords-fn 7 7)
;; Closures are handy to create low-arity functions
;; inside let binding boxes for the function body
;; to use:
(defn whisper-or-yell-or-ask [command sentence]
(let [whisper (fn []
(str (string/lower-case sentence) command))
yell (fn []
(str (string/upper-case sentence) command))
ask (fn []
(str sentence "?"))
default (fn []
(str sentence command " ¯\\_(ツ)_/¯"))]
(case command
"" (whisper)
"!" (yell)
"?" (ask)
(default))))
;; All functions created in the let binding box
;; ”close in” the `command` and the `sentence` so
;; the `case` can be kept terse and readable.
(whisper-or-yell-or-ask "" "How wOnDerFuLLY NIce To seE")
(whisper-or-yell-or-ask "!" "Hello tHERE")
(whisper-or-yell-or-ask "?" "How are you doing")
(whisper-or-yell-or-ask ":" "Oh well")
;; == The Attributes Map ==
;; The `defn` macro lets you add attributes to the
;; function in the form of a map. This gets added
;; as meta-data (some little more on that later)
;; to the var holding the function. The map goes
;; after the function name, and after any docs,
;; and before the arguments vector (or any arities)
(defn i-have-attributes
{:doc "Docs can be added like this too"
:foo "Any attributes you fancy"}
[]
"Good for you")
(doc i-have-attributes)
(meta #'i-have-attributes)
;; One handy attribute you can add is a test
;; function. Test runners will pick this up
(defn fizz-buzz-5
"That limited fizz-buzz function again"
{:test (fn []
(is (= "fizz-buzz" (fizz-buzz-5 15)))
(is (= 3 (fizz-buzz-5 3))))}
[n]
(if (pos? (rem 15 n))
"fizz-buzz"
n))
(clojure.test/test-var #'fizz-buzz-5)
;; Oops! You'll need to fix the bugs. 😀
;; How about implementing the complete Fizz Buzz?
;; https://en.wikipedia.org/wiki/Fizz_buzz
(defn fizz-buzz
"My Fizz Buzz solution"
{:test (fn []
(are [arg expected]
(= expected (fizz-buzz arg))
1 1
3 "Fizz"
4 4
5 "Buzz"
7 7
15 "Fizz Buzz"
20 "Buzz"))}
[n])
(clojure.test/test-var #'fizz-buzz)
(map fizz-buzz (range 1 40))
;; The meta-data that has special meaning to
;; the compiler and various Clojure core
;; facilities is listed here:
;; https://clojure.org/reference/special_forms
;; Now, on to higher order functions!
)
(comment
;; = Higher order functions =
;; A big contribution to what makes Clojure such a
;; powerful language is that functions are
;; ”first-class”
;; https://en.wikipedia.org/wiki/First-class_function
;; They can be values in collections (also keys
;; in maps) and can be passed as arguments to other
;; functions, and ”returned ”as results from
;; evaluations. You might be familiar with the
;; concept from languages like JavaScript.
;; Let's look at some higher order functions in
;; Clojure core. `some` calls the function on the
;; elements of its collection, one-by-one, and
;; returns the first truthy result, and will return
;; `nil` if the list is exhausted before some element
;; results in something truthy.
(some even? [1 1 2 3 5 8 13 21])
;; Not to be confused with `some?`, which is not
;; a higher order function.
(some some? [nil false])
(some some? [nil nil])
;; A common idiom in Clojure is to look for things
;; in collection using a `set` as the predicate.
;; Yes, sets are functions. Used as functions they
;; will look up the argument given to them in
;; themselves.
(#{"foo" "bar"} "bar")
;; Thus
(some #{"foo"} ["foo" "bar" "baz"])
(some #{"fubar"} ["foo" "bar" "baz"])
;; `apply` takes a function and a collection and
;; ”applies” the function on the collection. Say you
;; have a collection of numbers and want to add them.
;; This won't work:
(+ [1 1 2 3 5 8 13 21])
;; `apply` to the rescue
(apply + [1 1 2 3 5 8 13 21])
;; Concatenate the numbers as a string:
(apply str [1 1 2 3 5 8 13 21])
;; Contrast with
(str [1 1 2 3 5 8 13 21])
;; We've also seen `filter` and `remove` above, two
;; very commonly used higher order functions. They
;; play in the same league as `map`, and `reduce`.
;; Read on. 😎
)
(comment
;; = `map` and `reduce` =
;; Among the higher order functions you might have
;; used in other languages with first class
;; functions are `map` and `reduce`. They are worth
;; studying and practicing in much detail, here's
;; a super nice teaser:
;; https://purelyfunctional.tv/courses/3-functional-tools/
;; Let's also check them out briefly here.
;; `map` calls a function on the elements of one or
;; more collection from start to end and returns a
;; (lazy, more on that later) sequence of the results
;; in the same order. Let's say we want to decrement
;; each element in a list of numbers by one
(map dec '(1 1 2 3 5 8 13 21))
;; Let's say we then want to dec them again
(->> '(1 1 2 3 5 8 13 21)
(map dec)
(map dec))
;; Hmmm, better to subtract by two, maybe?
(map (fn [n] (- n 2)) '(1 1 2 3 5 8 13 21))
;; If you give `map` more collections to work on
;; it will repeatedly:
;; 1. pick the next item from each collection
;; 2. give them to the mapping function as arguments
;; 3. add the result to its return sequence
;; Until the shortest collection is exhausted
(map + [1 2 3] '(0 2 4 6 8))
(map (fn [n1 s n2] (str n1 ": " s "-" n2))
(range)
["foo" "bar" "baz"]
(range 2 -1 -1))
;; (We haven't talked much about `range`, it is a
;; function producing sequences of numbers. Given no
;; arguments it produces an infinite, watch out 😀,
;; sequence of integers
;; 0, 0+1, 0+2, 0+3, 0+4, 0+5, 0.6 ...
;; Good thing the other sequences got exhausted!)
;; A lot of the tasks you might solve with `for`
;; loops in other languages, are solved with `map`
;; in Clojure.
;; With other such ”for loopy” tasks you will
;; be wielding `reduce`. Unlike `map` it is not
;; limited to producing results of the same length
;; or shape as the input collection. Instead it
;; accumulates a result of any shape. For instance,
;; it can create a string from a collection of
;; numbers
(reduce (fn [acc n]
(str acc ":" n))
[1 1 2 3 5 8 13 21])
;; `reduce` will call the function with two
;; arguments: the result of the last function
;; call and the next number from the list. The
;; start of the process is special, since then
;; there are no results yet. `reduce` has two
;; ways to deal with this, two arities to be
;; specific. Called with two arguments, it
;; uses the two first elements from the list
;; for the first function call.
;; Here's reducing the `+` function using the
;; two-arity version of `reduce`
(reduce + [1 1 2 3 5 8 13 21])
;; The process then starts with calling `+`
;; like so
(+ 1 1)
;; Giving `reduce` three arguments makes it us
;; the second argument as the starting ”result”.
(reduce + 100 [1 1 2 3 5 8 13 21])
;; You might have noticed that the `+` function
;; takes more (and less) than 2 arguments.
(+)
(+ 1)
(+ 1 1)
(+ 1 1 2 3 5 8 13 21)
;; `+` will take the first argument, if any, and
;; add it to ”the current” value (which is zero),
;; then the next argument and add that to the new
;; current value, and so on, and so forth, until
;; there is a result. This process sounds a bit
;; like I just described a reduce, right?
;; In fact it is.
;; If we were to implement the `+` function, how
;; could we do it? We could start by implementing
;; something that adds two numbers together, then
;; use it as as the reducing function with
;; `reduce`.
;; Of course, now we have the task of adding two
;; numbers together, without using the existing
;; `+` function... 🤔
;; Hmmm... Let's keep it simple and only do
;; integer math. Then we can use the Java's
;; `Integer.sum(x, y)` method.
(Integer/sum 1 1)
;; Awesome, with this we can create an `add-two`
;; function
(defn add-two [x y]
(Integer/sum x y))
(add-two 1 1)
;; Unlike `+`, this one is not fully composable
;; with a higher order function like apply
(apply add-two [])
(apply add-two [1])
(apply add-two [1 1])
(apply add-two [1 1 2 3 5 8 13 21])
;; We need `add-many`. With `reduce` and our
;; `add-two` we can define `add-many` like so
(defn add-many [& numbers]
(reduce add-two numbers))
;; That does it, right?
(apply add-many [1])
(apply add-many [1 1])
(apply add-many [1 1 2 3 5 8 13 21])
;; What about the zero-arity version of `+`, you
;; ask? Correct, that will blow up
(add-many)
;; The built-in `+` function has a default ”current”
;; value of zero, remember? We can add that to
;; `add-many` in two ways: Either add a zero-arity
;; signature, or use the three-arity `reduce`. Let's
;; go for the latter option, since we are learning
;; about reduce here:
(defn add* [& numbers]
(reduce add-two 0 numbers))
(add*)
(add* 1)
(add* 1 1)
(add* 1 1 2 3)
;; BOOM.
;; We can use it with `apply` as well:
(apply add* [])
(apply add* [1])
(apply add* [1 1])
(apply add* [1 1 2 3 5 8 13 21])
;; Or `reduce`:
(reduce add* [])
(reduce add* [1])
(reduce add* [1 1])
(reduce add* [1 1 2 3 5 8 13 21])
;; Apart from that we only handle integers, our `add*`
;; is very much like how `+` is implemented in
;; Clojure core. Check it out (in the output window):
(source +)
;; Hmmm, well, they seem to be using multi-arity
;; function signatures for the low-arity cases, probably
;; because of the casting, but anyway, 😀
;; There's one more thing with `reduce` we want to
;; mention. When writing reducing functions you can
;; stop the process before the input sequence is
;; exhausted, using the `reduced` function. Say we
;; want the input sequence as a string separated by
;; `:`, as above, but stop when we see a `nil` item.
;; Here's the last version for comparison:
(reduce (fn [acc n]
(str acc ":" n))
[1 1 2 3 5 8 nil 13 21])
;; We can short circuit the process by calling
;; `reduced` with the accumulated value when we
;; encounter a `nil` item
(reduce (fn [acc n]
(if (nil? n)
(reduced acc)
(str acc ":" n)))
[1 1 2 3 5 8 nil 13 21])
;; Here is what is going on
(doc reduced)
;; Reducing is a mighty important concept in Clojure
;; since it is a ”functional first” language. Or as
;; it is worded in this Functional Design episode
;; https://clojuredesign.club/episode/058-reducing-it-down/
;; ”Reducing functions are a backbone of functional
;; programming, because we don’t have mutation.”
;; In fact in Clojure reducing is so important that
;; Rich Hickey has added a whole library with reducers
;; packing even more punch
;; https://clojure.org/reference/reducers
;; Again, the Functional Design duo, Nate Jones, and
;; Christoph Neumann have examined this library
;; a bit:
;; https://clojuredesign.club/episode/060-reduce-done-quick/
;; Amazing quote from that episode:
;; “The seq abstraction, it’s rather lazy.”
;; We are not going down the rabbit hole of the
;; `reducers` library, though...
)
;; ... Instead we are picking up that Nate and
;; Christoph mention three super important concepts
;; in those two above quotes.
;; * immutability
;; * the `seq` abstraction
;; * laziness
;; They are related, and maybe it is best to start with
;; immutability...
(comment
;; = Immutability =
;; It is rather crazy that we have been talking about
;; Clojure for this long without discussing how
;; it encourages us to avoid mutating our data as
;; it is being processed. Clojurians never shut up
;; about immutability, right? We can almost sound
;; like Rothbardians in defining ourselves as
;; Enemies of the State 😄
;; https://www.youtube.com/watch?v=qe60zwUAOqE
;; This is to some extent true, as Clojurians we
;; often try to stay in a data transformation mode
;; for the duration of an operation and only deal
;; with the impure world, at the ”boundaries”. at
;; the start we might be reading some input, and
;; at the end we might be updating a database,
;; printing the results to a file (or to the
;; screen), or mutating the DOM of a web page.
;; Clojure encourages us to walk the immutable
;; path in many ways, two of which I am going
;; to mention a bit here:
;; * Persistent Data Structures
;; * Pure Functions
;; == Persistent Data Structures ==
;; Clojure helps us to stay in immutable land by
;; providing us with immutable data structures.
;; The implementation of these is called Persistent
;; Data Structure:
;; https://en.wikipedia.org/wiki/Persistent_data_structure
;; In effect it means that the data structures are
;; never changed, The functions we use to transform
;; them actually create copies. (In a very smart
;; way, so don't you start worrying now.)
;; Say we define a a vector of some digits
(def eighteen [1 0 0 1 0])
eighteen
;; Now we want to change that last `0` to a `1`
;; We can use the `assoc` function. When used on
;; a vector, takes an index and the new value
(def nineteen (assoc eighteen 4 1))
nineteen
;; Examining `eighteen` again ...
eighteen
;; ... we see that it is still true to its name.
;; Associng a `1` at index 4 of it created a
;; copy, which was then defined as `nineteen`
;; Perhaps obvious, this stands true in local
;; bindings as well.
(let [origin {:x 0
:y 0}
x-travel (assoc origin :x 100)]
[origin x-travel])
;; This provides for a very deterministic program
;; flow. Data does not willy-nilly change under our
;; feet. And, transformation processes that do not
;; mutate state are much easier to parallelize,
;; other threads can't change the data you are
;; transforming. A whole category of bugs never get
;; the chance to hatch!
;; Another benefit we get from immutability is
;; that Clojure can efficiently offer us value
;; equality. Values are immutable, by definition.
;; In Clojure, even the deepest data structures can
;; be compared in less than a jiffy.
;; Let's show this with a not so deep structure
;; (except in the name)
(def universa {:one {"Alice" {:x 100
:y 100
:z 100}
"Bob" {:x 100
:y 100
:z 100}}
:two {"Alice" {:x 100
:y 100
:z 100}
"Bob" {:x 100
:y 100
:z 99}}})
(= (:one universa)
(:two universa))
;; `update-in` is a higher order function for
;; transforming data structures given an
;; ”address” and a function. We can use it
;; to make two-Bob find two-Alice, just like
;; one-Bob and one-Alice have found each other
(def unified-universa
(update-in universa [:two "Bob" :z] inc))
unified-universa
(= (:one unified-universa)
(:two unified-universa))
(= universa unified-universa)
;; You'll never have to write an `equals()`
;; method again! 😄
;; Immutability also makes our programs different
;; than they are when you can change the value of
;; a variable at will. It can take a while to get
;; used to this. (I am still at the point where I
;; have an easier time to see mutating solutions
;; to many problems. It is less and less so, but
;; anyway. Probably you will grok it quicker than
;; I am doing.)
;; It is totally worth it to insist on getting it.
;; The payoff is huge. If you are only going to
;; check out one of the resources I am recommending
;; in this guide, I suggest it be this one about
;; solving problems the Clojure way, by Rafal
;; Dittwald:
;; https://www.youtube.com/watch?v=vK1DazRK_a0
;; Spoiler: He is not using Clojure in the video
;; Of course, in the talk, Rafal is not only
;; pretending data is immutable. He is also
;; employing function purity.
;; == Pure functions
;; Clojure doesn't force purity on you, like
;; some languages do (looking at you Haskell), but
;; it makes it easy to fall into the habit of
;; writing pure functions and thus push side effects
;; towards the ”edges” of your program.
;; A function is considered pure if it abides to
;; these rules:
;; 1. Always return the same value for the same input
;; 2. Does not effect anything in its environment.
;; So, not mutating anything, including not printing
;; anything anywhere, or hitting mutating API
;; endpoints.
;; A pure function is deterministic and you can
;; safely call it without worrying that it will update
;; application state or do anything else than
;; compute its return value based on the input you
;; hand it, and nothing but the input you hand it.
)
;; Before examining the `seq` abstraction, let's divert
;; a bit into some common Clojure core functions for
;; transforming data structures.
(comment
;; = Transforming Data Structures =
;; Clojure has a core library that makes it easy,
;; fun, and readable to ”reach in” to a data
;; data structure and manipulate it, creating a
;; copy with holding the result.
;; We have seen `assoc`, which creates a copy of
;; the data structure with a new value at the index
;; (in case of a `vector`) or key (in case of a map)
(def colt-express
{:name "Colt Express"
:categories ["Family"
"Strategy"]
:play-time 40
:ratings {:pez 5
:kat 5
:wiv 5
:vig 3
:rex 5
:lun 4}})
(def exit-haunted
{:name "EXIT: The Haunted Roller Coaster"
:categories ["Family"
"Co-op"
"Puzzle"
"Cards"]
:ratings {:pez 5
:kat 5
:wiv 5
:vig 4
:rex 5}})
;; `assoc` can add a new key to a map
(def colt-express-w-age
(assoc colt-express :age-from 10))
;; With a vector you can only add a new item right
;; behind the last item, not beyond
(def board-games-empty
[])
(def board-games-w-c-e
(assoc board-games-empty 0 colt-express))
;; board-games-empty is still empty. Thus
(def board-games-w-c-e-and-exit-fail
(assoc board-games-empty 1 exit-haunted))
(def board-games-w-c-e-and-exit
(assoc board-games-w-c-e 1 exit-haunted))
;; Not that it is very common to add things
;; to a vector using `assoc`. For this `conj`
;; often makes more sense
(conj board-games-empty colt-express exit-haunted)
;; `assoc` on maps can replace existing values
;; (in the copy)
(def colt-express-w-age-and-adjusted-playtime
(assoc colt-express-w-age :play-time 45))
;; `assoc` on vectors can do this too
(def board-games-w-adjusted-c-e
(assoc board-games-w-c-e
0
colt-express-w-age-and-adjusted-playtime))
;; You can `assoc` multiple things in one call
(assoc colt-express
:play-time 50
:age-from 10)
(assoc board-games-empty
0 colt-express
1 exit-haunted)
;; (Again, there is `conj` for this.)
;; With maps there is also `merge`, letting you
;; merge two or more maps together
(merge colt-express
{:play-time 45
:age-from 10})
;; NB: it is a ”shallow” merge, so adding a family
;; member rating like this won't work.
(merge exit-haunted
{:play-time 90
:ratings {:lun 5}
:age-from 10})
;; `assoc` does the same
(assoc exit-haunted :ratings {:lun 5})
;; There is no deep-merge in Clojure core, but
;; there is `assoc-in` for reaching in deeper
;; Instead of an key (or index) it takes a ”path”
(assoc-in exit-haunted [:ratings :lun] 5)
(assoc-in colt-express [:categories 2] "Planning")
;; (But... don't, see below under `update` for
;; how to `conj` the category instead.)
;; Unlike with `assoc`, you can only add one thing
;; at a time with `assoc-in`
;; Removing things from a map is done with
;; `dissoc`
(dissoc colt-express :play-time :ratings :categories)
;; You will probably use `dissoc` often with
;; the REPL (like you do in this file) to
;; examine some data structures that might
;; have some large data structures in them,
;; like a log or something
(dissoc colt-express :log)
;; (This data structure didn't have any log,
;; so it was left unchanged, but anyway.)
;; There is no `dissoc-in` in Clojure core, but
;; let's return to that after we have visited
;; `update` and `update-in`.
;; `update` and `update-in` are similar to
;; their `assoc` counterparts, but instead of a
;; value, they take a function which is used to
;; manipulate the value.
(update exit-haunted :name string/upper-case)
;; An exercise for you: Update the `:play-time`
;; of the `colt-express` entry with 5 or so
;; Arguments that you add after the function
;; get passed to the function
(update colt-express :categories conj "Planning")
;; Exercise: Make your update of the :play-time
;; take the `5` (or so) as an argument.
;; Exercise: Remove the `:pez` and `:wiv` entries
;; from the `:ratings` of `exit-haunted`
;; `update-in` is to `assoc-in` what `update` is
;; to `assoc`.
(update-in colt-express [:ratings :lun] inc)
(update-in colt-express [:ratings :lun] + 9000)
;; https://www.youtube.com/watch?v=PCHxU7witPA
;; Exercise: There is no `dissoc-in`, but it does
;; look like you can use `update-in` for this,
;; in'it?
;; The reward is one less visit to StackOverflow
;; for you when lacking `dissoc-in` 😄
;; https://stackoverflow.com/a/21942548/44639
;; We have been using keywords as map lookup
;; functions earlier. That's fine, but you might
;; sometimes prefer the `get` function
(get colt-express :ratings)
(= (:ratings colt-express)
(get colt-express :ratings))
;; `get` takes a third argument that will be used
;; as the default, should the entry be missing
(get exit-haunted :play-time 0)
;; keywords as lookup functions also supports
;; this
(:play-time exit-haunted 0)
;; Without the default, `nil` will be returned.
;; Which might blow up, depending on what you
;; use the value for
(* (get colt-express :play-time) 2)
(* (get exit-haunted :play-time) 2)
;; Better safe than sorry, in cases like this
(* (get colt-express :play-time 0) 2)
(* (get exit-haunted :play-time 0) 2)
;; Yes, there is `get-in` as well
;; Exercise: Use `get-in` to grab my rating
;; on these two wonderful family games
;; You might have noticed that all the
;; functions in this section take the collection
;; as their first argument. That makes them
;; easy to use with the Thread First, `->`,
;; macro. This is by design and highly idiomatic
;; Clojure.
;; It is common to see data transformation pipe-
;; lines like this
(-> exit-haunted
(assoc :play-time 90)
(update :categories conj "Scary")
(assoc-in [:ratings :lun] 5)
(update-in [:ratings :vig] + 1)
(dissoc :name)
(update :log vec)
(update :log conj "Name redacted")
(update :log conj "(Because scary)"))
;; (Although, perhaps more meaningful than that)
;; I can recommend ”See also”-browsing ClojureDocs
;; some starting here:
;; https://clojuredocs.org/clojure.core/update-in
;; And pasting a lot of examples here to
;; experiment with.
)
(comment
;; == Manipulating `sets` ==
;; Maps, vectors and sets are the bread and
;; butter for most Clojure programs. With the
;; amazing literal syntax for these the code gets
;; gets easy to read and reason about. And
;; manipulating them is easy and intuitive.
;; `sets` are `seqs` (more on that later)
)
;; To be continued...
;; Until there's more material to read here, maybe
;; it's time you check how to connect Calva to
;; your Clojure/ClojureScript projects:
;; https://calva.io/connect/
;; Things on the to-write-about list:
;; meta-data
;; comments
;; destructuring
;; atoms
;; nil, nil safety, nil punning
;; seqs
;; laziness
;; loop, recur
;; debugging
;; some wrapping up exercises here and there
;; Learn much more Clojure at https://clojure.org/
;; There is also ClojureScript, the same wonderful language,
;; for JavaScript VMs: https://clojurescript.org
;; There is so much about Clojure not mentioned in this
;; short guide. https://clojure.org/ is where you
;; go for the complete story.
;; To get help with your Clojure questions, check these
;; resources out:
;; https://ask.clojure.org/
;; https://clojurians.net
;; https://clojureverse.org
;; https://www.reddit.com/r/Clojure/
;; https://exercism.io/tracks/clojure
;; And there are also many other resources, such as:
;; https://clojuredocs.org
;; https://clojure.org/api/cheatsheet
"File loaded. Welcome to Clojure! ♥️"
;; This guide is downloaded from:
;; https://github.com/BetterThanTomorrow/dram
;; Please consider contributing.
|
53605
|
(ns welcome-to-clojure
(:require [clojure.repl :refer [source apropos dir pst doc find-doc]]
[clojure.string :as string]
[clojure.test :refer [is are]]))
;; Welcome to Clojure! ♥️
;; Start with loading this file.
;; Ctrl+Alt+C Enter
;; Then evaluate this expression with Alt+Enter:
"Hello World"
;; That's a concise Hello World for any language.
;; And note that there are no parens. 😀
;; This guide will try to give you a basic
;; understanding of the Clojure language. Basic in
;; the sense that it is not extensive. Basic in the
;; sense that it is foundational, building from first
;; principles in order to make the Clojure journey
;; you have ahead easier to comprehend.
;; With the foundations in place you'll have a good
;; chance of having the right gut feeling for how to
;; code something, how to formulate your questions,
;; how to search effectively for information, how to make
;; sense of code you stumble across, and so on.
;; There will be links here and there, ctrl/cmd-click
;; those to open them in a browser. Here's the first
;; such link;
;; https://clojure.org/guides/learn/syntax
;; There you can read more about the concepts
;; mentioned in this guide.
;; The way to use the guide is to read about the
;; concepts and evaluate the examples. Sometimes there
;; will be exercises in the text. Don't limit your
;; exercising to those, though. Please feel encouraged
;; to edit the examples, and add new code
;; and evaluate that. Evaluate this to warm up:
(comment
(str "Welcome"
" to "
"Clojure!"
" "
"♥️"))
;; Then see what happens if you throw in some numbers
;; here and there and evaluate again.
;; NB: This is work in progress...
;; When you fire up the Getting Started REPL the next
;; time, you will be presented with the option to
;; download new files or continue with the files you
;; have. You can also always find the latest version here:
;; https://github.com/BetterThanTomorrow/dram/blob/dev/drams/welcome_to_clojure.clj
(comment
;; = EXPRESSIONS =
;; In Clojure everything is an expression.
;; (There are no statements.) Unless there is
;; an error when evaluating an expression, there
;; is always a return value (which is sometimes `nil`).
;; An important aspect of this is that the result
;; of an expression is always the last form/expression
;; evaluated. E.g. if you have a function defined
;; like so:
(defn last-eval-wins []
(println 'side-effect-1)
1
(println 'side-effect-2)
2)
;; This defines a function named
;; `last-eval-wins`, taking no arguments, with four
;; expressions in its function body. (We'll return to
;; defining functions later.)
;; Calling the function
(last-eval-wins) ; <- Evaluate that 😄
;; will cause all four expressions in the function
;; body to be evaluated. The result of the call will
;; be the last expression that was evaluated.
;; In the output window you will also see the
;; `println` calls happening. They are also
;; expressions, evaluating to `nil`.
(println 'prints-this-evaluates-to-nil)
;; Expressions are composed from literals (evaluating
;; to themselves) and/or calls to either:
;; * special forms
;; * macros
;; * functions
;; ”Hello World” at the beginning of this guide is a
;; literal string (thus, it evaluates to itself).
;; More about literals in the next section.
;; Calls are written as lists with the called thing
;; as the first element.
(def foo "foo") ; Calls the special form `def`,
; evaluates to the var it creates
; (More on this later)
(for [x '(1 2 3) ; Calls the macro `for`
y '(:a :b)] ; (List comprehension)
[x y])
(str 1 2 3) ; Calls the function `str` with the
; arguments 1, 2, and 3.
)
(comment
;; = LITERALS =
;; Literals evaluate to themselves.
;; (Remember your friends:
;; Alt+Enter and Ctrl+Enter)
;; Numeric types
18 ; integer
-1.8 ; floating point
0.18e2 ; exponent
18.0M ; big decimal
18/324 ; ratio
18N ; big integer
0x12 ; hex
022 ; octal
2r10010 ; base 2
;; Character types
"hello" ; string
\e ; character
#"[0-9]+" ; regular expression
;; Symbols and idents
map ; symbol
+ ; symbol - most punctuation allowed
clojure.core/+ ; namespaced symbol
nil ; null/nil value (named in the LISP tradition)
true false ; booleans
:alpha ; keyword
:release/alpha ; namespaced keyword
::alpha ; namespaced keyword,
; in current namespace
;; == KEYWORDS ==
;; Keywords are start with a `:`. They are a thing
;; in themselves, often used as identifiers and as
;; keys in maps (more on maps later). Keywords are
;; very memory and speed efficient.
;; The same keyword is of course equal to itself
(= :foo :foo)
;; It is, however, also identical to itself
(identical? :foo :foo)
;; This means it is the same thing, occupying the
;; same (very tiny) place in memory.
;; Even if you construct a non-literal keyword
;; it remains identical to it's literal form
(identical? (keyword "foo") :foo)
;; This holds true for your whole Clojure program.
;; Keywords are global. There is namespace syntax
;; for them, so that you can have control of this.
;; Keywords are also functions, actually. But more
;; on that later. For now let it suffice to say
;; that keywords have a very special and important
;; role in most Clojure programs.
;; == STRINGS ==
;; Somewhere in between the atomic literals and
;; the collections we have strings. They are sometimes
;; treated as sequences (a cool abstraction I'll
;; talk more about).
;; Strings are enclosed by double quotes.
"A string can be
multi-line, but will contain any leading spaces."
"Write strings
like this, if leading spaces are no-no."
;; (The single quote is used for something else.
;; You'll see for what a bit later.)
)
(comment
;; = NAMESPACES =
;; Important as namespaces are, we won't dwell on
;; the subject very much in this guide. The official
;; docs make them the best justice:
;; https://clojure.org/reference/namespaces
;;
;; There are some things we really need to know
;; though...
;; Clojure symbols are defined in namespaces (With
;; the `def `special form) where they are reachable
;; from any other namespace.
(def foo-2 "foo")
;; Also know that there is such a thing as the
;; current namespace. (A bit like the current working
;; directory in the shell.) When you evaluated the
;; `def` form above, you'll saw where `foo-2` got
;; defined.
;; When evaluating a symbol from any namespace it
;; must have been defined, or the compiler will
;; complain, and throw
foo-3
;; The namespace also needs to have been created
some-namespace/foo
;; If you have loaded the `hello_repl.clj` file
;; the `hello-repl` namespace is created and its
;; top level symbols are defined (not the ones
;; hidden in `(comment ...)` forms, because the
;; `comment` macro ignores the body and just
;; evaluates to/returns `nil`)
hello-repl/greet
(hello-repl/greet "from the welcome-to-clojure namespace")
;; If those throw, you need to first load
;; `hello_repl.clj`, or at least evaluate its `ns`
;; form and the `greet` form.
;; It is not to recommend that you rely on some
;; namespace existing like this though. That makes
;; your code brittle. It is better to `require`
;; the namespace. If you haven't loaded it, you
;; can do that in the same go:
(require 'hello-paredit :reload)
hello-paredit/strict-greet
(hello-paredit/strict-greet "World")
;; For most Clojure code you write you will arrange
;; it into separate files with one namespace each,
;; and use the `ns` form (that starts most Clojure
;; files) to `:require` the needed namespaces, aliasing
;; them to something convenient and sometimes `:refer`
;; in some of their symbols so that you can use
;; them without the namespace prefix (which is the
;; text before the `/`, btw, in case that wasn't
;; obvious enough). Examine the `ns` form of this
;; file to see why these forms compile without
;; complaints:
(doc require) ; Check the output window
(string/split "foo:bar:baz" #":")
;; See also:
;; https://clojuredocs.org/clojure.core/ns
;; Keywords can also be namespaced, but they are
;; not really registered in a namespace, like
;; symbols are, so you can just use them, regardless
:foo-whatever
:whatever-namespace/foo
;; The notion about the current namespace exists
;; for keywords in that the double-colon prefix
;; expands to `:<current-namespace>/foo`:
::foo
;; This is important to know about. `:foo` will
;; refer to the same keyword regardless of from which
;; namespace it is used. `::foo` will not.
)
(comment
;; = COLLECTIONS =
;; Clojure has literal syntax for four collection types
;; They evaluate to themselves.
'(1 2 3) ; list (a quoted list, more about this below)
[1 2 3] ; vector
#{1 2 3} ; set
{:a 1 :b 2} ; map
;; They compose
{:foo [1 2]
:bar #{1 2}}
;; In Clojure we do most things with just these
;; collections. Literal collections and functions.
)
(comment
;; = FUNCTIONS =
;; So far you have been able to evaluate all examples.
;; It's because we quoted that list.
;; Actually lists look like so
(1 2 3)
;; But if you evaluate that, you'll get an error:
;; => class java.lang.Long cannot be cast to class
;; clojure.lang.IFn
;; (Of course, the linter already warned you.)
;; This is because the Clojure will try to call
;; `1` as a function. When evaluating unquoted lists
;; the first element in the list is regarded as being
;; in ”function position”. A Clojure program is data.
;; In fancier words, Clojure is homoiconic:
;; https://wiki.c2.com/?HomoiconicLanguages
;; This gives great macro power, more about that below.
;; Here are some lists with proper functions at
;; position 1:
(str 1 2 3 4 5 :foo)
(< 1 2 3 4 5)
(*)
(= "1"
(str "1")
(str \1))
(println "From Clojure with ♥️")
(reverse [5 4 3 2 1])
;; Everything after the first position is
;; handed to the function as arguments
;; Note: I'll be referring to literals, symbols, and
;; literal collections collectively as forms,
;; sometimes, sexprs:
;; https://en.wikipedia.org/wiki/S-expression
;; You define new functions and bind them to names
;; in the current namespace using the macro `defn`.
;; It's a very flexible macro. Here's a simple use:
(defn add2
[arg]
(+ arg 2))
;; It defines the function `add2` taking one argument.
;; The function body calls the core functions `+`
;; with the arguments `arg` and 2.
;; Evaluating the form will define it and you'll see:
;; => #'hello-clojure/add2
;; That's a var ”holding” the value of the function
;; You can now reference the var using the symbol
;; `add2`. Putting it in the function position of a
;; list with 3 in the first argument position and
;; evaluating the list gives us back what?
(add2 3)
;; Clojure has an extensive core library of functions
;; and macros. See: https://clojuredocs.org for a
;; community-driven Clojure core (and more) search engine.
)
(comment
;; = SPECIAL FORMS =
;; The core library is composed from the functions and macros
;; in the library itself. Bootstrapping the library is
;; a few (15-ish) built-in primitive forms,
;; aka ”special forms”.
;; You have met one of these special forms already:
(quote (1 2 3))
;; The doc hover of the symbol `quote` tells you that
;; it is a special form.
;; Wondering where you met this special form before?
;; I used the shorthand syntax for it then:
'(1 2 3)
;; Convince yourself they are the same with the `=` function:
(= (quote (1 2 3))
'(1 2 3))
;; Clojure has value semantics. Any data structures
;; that evaluate to the same data are equal,
;; no matter how deep or big the structures are.
(= [1 [1 #{1 {:a 1 :b '(:foo bar)}}]]
[1 [1 #{1 {:a (- 3 2) :b (quote (:foo bar))}}]])
;; ... but that was a detour, back to special forms.
;; Official docs:
;; https://clojure.org/reference/special_forms#_other_special_forms
;; A very important special form is `fn` (which is
;; actually four special forms, but anyway).
;; Without this form we can't define new functions.
;; The following form evaluates to a function which
;; adds 2 to its argument.
(fn [arg] (+ arg 2))
;; Calling the function with the argument 3:
((fn [arg] (+ arg 2)) 3)
;; Another special form is `def`. It defines things,
;; giving them namespaced names.
(def foo :foo)
;; ”Defining a thing” means that a var is created,
;; holding the value, and that a symbol is bound
;; to the var. Evaluating the symbol picks up the
;; value from the var it is bound to.
foo
;; The var can be accessed using the `var` special
;; form.
(var foo)
;; You will most often see the var-quote shorthand
#'foo
;; With these two special forms we can define functions
(def add2-2 (fn [arg] (+ arg 2)))
(add2-2 3)
;; This is what the macro `defn` does. You will most
;; often be defining functions like what we saw
;; earlier, (when discussing the function position of
;; a form):
(defn add2-3
[arg]
(+ arg 2))
;; We can use the function `macroexpand` to see that
;; what the macro produces:
(macroexpand '(defn add2-3
[arg]
(+ arg 2)))
;; Yet another super duper important special form:
(if 'test
'value-if-true
'value-if-false)
;; Rumour has it that all conditional constructs (macros)
;; are built using `if`. Try to imagine a programming
;; language without conditionals!
;; We'll return to `if` and conditionals.
;; == `let` ==
;; `let` is a special form that lets you bind values to
;; variables that will be used in the body of the form.
(let [x 1
y 2]
(str x y))
;; The bindings are provided as the first ”argument”,
;; in a vector. This is a pattern that is used by
;; other special forms and macros that let you define
;; bindings. It is similar to the lexical scope of other
;; programming languages (even if this rather is
;; structural). Sibling and parent forms do not
;; ”see” these bindings (they have no way they could
;; possibly reach it). Here's an example:
(do
(def x :namespace-x)
(println "`x` in `do` _before_ `let`: " x)
(let [x :let-x]
(println "`x` from `let`: " x))
(println "`x` in `do`, _after_ `let`: " x))
(println "`x` _outside_ `do`: " x)
;; As noted before in this guide, the `def` special
;; form defines things ”globally”, though namespaced.
;; If you have followed the instructions to examine
;; things mentioned here, for instance by
;; ctrl/cmd-clicking the `let` symbol in the code
;; snippets, you'll find that in `core.clj`, `let`
;; is defined as a macro. Never mind that. It is
;; actually referred to as a special form here
;; https://clojure.org/reference/special_forms#let
;; Let's (pun unintended) wrap the special forms section
;; up with noting that together with _how_ Clojure
;; reads and evaluates code, the special forms make up
;; the Clojure language itself. The next level och
;; building blocks are macros.
;; But let us investigate this thing with how code
;; is read first...
)
(comment
;; = THE READER =
;; https://clojure.org/reference/reader
;; The Clojure Reader is responsible for reading text,
;; making data from it, which is what the compiler gets.
;; The Reader is where literals, symbols, strings, lists,
;; vectors, maps, and sets are picked apart and
;; re-assembled, figuring out what is a function,
;; a macro or special form.
;; In doing this whitespace plays a key role and there
;; are also some extra syntax rules are in play.
;; == WHITESPACE ==
;; Most things you would think counts as whitespace
;; is whitespace, and then there is also that Clojure,
;; being a LISP, does not need commas to separate
;; list items. However, commas can be used for this
;; anyway, since commas are whitespace.
(= '(1 2 3)
'(1,2,3)
'(1, 2, 3)
'(1,,,,2,,,,3))
;; (There are no operators in Clojure, `=` is a
;; function. It will check for equality of all
;; arguments it is passed.)
;; == LINE COMMENTS ==
;; The Reader skips reading everything on a line from
;; a semicolon. This is unstructured comments in
;; that if you start a form
(range 1 ; 10)
;; and then place a line comment so that the closing
;; bracket of that form gets commented out, the
;; structure breaks.
)
;; ^ Healing the structure.
;; If you remove the semicolon on the opening form
;; above, make sure to also remove this closing paren.
;; Since everything on the line is ignored, you can
;; add as many semicolons as you want.
;;;;;;;;;; (skipped by the Reader)
;; It's common to use two semicolons to start a full
;; line comment.
;; == EXTRA SYNTAX ===
;; We've already seen the single quote
'something
;; Which is, as we have seen, transformed to
(quote something)
;; `quote` is needed to stop the Reader from treating
;; things as something that should be evaluated.
;; See what happens if you evaluate `something`
;; without the quoting:
something
;; as well as the difference between evaluating these:
(1 2 3 4)
'(1 2 3 4)
;; There are some more quoting, and even splicing
;; symbols, which I won't cover in this guide.
;; === Deref ===
;; Clojure also has reference types, we'll discuss
;; (briefly) the most common one, `atom`, later.
(def an-atom (atom [1 2 3]))
(type an-atom)
;; To access value from a reference:
(deref an-atom)
(type (deref an-atom))
;; Again, `deref` is used for dereferencing a lot
;; different reference types, including futures,
;; https://clojure.org/reference/refs
;; https://clojure.org/about/concurrent_programming
;; Anyway, `deref` is so common that there is
;; shorthand syntax for it
@an-atom
(= (deref an-atom)
@an-atom)
;; It's a common mistake to forget to deref
(first an-atom)
(first @an-atom)
;; === THE DISPATCHER (HASH SIGN) ===
;; That hash sign shows up now and then. It has a
;; special role. It is aka Dispatch. Depending on
;; what character is following it, different cool
;; things happen. Here follows some common ones:
;; Regular expressions have literal syntax, they are
;; written like strings, but with a hash sign in front
#"reg(?:ular )?exp(?:ression)?"
;; Regexps are handled by the host platform, so they
;; are Java regexps in this tutorial. If you
;; evaluated the above regexp, we can test it.
(re-seq *1 "regexp regular expression")
;; `*1` is a special symbol for a variable holding
;; the value of the last evaluation result. It might
;; be easier to get a regexp right by using it
;; directly:
(re-seq #"fooo*" "fo foo fooo")
(re-find #"fooo*" "fo foo fooo")
;; If the hash sign is followed by a `(`, the Reader
;; will start expecting a function body.
#(+ % 2)
;; This is special syntax for ”function literals”, a
;; way to specify a function. The example above is
;; equivalent to this anonymous function.
(fn [arg] (+ arg 2))
;; Nesting function literals is forbidden activity
;(#(+ % (#(- % 2) 3)))
;; (thankfully)
;; In addition to sets, regexps and function literals
;; we have seen var-quotes earlier in this guide
#'add2
;; There was also a brief discussion about `vars`.
;; You might want to revisit it and also read more
;; about it, because it is a very important concept.
;; https://clojure.org/reference/vars
;; There is a very useful hash-dispatcher which
;; is used to make the Reader ignore the next form
#_(println "The reader will not send this function call
to the compiler") "This is not ignored"
;; To test this select the ignore marker together with
;; the function call and the string, then use Ctrl+Enter,
;; to make Calva send it all to the Reader, which will
;; read it, ignore the function call, and only evaluate
;; the string.
;; Since #_ ignores the next form it is a structural
;; comment mechanism, often used to temporarily disable
;; some code or some data
(str "a" "b" #_(str 1 2 3 [4 5 6]) "c")
;; Ignore markers stack
(str "a" #_#_"b" (str 1 2 3 [4 5 6]) "c")
;; Note that the Reader _will_ read the ignored form.
;; If there are syntactic errors in there, the
;; Reader will get sad, complain, and stop reading.
;; Select from the marker up to and including the string
;; here and press Ctrl+Enter
;#_(#(+ % (#(- % 2) 3))) "foo"
;; Two more common #-variants you will see, and use,
;; are namespaced map keyword shorthand syntax and
;; tagged literals, aka, data readers. Let's start
;; with the former:
(= #:foo {:bar 'bar
:baz 'baz}
{:foo/bar 'bar
:foo/baz 'baz})
;; Unrelated to the #: There is another shorthand for
;; specifying namespaced keywords. Double colon
;; keywords get namespaced with the current namespace
::foo
(= ::foo :welcome-to-clojure/foo)
;; Tagged literals, then. It's a way to invoke functions
;; bound to the tags on the form following it.
;; https://clojure.org/reference/reader#tagged_literals
;; They are also referred to as data readers. You can
;; define your own. Here let it suffice with mentioning
;; the two build in ones.
;; #inst will convert the string it tags to an instance.
;; (I.e. an instance in time, not an instance in the
;; Object Orientation sense of the word.)
#inst "2018-03-28T10:48:00.000"
(type *1)
;; #uuid will make an UUID of the string it tags
#uuid "0000000-0000-0000-0000-000000000016"
(java.util.UUID/fromString "0000000-0000-0000-0000-000000000016")
;; You now know how to read (in the sense of you
;; being a Clojure Reader) most Clojure code.
;; That said, let's skip going into the syntax
;; sugar and special forms for making host platform
;; interop extra nice.
;; https://clojure.org/reference/java_interop
;; Just a sneak peek:
(.before #inst "2018-03-28T10:48:00.000"
#inst "2021-02-17T00:27:00.000")
;; This invokes the method `before` on the date
;; object for year 2018 giving it the date from
;; year 2021 as argument. You'll see some little
;; more Java interop in this guide and probably
;; notice how available the host platform is when
;; coding Clojure. The same goes for
;; ClojureScript and for Clojure CLR.
;; Repeating this important resource on the Reader:
;; https://clojure.org/reference/reader
;; And in addition to that, read about All Those
;; Weird Characters here:
;; https://clojure.org/guides/weird_characters
)
(comment
;; = MACROS =
;; Clojure has powerful data transformation
;; capabilities. We'll touch on that a bit later.
;; Here I want to highlight that this power can
;; be wielded for extending the language itself.
;; Since Clojure code is structured and code is
;; data, Clojure can be used to produce Clojure
;; code from Clojure code. It is similar to the
;; preprocessor facilitates that some languages
;; offer, like C's `#pragma`, but it is much more
;; convenient and powerful. A lot of what you
;; will learn to love and recognize as Clojure
;; is actually created with Clojure, as macros.
;; This guide is mostly concerned with letting you
;; know that macros are a thing, to help you to
;; quickly realize when you are using a macro rather
;; than a function. I.e. I will not go into the
;; subject of how to create macros.
;; The distinction is important, because even if
;; macro calls look a lot like function calls,
;; macros are not first class. They can't be
;; passed as arguments, or returned as results.
;; More about ”first class” in the section about
;; functions, later.
;; == `when` ==
;; Let's just briefly examine the macro`when`.
;; This macro helps with writing more readable code.
;; How? Let's say you want to conditionally evaluate
;; something. Above you learnt that there is
;; a special form named `if` that can be used for
;; this. Like so:
(if 'this-is-true
'evaluate-this
'else-evaluate-this)
;; Now say you don't have something to evaluate
;; in the else case. `if` allows you to write this
(if 'this-is-true
'evaluate-this)
;; Which is fine, but you will have to scan the
;; code a bit extra to see that there is no else
;; branch. Easy with this short example, but can
;; get pretty hairy in real code. To address this,
;; you could write:
(if 'this-is-true
'evaluate-this
nil)
;; But that is a bit silly, what if there was a
;; way to tell the human reading the code that
;; there is no else branch? There is!
(when 'this-is-true
'evaluate-this)
;; Let's look at how `when` is defined, you can
;; ctrl/cmd-click `when` to navigate to where
;; it is defined in Clojure `core.clj`.
;; You can also use the function `macroexpand`
(macroexpand '(when 'this-is-true
'evaluate-this))
;; You'll notice that `when` wraps the body in
;; a `(do ...)`, which is a special form that lets
;; you evaluate several expressions, returning the
;; results of the last one.
;; https://clojuredocs.org/clojure.core/do
;; `do` is handy when you want to have some side-
;; effect going, in addition to evaluating something.
;; In development this often happens when you
;; want to `println` something before the result
;; of the expression is evaluated and returned.
(do (println "The quick brown fox jumps over the lazy dog")
(+ 2 2))
;; The `when` macro let's you take advantage of that
;; there is only one branch, so you can do this
(when 'this-is-true
(println "The quick brown fox jumps over the lazy dog")
(+ 2 2))
;; Without `when` you would write:
(if 'this-is-true
(do
(println "The quick brown fox jumps over the lazy dog")
(+ 2 2)))
;; Here `when` saves us both the extra scanning for
;; the else-branch and the use of `do`.
;; As far as macros go, `when` is about as simple as
;; they get. From two built-in special forms,
;; `if` and `do`, it composes a form that helps us
;; write easy to write and easy to read code.
;; == `for` ==
;; The `for` macro really demonstrates how Clojure
;; can be extended using Clojure. You might think
;; it provides looping like the for loop in many
;; other languages, but in Clojure there are no for
;; loops. Instead `for` is about list comprehensions
;; (if you have Python experience, yes, that kind of
;; list comprehensions). Here's how to produce the
;; cartesian product of two vectors, `x` and `y`:
(for [x [1 2 3]
y [1 2 3 4]]
[x y])
;; If you recall the `let` form above, and how it
;; lets you bind variables to use in the body of the
;; form, this is similar, only that `x` and `y` will
;; get bound to each value in the sequences and the
;; body will get evaluated for all combinations of
;; `x` and `y`.
;; All values? Well, `for` also lets you filter the
;; results
(for [x [1 2 3]
y [1 2 3 4]
:when (not= x y)]
[x y])
;; You can bind variable names in the comprehension
;; to store intermediate calculations and generally
;; make code more readable
(for [x [1 2 3]
y [1 2 3 4]
:let [d' (- x y)
d (Math/abs d')]]
d)
;; Is the same as:
(for [x [1 2 3]
y [1 2 3 4]]
(Math/abs (- x y)))
;; Debatable what is more readable in this particular
;; case... ¯\_(ツ)_/¯
;; A note about the variable name `d'` above:
;; `d'` is just a symbol name like any other. The
;; single-quote has no special meaning unless it is
;; the first character
;; Filters and bindings can be used together.
;; Use both `:let` and `:when` to make this
;; comprehension return a list of all `[x y]` where
;; their sum is odd. The functions `+` and `odd?`
;; are your friends here.
(for [x [1 2 3]
y [1 2 3 4]]
[x y])
;; (Yes, it can be solved without `:let` or `:when`.
;; Humour me. 😎)
;; See https://www.youtube.com/watch?v=5lvV9ICwaMo for
;; a great primer on Clojure list comprehensions
;; See https://clojuredocs.org/clojure.core/for for
;; example usages and tips.
;; Note that even though `let` and `for` look like
;; functions, they are not. The compiler would not
;; like it if you are passing undefined symbols to a
;; function. This is legal code:
(let [abc 1]
2)
;; This isn't.
(str [abc 1]
1)
;; (Notice that the clj-kondo linter is marking the
;; first with a warning, and the second as an error)
;; Macros extend the Clojure compiler.
;; https://clojure.org/reference/macros
;; == Threading macros ==
;; Macros can totally rearrange your code. The
;; built-in ”threading” macros do this. Sometimes
;; when the nesting of function(-ish) calls get
;; deep it can get a bit hard to read and to keep
;; track of all the parens
(Math/abs
(apply -
(:d (zipmap
[:a :b :c :d]
(partition 2 [1 1 2 3 5 8 13 21])))))
;; You read Clojure from the innermost expression
;; and out, which gets easier with time, but an
;; experienced Clojure coder would still find it
;; easier to read this
(->> [1 1 2 3 5 8 13 21]
(partition 2)
(zipmap [:a :b :c :d])
:d
(apply -)
(Math/abs))
;; Let's read this together. The thread-last macro,
;; `->>` is used, it takes its first argument and
;; places it (threads it) as the last argument to
;; following function. The first such step in
;; isolation:
(->> [1 1 2 3 5 8 13 21]
(partition 2))
;; The first argument/element passed to `->>` is
;; `[1 1 2 3 5 8 13 21]`
;; This is inserted as the last element of the
;; function call `(partition 2)`, yielding:
(partition 2 [1 1 2 3 5 8 13 21])
;; This partitions the list into lists of
;; 2 elements => `((1 1) (2 3) (5 8) (13 21))`
;; This new list is then inserted (threaded)
;; as the last argument to the next function,
;; yielding:
(zipmap [:a :b :c :d] '((1 1) (2 3) (5 8) (13 21)))
;; Which ”zips” together a Clojure map using
;; the first list as keys and the second list
;; as values
;; => `{:a (1 1), :b (2 3), :c (5 8), :d (13 21)}`
;; This map is then threaded as the last argument
;; to the function `:d`
(:d '{:a (1 1), :b (2 3), :c (5 8), :d (13 21)})
;; (In clojure keywords are functions that look
;; themselves up in the map handed to them.)
;; => `(13 21)`
;; You know the drill by now, this is threaded
(apply - '(13 21))
;; Which applies the `-` function over the list
;; => `-8`
;; Then this is threaded to `Math/abs`
(Math/abs -8)
;; 🎉
;; (In many Clojure capable editors, including
;; Calva, there are commands for ”unwinding”
;; a thread, and for converting a nested
;; expressions into a thread. Search for ”thread”
;; among the commands.)
;; https://github.com/clojure-emacs/clj-refactor.el/wiki/cljr-unwind-all
;; There is also a thread-first macro
;; `->` https://clojuredocs.org/clojure.core/-%3E
;; Sometimes you neither want to thread first
;; of last. There is a macro for this too.
;; `as->` lets you bind a variable name to the
;; threaded thing and place it wherever you
;; fancy in each function call.
(as-> 15 foo
(range 1 foo 3)
(interpose ":" foo))
;; https://clojuredocs.org/clojure.core/as-%3E
;; It's common to utilize the fact that most characters
;; are available when naming Clojure symbols. I often
;; use `$` for this threading macro:
(as-> 15 $
(range 1 $ 3)
(interpose ":" $))
;; Others use other names 😄
(as-> 15 <>
(range 1 <> 3)
(interpose ":" <>))
;; I think emojis should be avoided, the official
;; docs only mention alphanumerics plus:
;; `*`, `+`, `!`, `-`, `_`, `'`, `?`, `<`, `>`, and `=`
;; (so not even `$`) but here goes:
(as-> 15 ❤️
(range 1 ❤️ 3)
(interpose ":" ❤️))
;; Other core threading macros are:
;; `cond->`, `cond->>`, `some->`, and `some->>`
;; https://clojuredocs.org/clojure.core/cond-%3E
;; Please feel encouraged to copy the examples
;; from ClojureDocs here and play with them.
;; Here's one:
(cond-> 1 ; we start with 1
true inc ; the condition is true so (inc 1) => 2
false (* 42) ; the condition is false so the operation is skipped
(= 2 2) (* 3)) ; (= 2 2) is true so (* 2 3) => 6
;; See ”Threading with Style” by <NAME>
;; for idiomatic use of the threading facilities.
;; https://stuartsierra.com/2018/07/06/threading-with-style
)
;; With special forms, the special syntax of the Reader,
;; and macros, the foundations of what is the Clojure
;; language you use are laid. You can of course extend
;; the language further with libraries including macros
;; or create your own. However the core language, with
;; its macros is very expressive. Taking data oriented
;; approaches is often enough. Even to prefer, rather
;; than creating more macros.
;; On to flow control!
(comment
;; = Flow Control, Conditionals, Branching =
;; Clojure is richer than most languages in what it
;; offers us to let our programs flow the way we want
;; them to. Almost all the core library features for
;; this are implemented using the primitive (special
;; form) `if`. This is still the staple for us as
;; Clojure coders. It takes three forms as its
;; arguments:
;; 1. A condition to evaluate
;; 2. What to evaluate if the condition evaluates
;; to something true (truthy)
;; 3. The form to evaluate if the condition does not
;; evaluate to something truthy (the ”else” branch)
;; Roll this dice, some ten-twenty times, checking if
;; it is a six:
(if (= 6 (inc (rand-int 6)))
"One time out of six you get a six"
"Five times out of six you get something else")
;; Since there are no statements in Clojure `if` is
;; the equivalent to the ternary `if` expression you
;; find in C and many other languages:
;; test ? true-expression : false-expression
;; Pseudo code for our dice:
;; int(rand() * 6) + 1 == 6 ?
;; "One time out of six you get a six" :
;; "Five times out of six you get something else";
;; == The Search for Truth ==
;; Again, in Clojure we use expressions evaluating to
;; values. When examined for branching all values
;; are either truthy or falsy. In fact, almost all
;; values are truthy
(if true :truthy :falsy)
(if :foo :truthy :falsy)
(if '() :truthy :falsy)
(if 0 :truthy :falsy)
(if "" :truthy :falsy)
;; The only falsy values are `false` and `nil`
(if false :truthy :falsy)
(if nil :truthy :falsy)
(when false :truthy)
;; About that last one: `when` evaluates to `nil`
;; when the condition is falsy. Since `nil` is
;; falsy the above `when` expression would be
;; making the ”else” branch of an `if` to be
;; evaluated
(if (when false :truthy) :true :falsy)
;; (Super extra bad code, but anyway)
;; When only boolean truth or falsehood can cut
;; it for you, there is the `true?` function
(true? true)
(true? 0)
(true? '())
(true? nil)
(true? false)
;; Thus
(if (true? 0) :true :false)
;; == `when` ==
;; As mentioned before, `when` is a one-branch
;; `if`, only for the truthy branch, which is
;; wrapped in a `do` for you. Try this and then
;; try it replacing the `when` with an `if`:
(when :truthy
(println "That sounds true to me")
:truthy-for-you)
;; If the `when` condition is not truthy,
;; `nil` will be returned.
(when nil :true-enough?)
;; == `cond` ==
;; Since deeply nested if/else structures can be
;; hard to write, read, and maintain, Clojure core
;; offers several more constructs for flow control,
;; one very common such is the `cond` macro. It
;; takes pairs of condition/result forms, tests
;; each condition, if it is true, then the result
;; form is evaluated and ”returned”, short-circuiting
;; so that no more condition is tested.
(let [dice-roll (inc (rand-int 6))]
(cond
(= 6 dice-roll) "Six is as high as it gets"
(odd? dice-roll) (str "An odd roll " dice-roll " is")
:else (str "Not six, nor odd, instead: " dice-roll)))
;; The `:else` is just the keyword `:else` which
;; evaluates to itself and is truthy. It is the
;; conventional way to give your cond forms a
;; default value. Without a default clause, the
;; form would evaluate to `nil` for anything not-six
;; not-odd. Try it by placing two ignore markers
;; (`#_ #_`) in front of the `:else` keyword.
;; Gotta love ClojureDocs
;; https://clojuredocs.org/clojure.core/cond
;; Paste examples from there here and play around:
;; See also links to `cond->` info above
;; == `case` ==
;; A bit similar to `switch/case` constructs in
;; other languages, Clojure core has the `case`
;; macro which takes a test expression, followed by
;; zero or more clauses (pairs) of test constant/expr,
;; followed by an optional expr. (However, the body
;; after the test expression may not be empty.)
(let [test-str "foo bar"]
(case test-str
"foo bar" (str "That's very " :foo-bar)
"baz" :baz
(count test-str)))
;; The trailing expression, if any, is ”returned” as
;; the default value.
(let [test-str "foo bar"]
(case test-str
#_#_"foo bar" (str "That's very " :foo-bar)
"baz" :baz
(count test-str)))
;; If no clause matches and there is no default,
;; a run time error happens
(let [test-str "foo bar"]
(case test-str
#_#_"foo bar" (str "That's very " :foo-bar)
"baz" :baz
#_(count test-str)))
;; WATCH OUT! A test constant must be a compile
;; time literal, and the compiler won't help you
;; find bugs like this:
(let [test-int 2
two 2]
(case test-int
1 :one
two (str "That's not a literal 2")
(str test-int ": Probably not expected")))
;; https://clojuredocs.org/clojure.core/case
;; Paste some `case` examples here and experiment
;; The Functional Design in Clojure podcast has a
;; fantastic episode about branching
;; https://clojuredesign.club/episode/089-branching-out/
;; == Less branching is good, right? ==
;; The core library is rich with functions that
;; helps you avoid writing branching code. Instead
;; you provide the condition as a predicate.
;; An often used predicate function is `filter`
(filter even? [0 1 2 3 4 5 6 7 8 9 10 11 12])
;; and its ”sibling” `remove`
(remove odd? [0 1 2 3 4 5 6 7 8 9 10 11 12])
;; Filtering sequences of values is a common task
;; and your programming time can instead be used
;; to decide _how_ it should be filtered, by writing
;; the predicate. Sometimes you don't even need to
;; do that, Clojure core is rich with predicates
(zero? 0)
(even? 0)
(neg? 0)
(pos? 0)
(nat-int? 0)
(empty? "")
(empty? [])
(empty? (take 0 [1 2 3]))
(integer? -2/1)
(indexed? [1 2 3])
(indexed? '(1 2 3))
;; What's a predicate? For the purpose of this guide
;; A predicate is a function testing things for
;; truthiness. It is convention that these functions
;; end with `?`. Many take only one argument.
;; A handy predicate is `some?` which tests for
;; "somethingness”, if it is not `nil` it is
;; something
(some? nil)
(some? false)
(some? '())
;; You can use it to test for if something is `nil`
;; by wrapping it in a call to the `not` function
(not (some? nil))
(not (some? false))
;; You get the urge to define a function named `nil?`,
;; right? You don't have to
(nil? nil)
(nil? false)
;; Clojure core also contains predicates that take
;; a predicate plus a collection to apply it on.
;; Such as `every?`
(every? nat-int? [0 1 2])
(every? nat-int? [-1 0 1 2])
;; Check the docs for `nat-int? and come up
;; with some more lists to test, like
(every? nat-int? [0 1 2N]) ; 2N is not fixed precision
(doc nat-int?)
;; This pattern with functions that take functions
;; as argument is common in Clojure. It spans beyond
;; predicates. Functions that take functions as
;; arguments are referred to as ”higher order
;; functions”.
;; https://en.wikipedia.org/wiki/Higher-order_function
)
(comment
;; = Functions =
;; Before diving into higher order functions, let's
;; look at functions.Functions are first class
;; Clojure citizens and the main building blocks for
;; solving your business problems.
;; We have seen a few ways you can create functions.
;; Here's an anonymous function that returns the
;; integer given to it, unless it is divisible by
;; 15, in which case it returns "fizz buzz".
;; (Not the full Fizz Buzz problem by any means.)
(fn [n]
(if (zero? (mod n 15))
"fizz buzz"
n))
;; Let's define it (bind it to a symbol we can use)
(def fizz-buzz-1 (fn [n]
(if (zero? (mod n 15))
"fizz buzz"
n)))
(fizz-buzz-1 2)
(fizz-buzz-1 15)
;; There's a macro that lets us define and create
;; the function in one call
(defn fizz-buzz-2 [n]
(if (zero? (mod n 15))
"fizz buzz"
n))
(fizz-buzz-2 4)
;; `defn` lets us provide documentation for the
;; function
(defn fizz-buzz-3
"Says 'fizz buzz' if `n` is divisible by 15,
otherwise says `n`"
[n]
(if (zero? (mod n 15))
"fizz buzz"
n))
(doc fizz-buzz-3) ; (or hover `fizz-buzz-3`)
;; It is easy to place the doc string wrong,
;; especially since it is common to write the `defn`
;; form like we did with `fizz-buzz-2` above.
(defn fizz-buzz-4
[n]
"Says 'fizz buzz' if `n` is divisible by 15,
otherwise says `n`"
(if (zero? (mod n 15))
"fizz buzz"
n))
;; This specifies a fully valid function body, so
;; Clojure won't complain about it. But:
(doc fizz-buzz-4)
;; clj-kondo's default configuration will help you
;; spot these errors. However, it can't help with
;; this:
(defn only-the-last-eval-returns [x]
[1 x]
[2 x])
(only-the-last-eval-returns "foo")
;; It is easy enough to spot like this and also to
;; wonder why you would ever write a function that
;; way. Yet you probably will do this mistake,
;; especially if you ever write some Hiccup, which
;; is a super nice way of writing HTML with Clojure
;; data structures. It's used by the popular Reagent
;; library
;; https://purelyfunctional.tv/guide/reagent/#hiccup
;; When you do the mistake and finish your hour-long
;; bug hunt, you will hear this guide whisper
;; ”Called it!”
;; The argument binding vector of `fn` (and
;; therefore `defn`) binds each argument in order
;; to a name.
(defn coords->str [x y]
(str "x: " x ", y: " y))
;; == Variadic Functions ==
;; You can define functions that take an arbitrary
;; number of arguments by placing a `&` in front
;; of the last argument name. That binds the name
;; to a sequence that contains all the remaining
;; arguments.
(defn lead+members [lead & members]
{:lead lead
:members members})
(lead+members "<NAME>"
"<NAME>"
"<NAME>"
"<NAME>")
;; == Multi-arity ==
;; Clojure supports function signatures based on
;; the number of arguments. The `defn` macro lets
;; you define each arity as a separate list. This
;; is often used to provide default values
(defn hello
([] (hello "World"))
([s] (str "Hello " s "!")))
(hello)
(hello "Clojure Friend")
;; Or to create an ”identity” value for a function,
;; (A starting value that the rest of the operation
;; uses.) Say you want to add two x-y coordinates
(defn add-coords-1 [coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))})
(add-coords-1 {:x -2 :y 10}
{:x 4 :y 6})
;; What if the requirements were that if the
;; function is called with ne argument it should
;; add it to the origin? (See what I did there?
;; The identity value is where the function
;; should start, so start from the origin. 😎)
;; We can see that `add-coords-1` fails here
(add-coords-1 {:x -2 :y 10})
;; we need to add a one-arity
(defn add-coords-2
([coord]
(add-coords-2 {:x 0
:y 0}
coord))
([coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))}))
(add-coords-2 {:x -2 :y 10})
;; Now if called with no arguments it should
;; return the origin, because if you do not add
;; any coordinate you stay at the start.
;; Write a function `add-coords-3` that returns
;; the origin when called like this
(add-coords-3)
;; It should still handle to be called like this
(add-coords-3 {:x 3 :y 4})
(add-coords-3 {:x 2 :y 4}
{:x -4 :y -4})
;; It has to do with making the function compose
;; with other functions. E.g. the `apply` function
;; which is a higher order function that ”applies”
;; a function over a sequence. Right now we can
;; apply our `add-coords-2` function like this
(apply add-coords-2 [{:x 1 :y 1} {:x 4 :y 4}])
;; And like this
(apply add-coords-2 [{:x 1 :y 1}])
;; But not like this
(apply add-coords-2 [])
;; But the `add-coords-3` function you created can
(apply add-coords-3 [])
;; It will not handle an arbitrary long sequence
;; of coords, though. For that we would need one
;; more arity like so
(defn add-coords-4
;; add zero-arity from your `add-coords-3` here
;; add one-arity from your `add-coords-3` here
([coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))})
([coord-1 coord-2 & more-coords]
;; Implement this arity when you have learnt
;; about the higher order function `reduce`
))
(apply add-coords-4 [{:x 1 :y 1}
{:x 1 :y 1}
{:x 1 :y 1}
{:x -6 :y -6}])
;; Listen to Eric Normand explain in more detail
;; why the identity of a function is important:
;; https://lispcast.com/what-is-a-functions-identity/
;; == Closures ==
;; When you create functions on the fly, lambdas,
;; if you like, you use either the `fn` special
;; form directly, or by proxy with the `#()` syntax.
;; This creates a closure, like it does in JavaScript
;; and other languages. That is, these function can
;; access snapshots of variables with the values they
;; had when the function was created
(defn named-coords-factory [name]
(fn [x y] {:name name
:coords {:x x
:y y}}))
(def bob-coords-fn (named-coords-factory "<NAME>"))
(def fred-coords-fn (named-coords-factory "<NAME>"))
(bob-coords-fn 0 0)
(fred-coords-fn 5 5)
(bob-coords-fn 7 7)
;; Closures are handy to create low-arity functions
;; inside let binding boxes for the function body
;; to use:
(defn whisper-or-yell-or-ask [command sentence]
(let [whisper (fn []
(str (string/lower-case sentence) command))
yell (fn []
(str (string/upper-case sentence) command))
ask (fn []
(str sentence "?"))
default (fn []
(str sentence command " ¯\\_(ツ)_/¯"))]
(case command
"" (whisper)
"!" (yell)
"?" (ask)
(default))))
;; All functions created in the let binding box
;; ”close in” the `command` and the `sentence` so
;; the `case` can be kept terse and readable.
(whisper-or-yell-or-ask "" "How wOnDerFuLLY NIce To seE")
(whisper-or-yell-or-ask "!" "Hello tHERE")
(whisper-or-yell-or-ask "?" "How are you doing")
(whisper-or-yell-or-ask ":" "Oh well")
;; == The Attributes Map ==
;; The `defn` macro lets you add attributes to the
;; function in the form of a map. This gets added
;; as meta-data (some little more on that later)
;; to the var holding the function. The map goes
;; after the function name, and after any docs,
;; and before the arguments vector (or any arities)
(defn i-have-attributes
{:doc "Docs can be added like this too"
:foo "Any attributes you fancy"}
[]
"Good for you")
(doc i-have-attributes)
(meta #'i-have-attributes)
;; One handy attribute you can add is a test
;; function. Test runners will pick this up
(defn fizz-buzz-5
"That limited fizz-buzz function again"
{:test (fn []
(is (= "fizz-buzz" (fizz-buzz-5 15)))
(is (= 3 (fizz-buzz-5 3))))}
[n]
(if (pos? (rem 15 n))
"fizz-buzz"
n))
(clojure.test/test-var #'fizz-buzz-5)
;; Oops! You'll need to fix the bugs. 😀
;; How about implementing the complete Fizz Buzz?
;; https://en.wikipedia.org/wiki/Fizz_buzz
(defn fizz-buzz
"My Fizz Buzz solution"
{:test (fn []
(are [arg expected]
(= expected (fizz-buzz arg))
1 1
3 "Fizz"
4 4
5 "Buzz"
7 7
15 "Fizz Buzz"
20 "Buzz"))}
[n])
(clojure.test/test-var #'fizz-buzz)
(map fizz-buzz (range 1 40))
;; The meta-data that has special meaning to
;; the compiler and various Clojure core
;; facilities is listed here:
;; https://clojure.org/reference/special_forms
;; Now, on to higher order functions!
)
(comment
;; = Higher order functions =
;; A big contribution to what makes Clojure such a
;; powerful language is that functions are
;; ”first-class”
;; https://en.wikipedia.org/wiki/First-class_function
;; They can be values in collections (also keys
;; in maps) and can be passed as arguments to other
;; functions, and ”returned ”as results from
;; evaluations. You might be familiar with the
;; concept from languages like JavaScript.
;; Let's look at some higher order functions in
;; Clojure core. `some` calls the function on the
;; elements of its collection, one-by-one, and
;; returns the first truthy result, and will return
;; `nil` if the list is exhausted before some element
;; results in something truthy.
(some even? [1 1 2 3 5 8 13 21])
;; Not to be confused with `some?`, which is not
;; a higher order function.
(some some? [nil false])
(some some? [nil nil])
;; A common idiom in Clojure is to look for things
;; in collection using a `set` as the predicate.
;; Yes, sets are functions. Used as functions they
;; will look up the argument given to them in
;; themselves.
(#{"foo" "bar"} "bar")
;; Thus
(some #{"foo"} ["foo" "bar" "baz"])
(some #{"fubar"} ["foo" "bar" "baz"])
;; `apply` takes a function and a collection and
;; ”applies” the function on the collection. Say you
;; have a collection of numbers and want to add them.
;; This won't work:
(+ [1 1 2 3 5 8 13 21])
;; `apply` to the rescue
(apply + [1 1 2 3 5 8 13 21])
;; Concatenate the numbers as a string:
(apply str [1 1 2 3 5 8 13 21])
;; Contrast with
(str [1 1 2 3 5 8 13 21])
;; We've also seen `filter` and `remove` above, two
;; very commonly used higher order functions. They
;; play in the same league as `map`, and `reduce`.
;; Read on. 😎
)
(comment
;; = `map` and `reduce` =
;; Among the higher order functions you might have
;; used in other languages with first class
;; functions are `map` and `reduce`. They are worth
;; studying and practicing in much detail, here's
;; a super nice teaser:
;; https://purelyfunctional.tv/courses/3-functional-tools/
;; Let's also check them out briefly here.
;; `map` calls a function on the elements of one or
;; more collection from start to end and returns a
;; (lazy, more on that later) sequence of the results
;; in the same order. Let's say we want to decrement
;; each element in a list of numbers by one
(map dec '(1 1 2 3 5 8 13 21))
;; Let's say we then want to dec them again
(->> '(1 1 2 3 5 8 13 21)
(map dec)
(map dec))
;; Hmmm, better to subtract by two, maybe?
(map (fn [n] (- n 2)) '(1 1 2 3 5 8 13 21))
;; If you give `map` more collections to work on
;; it will repeatedly:
;; 1. pick the next item from each collection
;; 2. give them to the mapping function as arguments
;; 3. add the result to its return sequence
;; Until the shortest collection is exhausted
(map + [1 2 3] '(0 2 4 6 8))
(map (fn [n1 s n2] (str n1 ": " s "-" n2))
(range)
["foo" "bar" "baz"]
(range 2 -1 -1))
;; (We haven't talked much about `range`, it is a
;; function producing sequences of numbers. Given no
;; arguments it produces an infinite, watch out 😀,
;; sequence of integers
;; 0, 0+1, 0+2, 0+3, 0+4, 0+5, 0.6 ...
;; Good thing the other sequences got exhausted!)
;; A lot of the tasks you might solve with `for`
;; loops in other languages, are solved with `map`
;; in Clojure.
;; With other such ”for loopy” tasks you will
;; be wielding `reduce`. Unlike `map` it is not
;; limited to producing results of the same length
;; or shape as the input collection. Instead it
;; accumulates a result of any shape. For instance,
;; it can create a string from a collection of
;; numbers
(reduce (fn [acc n]
(str acc ":" n))
[1 1 2 3 5 8 13 21])
;; `reduce` will call the function with two
;; arguments: the result of the last function
;; call and the next number from the list. The
;; start of the process is special, since then
;; there are no results yet. `reduce` has two
;; ways to deal with this, two arities to be
;; specific. Called with two arguments, it
;; uses the two first elements from the list
;; for the first function call.
;; Here's reducing the `+` function using the
;; two-arity version of `reduce`
(reduce + [1 1 2 3 5 8 13 21])
;; The process then starts with calling `+`
;; like so
(+ 1 1)
;; Giving `reduce` three arguments makes it us
;; the second argument as the starting ”result”.
(reduce + 100 [1 1 2 3 5 8 13 21])
;; You might have noticed that the `+` function
;; takes more (and less) than 2 arguments.
(+)
(+ 1)
(+ 1 1)
(+ 1 1 2 3 5 8 13 21)
;; `+` will take the first argument, if any, and
;; add it to ”the current” value (which is zero),
;; then the next argument and add that to the new
;; current value, and so on, and so forth, until
;; there is a result. This process sounds a bit
;; like I just described a reduce, right?
;; In fact it is.
;; If we were to implement the `+` function, how
;; could we do it? We could start by implementing
;; something that adds two numbers together, then
;; use it as as the reducing function with
;; `reduce`.
;; Of course, now we have the task of adding two
;; numbers together, without using the existing
;; `+` function... 🤔
;; Hmmm... Let's keep it simple and only do
;; integer math. Then we can use the Java's
;; `Integer.sum(x, y)` method.
(Integer/sum 1 1)
;; Awesome, with this we can create an `add-two`
;; function
(defn add-two [x y]
(Integer/sum x y))
(add-two 1 1)
;; Unlike `+`, this one is not fully composable
;; with a higher order function like apply
(apply add-two [])
(apply add-two [1])
(apply add-two [1 1])
(apply add-two [1 1 2 3 5 8 13 21])
;; We need `add-many`. With `reduce` and our
;; `add-two` we can define `add-many` like so
(defn add-many [& numbers]
(reduce add-two numbers))
;; That does it, right?
(apply add-many [1])
(apply add-many [1 1])
(apply add-many [1 1 2 3 5 8 13 21])
;; What about the zero-arity version of `+`, you
;; ask? Correct, that will blow up
(add-many)
;; The built-in `+` function has a default ”current”
;; value of zero, remember? We can add that to
;; `add-many` in two ways: Either add a zero-arity
;; signature, or use the three-arity `reduce`. Let's
;; go for the latter option, since we are learning
;; about reduce here:
(defn add* [& numbers]
(reduce add-two 0 numbers))
(add*)
(add* 1)
(add* 1 1)
(add* 1 1 2 3)
;; BOOM.
;; We can use it with `apply` as well:
(apply add* [])
(apply add* [1])
(apply add* [1 1])
(apply add* [1 1 2 3 5 8 13 21])
;; Or `reduce`:
(reduce add* [])
(reduce add* [1])
(reduce add* [1 1])
(reduce add* [1 1 2 3 5 8 13 21])
;; Apart from that we only handle integers, our `add*`
;; is very much like how `+` is implemented in
;; Clojure core. Check it out (in the output window):
(source +)
;; Hmmm, well, they seem to be using multi-arity
;; function signatures for the low-arity cases, probably
;; because of the casting, but anyway, 😀
;; There's one more thing with `reduce` we want to
;; mention. When writing reducing functions you can
;; stop the process before the input sequence is
;; exhausted, using the `reduced` function. Say we
;; want the input sequence as a string separated by
;; `:`, as above, but stop when we see a `nil` item.
;; Here's the last version for comparison:
(reduce (fn [acc n]
(str acc ":" n))
[1 1 2 3 5 8 nil 13 21])
;; We can short circuit the process by calling
;; `reduced` with the accumulated value when we
;; encounter a `nil` item
(reduce (fn [acc n]
(if (nil? n)
(reduced acc)
(str acc ":" n)))
[1 1 2 3 5 8 nil 13 21])
;; Here is what is going on
(doc reduced)
;; Reducing is a mighty important concept in Clojure
;; since it is a ”functional first” language. Or as
;; it is worded in this Functional Design episode
;; https://clojuredesign.club/episode/058-reducing-it-down/
;; ”Reducing functions are a backbone of functional
;; programming, because we don’t have mutation.”
;; In fact in Clojure reducing is so important that
;; <NAME> has added a whole library with reducers
;; packing even more punch
;; https://clojure.org/reference/reducers
;; Again, the Functional Design duo, <NAME>, and
;; <NAME> have examined this library
;; a bit:
;; https://clojuredesign.club/episode/060-reduce-done-quick/
;; Amazing quote from that episode:
;; “The seq abstraction, it’s rather lazy.”
;; We are not going down the rabbit hole of the
;; `reducers` library, though...
)
;; ... Instead we are picking up that Nate and
;; <NAME> mention three super important concepts
;; in those two above quotes.
;; * immutability
;; * the `seq` abstraction
;; * laziness
;; They are related, and maybe it is best to start with
;; immutability...
(comment
;; = Immutability =
;; It is rather crazy that we have been talking about
;; Clojure for this long without discussing how
;; it encourages us to avoid mutating our data as
;; it is being processed. Clojurians never shut up
;; about immutability, right? We can almost sound
;; like Rothbardians in defining ourselves as
;; Enemies of the State 😄
;; https://www.youtube.com/watch?v=qe60zwUAOqE
;; This is to some extent true, as Clojurians we
;; often try to stay in a data transformation mode
;; for the duration of an operation and only deal
;; with the impure world, at the ”boundaries”. at
;; the start we might be reading some input, and
;; at the end we might be updating a database,
;; printing the results to a file (or to the
;; screen), or mutating the DOM of a web page.
;; Clojure encourages us to walk the immutable
;; path in many ways, two of which I am going
;; to mention a bit here:
;; * Persistent Data Structures
;; * Pure Functions
;; == Persistent Data Structures ==
;; Clojure helps us to stay in immutable land by
;; providing us with immutable data structures.
;; The implementation of these is called Persistent
;; Data Structure:
;; https://en.wikipedia.org/wiki/Persistent_data_structure
;; In effect it means that the data structures are
;; never changed, The functions we use to transform
;; them actually create copies. (In a very smart
;; way, so don't you start worrying now.)
;; Say we define a a vector of some digits
(def eighteen [1 0 0 1 0])
eighteen
;; Now we want to change that last `0` to a `1`
;; We can use the `assoc` function. When used on
;; a vector, takes an index and the new value
(def nineteen (assoc eighteen 4 1))
nineteen
;; Examining `eighteen` again ...
eighteen
;; ... we see that it is still true to its name.
;; Associng a `1` at index 4 of it created a
;; copy, which was then defined as `nineteen`
;; Perhaps obvious, this stands true in local
;; bindings as well.
(let [origin {:x 0
:y 0}
x-travel (assoc origin :x 100)]
[origin x-travel])
;; This provides for a very deterministic program
;; flow. Data does not willy-nilly change under our
;; feet. And, transformation processes that do not
;; mutate state are much easier to parallelize,
;; other threads can't change the data you are
;; transforming. A whole category of bugs never get
;; the chance to hatch!
;; Another benefit we get from immutability is
;; that Clojure can efficiently offer us value
;; equality. Values are immutable, by definition.
;; In Clojure, even the deepest data structures can
;; be compared in less than a jiffy.
;; Let's show this with a not so deep structure
;; (except in the name)
(def universa {:one {"<NAME>" {:x 100
:y 100
:z 100}
"<NAME>" {:x 100
:y 100
:z 100}}
:two {"<NAME>" {:x 100
:y 100
:z 100}
"<NAME>" {:x 100
:y 100
:z 99}}})
(= (:one universa)
(:two universa))
;; `update-in` is a higher order function for
;; transforming data structures given an
;; ”address” and a function. We can use it
;; to make two-Bob find two-Alice, just like
;; one-Bob and one-Alice have found each other
(def unified-universa
(update-in universa [:two "Bob" :z] inc))
unified-universa
(= (:one unified-universa)
(:two unified-universa))
(= universa unified-universa)
;; You'll never have to write an `equals()`
;; method again! 😄
;; Immutability also makes our programs different
;; than they are when you can change the value of
;; a variable at will. It can take a while to get
;; used to this. (I am still at the point where I
;; have an easier time to see mutating solutions
;; to many problems. It is less and less so, but
;; anyway. Probably you will grok it quicker than
;; I am doing.)
;; It is totally worth it to insist on getting it.
;; The payoff is huge. If you are only going to
;; check out one of the resources I am recommending
;; in this guide, I suggest it be this one about
;; solving problems the Clojure way, by <NAME>
;; <NAME>:
;; https://www.youtube.com/watch?v=vK1DazRK_a0
;; Spoiler: He is not using Clojure in the video
;; Of course, in the talk, <NAME> is not only
;; pretending data is immutable. He is also
;; employing function purity.
;; == Pure functions
;; Clojure doesn't force purity on you, like
;; some languages do (looking at you Haskell), but
;; it makes it easy to fall into the habit of
;; writing pure functions and thus push side effects
;; towards the ”edges” of your program.
;; A function is considered pure if it abides to
;; these rules:
;; 1. Always return the same value for the same input
;; 2. Does not effect anything in its environment.
;; So, not mutating anything, including not printing
;; anything anywhere, or hitting mutating API
;; endpoints.
;; A pure function is deterministic and you can
;; safely call it without worrying that it will update
;; application state or do anything else than
;; compute its return value based on the input you
;; hand it, and nothing but the input you hand it.
)
;; Before examining the `seq` abstraction, let's divert
;; a bit into some common Clojure core functions for
;; transforming data structures.
(comment
;; = Transforming Data Structures =
;; Clojure has a core library that makes it easy,
;; fun, and readable to ”reach in” to a data
;; data structure and manipulate it, creating a
;; copy with holding the result.
;; We have seen `assoc`, which creates a copy of
;; the data structure with a new value at the index
;; (in case of a `vector`) or key (in case of a map)
(def colt-express
{:name "Colt Express"
:categories ["Family"
"Strategy"]
:play-time 40
:ratings {:pez 5
:kat 5
:wiv 5
:vig 3
:rex 5
:lun 4}})
(def exit-haunted
{:name "EXIT: The Haunted Roller Coaster"
:categories ["Family"
"Co-op"
"Puzzle"
"Cards"]
:ratings {:pez 5
:kat 5
:wiv 5
:vig 4
:rex 5}})
;; `assoc` can add a new key to a map
(def colt-express-w-age
(assoc colt-express :age-from 10))
;; With a vector you can only add a new item right
;; behind the last item, not beyond
(def board-games-empty
[])
(def board-games-w-c-e
(assoc board-games-empty 0 colt-express))
;; board-games-empty is still empty. Thus
(def board-games-w-c-e-and-exit-fail
(assoc board-games-empty 1 exit-haunted))
(def board-games-w-c-e-and-exit
(assoc board-games-w-c-e 1 exit-haunted))
;; Not that it is very common to add things
;; to a vector using `assoc`. For this `conj`
;; often makes more sense
(conj board-games-empty colt-express exit-haunted)
;; `assoc` on maps can replace existing values
;; (in the copy)
(def colt-express-w-age-and-adjusted-playtime
(assoc colt-express-w-age :play-time 45))
;; `assoc` on vectors can do this too
(def board-games-w-adjusted-c-e
(assoc board-games-w-c-e
0
colt-express-w-age-and-adjusted-playtime))
;; You can `assoc` multiple things in one call
(assoc colt-express
:play-time 50
:age-from 10)
(assoc board-games-empty
0 colt-express
1 exit-haunted)
;; (Again, there is `conj` for this.)
;; With maps there is also `merge`, letting you
;; merge two or more maps together
(merge colt-express
{:play-time 45
:age-from 10})
;; NB: it is a ”shallow” merge, so adding a family
;; member rating like this won't work.
(merge exit-haunted
{:play-time 90
:ratings {:lun 5}
:age-from 10})
;; `assoc` does the same
(assoc exit-haunted :ratings {:lun 5})
;; There is no deep-merge in Clojure core, but
;; there is `assoc-in` for reaching in deeper
;; Instead of an key (or index) it takes a ”path”
(assoc-in exit-haunted [:ratings :lun] 5)
(assoc-in colt-express [:categories 2] "Planning")
;; (But... don't, see below under `update` for
;; how to `conj` the category instead.)
;; Unlike with `assoc`, you can only add one thing
;; at a time with `assoc-in`
;; Removing things from a map is done with
;; `dissoc`
(dissoc colt-express :play-time :ratings :categories)
;; You will probably use `dissoc` often with
;; the REPL (like you do in this file) to
;; examine some data structures that might
;; have some large data structures in them,
;; like a log or something
(dissoc colt-express :log)
;; (This data structure didn't have any log,
;; so it was left unchanged, but anyway.)
;; There is no `dissoc-in` in Clojure core, but
;; let's return to that after we have visited
;; `update` and `update-in`.
;; `update` and `update-in` are similar to
;; their `assoc` counterparts, but instead of a
;; value, they take a function which is used to
;; manipulate the value.
(update exit-haunted :name string/upper-case)
;; An exercise for you: Update the `:play-time`
;; of the `colt-express` entry with 5 or so
;; Arguments that you add after the function
;; get passed to the function
(update colt-express :categories conj "Planning")
;; Exercise: Make your update of the :play-time
;; take the `5` (or so) as an argument.
;; Exercise: Remove the `:pez` and `:wiv` entries
;; from the `:ratings` of `exit-haunted`
;; `update-in` is to `assoc-in` what `update` is
;; to `assoc`.
(update-in colt-express [:ratings :lun] inc)
(update-in colt-express [:ratings :lun] + 9000)
;; https://www.youtube.com/watch?v=PCHxU7witPA
;; Exercise: There is no `dissoc-in`, but it does
;; look like you can use `update-in` for this,
;; in'it?
;; The reward is one less visit to StackOverflow
;; for you when lacking `dissoc-in` 😄
;; https://stackoverflow.com/a/21942548/44639
;; We have been using keywords as map lookup
;; functions earlier. That's fine, but you might
;; sometimes prefer the `get` function
(get colt-express :ratings)
(= (:ratings colt-express)
(get colt-express :ratings))
;; `get` takes a third argument that will be used
;; as the default, should the entry be missing
(get exit-haunted :play-time 0)
;; keywords as lookup functions also supports
;; this
(:play-time exit-haunted 0)
;; Without the default, `nil` will be returned.
;; Which might blow up, depending on what you
;; use the value for
(* (get colt-express :play-time) 2)
(* (get exit-haunted :play-time) 2)
;; Better safe than sorry, in cases like this
(* (get colt-express :play-time 0) 2)
(* (get exit-haunted :play-time 0) 2)
;; Yes, there is `get-in` as well
;; Exercise: Use `get-in` to grab my rating
;; on these two wonderful family games
;; You might have noticed that all the
;; functions in this section take the collection
;; as their first argument. That makes them
;; easy to use with the Thread First, `->`,
;; macro. This is by design and highly idiomatic
;; Clojure.
;; It is common to see data transformation pipe-
;; lines like this
(-> exit-haunted
(assoc :play-time 90)
(update :categories conj "Scary")
(assoc-in [:ratings :lun] 5)
(update-in [:ratings :vig] + 1)
(dissoc :name)
(update :log vec)
(update :log conj "Name redacted")
(update :log conj "(Because scary)"))
;; (Although, perhaps more meaningful than that)
;; I can recommend ”See also”-browsing ClojureDocs
;; some starting here:
;; https://clojuredocs.org/clojure.core/update-in
;; And pasting a lot of examples here to
;; experiment with.
)
(comment
;; == Manipulating `sets` ==
;; Maps, vectors and sets are the bread and
;; butter for most Clojure programs. With the
;; amazing literal syntax for these the code gets
;; gets easy to read and reason about. And
;; manipulating them is easy and intuitive.
;; `sets` are `seqs` (more on that later)
)
;; To be continued...
;; Until there's more material to read here, maybe
;; it's time you check how to connect Calva to
;; your Clojure/ClojureScript projects:
;; https://calva.io/connect/
;; Things on the to-write-about list:
;; meta-data
;; comments
;; destructuring
;; atoms
;; nil, nil safety, nil punning
;; seqs
;; laziness
;; loop, recur
;; debugging
;; some wrapping up exercises here and there
;; Learn much more Clojure at https://clojure.org/
;; There is also ClojureScript, the same wonderful language,
;; for JavaScript VMs: https://clojurescript.org
;; There is so much about Clojure not mentioned in this
;; short guide. https://clojure.org/ is where you
;; go for the complete story.
;; To get help with your Clojure questions, check these
;; resources out:
;; https://ask.clojure.org/
;; https://clojurians.net
;; https://clojureverse.org
;; https://www.reddit.com/r/Clojure/
;; https://exercism.io/tracks/clojure
;; And there are also many other resources, such as:
;; https://clojuredocs.org
;; https://clojure.org/api/cheatsheet
"File loaded. Welcome to Clojure! ♥️"
;; This guide is downloaded from:
;; https://github.com/BetterThanTomorrow/dram
;; Please consider contributing.
| true |
(ns welcome-to-clojure
(:require [clojure.repl :refer [source apropos dir pst doc find-doc]]
[clojure.string :as string]
[clojure.test :refer [is are]]))
;; Welcome to Clojure! ♥️
;; Start with loading this file.
;; Ctrl+Alt+C Enter
;; Then evaluate this expression with Alt+Enter:
"Hello World"
;; That's a concise Hello World for any language.
;; And note that there are no parens. 😀
;; This guide will try to give you a basic
;; understanding of the Clojure language. Basic in
;; the sense that it is not extensive. Basic in the
;; sense that it is foundational, building from first
;; principles in order to make the Clojure journey
;; you have ahead easier to comprehend.
;; With the foundations in place you'll have a good
;; chance of having the right gut feeling for how to
;; code something, how to formulate your questions,
;; how to search effectively for information, how to make
;; sense of code you stumble across, and so on.
;; There will be links here and there, ctrl/cmd-click
;; those to open them in a browser. Here's the first
;; such link;
;; https://clojure.org/guides/learn/syntax
;; There you can read more about the concepts
;; mentioned in this guide.
;; The way to use the guide is to read about the
;; concepts and evaluate the examples. Sometimes there
;; will be exercises in the text. Don't limit your
;; exercising to those, though. Please feel encouraged
;; to edit the examples, and add new code
;; and evaluate that. Evaluate this to warm up:
(comment
(str "Welcome"
" to "
"Clojure!"
" "
"♥️"))
;; Then see what happens if you throw in some numbers
;; here and there and evaluate again.
;; NB: This is work in progress...
;; When you fire up the Getting Started REPL the next
;; time, you will be presented with the option to
;; download new files or continue with the files you
;; have. You can also always find the latest version here:
;; https://github.com/BetterThanTomorrow/dram/blob/dev/drams/welcome_to_clojure.clj
(comment
;; = EXPRESSIONS =
;; In Clojure everything is an expression.
;; (There are no statements.) Unless there is
;; an error when evaluating an expression, there
;; is always a return value (which is sometimes `nil`).
;; An important aspect of this is that the result
;; of an expression is always the last form/expression
;; evaluated. E.g. if you have a function defined
;; like so:
(defn last-eval-wins []
(println 'side-effect-1)
1
(println 'side-effect-2)
2)
;; This defines a function named
;; `last-eval-wins`, taking no arguments, with four
;; expressions in its function body. (We'll return to
;; defining functions later.)
;; Calling the function
(last-eval-wins) ; <- Evaluate that 😄
;; will cause all four expressions in the function
;; body to be evaluated. The result of the call will
;; be the last expression that was evaluated.
;; In the output window you will also see the
;; `println` calls happening. They are also
;; expressions, evaluating to `nil`.
(println 'prints-this-evaluates-to-nil)
;; Expressions are composed from literals (evaluating
;; to themselves) and/or calls to either:
;; * special forms
;; * macros
;; * functions
;; ”Hello World” at the beginning of this guide is a
;; literal string (thus, it evaluates to itself).
;; More about literals in the next section.
;; Calls are written as lists with the called thing
;; as the first element.
(def foo "foo") ; Calls the special form `def`,
; evaluates to the var it creates
; (More on this later)
(for [x '(1 2 3) ; Calls the macro `for`
y '(:a :b)] ; (List comprehension)
[x y])
(str 1 2 3) ; Calls the function `str` with the
; arguments 1, 2, and 3.
)
(comment
;; = LITERALS =
;; Literals evaluate to themselves.
;; (Remember your friends:
;; Alt+Enter and Ctrl+Enter)
;; Numeric types
18 ; integer
-1.8 ; floating point
0.18e2 ; exponent
18.0M ; big decimal
18/324 ; ratio
18N ; big integer
0x12 ; hex
022 ; octal
2r10010 ; base 2
;; Character types
"hello" ; string
\e ; character
#"[0-9]+" ; regular expression
;; Symbols and idents
map ; symbol
+ ; symbol - most punctuation allowed
clojure.core/+ ; namespaced symbol
nil ; null/nil value (named in the LISP tradition)
true false ; booleans
:alpha ; keyword
:release/alpha ; namespaced keyword
::alpha ; namespaced keyword,
; in current namespace
;; == KEYWORDS ==
;; Keywords are start with a `:`. They are a thing
;; in themselves, often used as identifiers and as
;; keys in maps (more on maps later). Keywords are
;; very memory and speed efficient.
;; The same keyword is of course equal to itself
(= :foo :foo)
;; It is, however, also identical to itself
(identical? :foo :foo)
;; This means it is the same thing, occupying the
;; same (very tiny) place in memory.
;; Even if you construct a non-literal keyword
;; it remains identical to it's literal form
(identical? (keyword "foo") :foo)
;; This holds true for your whole Clojure program.
;; Keywords are global. There is namespace syntax
;; for them, so that you can have control of this.
;; Keywords are also functions, actually. But more
;; on that later. For now let it suffice to say
;; that keywords have a very special and important
;; role in most Clojure programs.
;; == STRINGS ==
;; Somewhere in between the atomic literals and
;; the collections we have strings. They are sometimes
;; treated as sequences (a cool abstraction I'll
;; talk more about).
;; Strings are enclosed by double quotes.
"A string can be
multi-line, but will contain any leading spaces."
"Write strings
like this, if leading spaces are no-no."
;; (The single quote is used for something else.
;; You'll see for what a bit later.)
)
(comment
;; = NAMESPACES =
;; Important as namespaces are, we won't dwell on
;; the subject very much in this guide. The official
;; docs make them the best justice:
;; https://clojure.org/reference/namespaces
;;
;; There are some things we really need to know
;; though...
;; Clojure symbols are defined in namespaces (With
;; the `def `special form) where they are reachable
;; from any other namespace.
(def foo-2 "foo")
;; Also know that there is such a thing as the
;; current namespace. (A bit like the current working
;; directory in the shell.) When you evaluated the
;; `def` form above, you'll saw where `foo-2` got
;; defined.
;; When evaluating a symbol from any namespace it
;; must have been defined, or the compiler will
;; complain, and throw
foo-3
;; The namespace also needs to have been created
some-namespace/foo
;; If you have loaded the `hello_repl.clj` file
;; the `hello-repl` namespace is created and its
;; top level symbols are defined (not the ones
;; hidden in `(comment ...)` forms, because the
;; `comment` macro ignores the body and just
;; evaluates to/returns `nil`)
hello-repl/greet
(hello-repl/greet "from the welcome-to-clojure namespace")
;; If those throw, you need to first load
;; `hello_repl.clj`, or at least evaluate its `ns`
;; form and the `greet` form.
;; It is not to recommend that you rely on some
;; namespace existing like this though. That makes
;; your code brittle. It is better to `require`
;; the namespace. If you haven't loaded it, you
;; can do that in the same go:
(require 'hello-paredit :reload)
hello-paredit/strict-greet
(hello-paredit/strict-greet "World")
;; For most Clojure code you write you will arrange
;; it into separate files with one namespace each,
;; and use the `ns` form (that starts most Clojure
;; files) to `:require` the needed namespaces, aliasing
;; them to something convenient and sometimes `:refer`
;; in some of their symbols so that you can use
;; them without the namespace prefix (which is the
;; text before the `/`, btw, in case that wasn't
;; obvious enough). Examine the `ns` form of this
;; file to see why these forms compile without
;; complaints:
(doc require) ; Check the output window
(string/split "foo:bar:baz" #":")
;; See also:
;; https://clojuredocs.org/clojure.core/ns
;; Keywords can also be namespaced, but they are
;; not really registered in a namespace, like
;; symbols are, so you can just use them, regardless
:foo-whatever
:whatever-namespace/foo
;; The notion about the current namespace exists
;; for keywords in that the double-colon prefix
;; expands to `:<current-namespace>/foo`:
::foo
;; This is important to know about. `:foo` will
;; refer to the same keyword regardless of from which
;; namespace it is used. `::foo` will not.
)
(comment
;; = COLLECTIONS =
;; Clojure has literal syntax for four collection types
;; They evaluate to themselves.
'(1 2 3) ; list (a quoted list, more about this below)
[1 2 3] ; vector
#{1 2 3} ; set
{:a 1 :b 2} ; map
;; They compose
{:foo [1 2]
:bar #{1 2}}
;; In Clojure we do most things with just these
;; collections. Literal collections and functions.
)
(comment
;; = FUNCTIONS =
;; So far you have been able to evaluate all examples.
;; It's because we quoted that list.
;; Actually lists look like so
(1 2 3)
;; But if you evaluate that, you'll get an error:
;; => class java.lang.Long cannot be cast to class
;; clojure.lang.IFn
;; (Of course, the linter already warned you.)
;; This is because the Clojure will try to call
;; `1` as a function. When evaluating unquoted lists
;; the first element in the list is regarded as being
;; in ”function position”. A Clojure program is data.
;; In fancier words, Clojure is homoiconic:
;; https://wiki.c2.com/?HomoiconicLanguages
;; This gives great macro power, more about that below.
;; Here are some lists with proper functions at
;; position 1:
(str 1 2 3 4 5 :foo)
(< 1 2 3 4 5)
(*)
(= "1"
(str "1")
(str \1))
(println "From Clojure with ♥️")
(reverse [5 4 3 2 1])
;; Everything after the first position is
;; handed to the function as arguments
;; Note: I'll be referring to literals, symbols, and
;; literal collections collectively as forms,
;; sometimes, sexprs:
;; https://en.wikipedia.org/wiki/S-expression
;; You define new functions and bind them to names
;; in the current namespace using the macro `defn`.
;; It's a very flexible macro. Here's a simple use:
(defn add2
[arg]
(+ arg 2))
;; It defines the function `add2` taking one argument.
;; The function body calls the core functions `+`
;; with the arguments `arg` and 2.
;; Evaluating the form will define it and you'll see:
;; => #'hello-clojure/add2
;; That's a var ”holding” the value of the function
;; You can now reference the var using the symbol
;; `add2`. Putting it in the function position of a
;; list with 3 in the first argument position and
;; evaluating the list gives us back what?
(add2 3)
;; Clojure has an extensive core library of functions
;; and macros. See: https://clojuredocs.org for a
;; community-driven Clojure core (and more) search engine.
)
(comment
;; = SPECIAL FORMS =
;; The core library is composed from the functions and macros
;; in the library itself. Bootstrapping the library is
;; a few (15-ish) built-in primitive forms,
;; aka ”special forms”.
;; You have met one of these special forms already:
(quote (1 2 3))
;; The doc hover of the symbol `quote` tells you that
;; it is a special form.
;; Wondering where you met this special form before?
;; I used the shorthand syntax for it then:
'(1 2 3)
;; Convince yourself they are the same with the `=` function:
(= (quote (1 2 3))
'(1 2 3))
;; Clojure has value semantics. Any data structures
;; that evaluate to the same data are equal,
;; no matter how deep or big the structures are.
(= [1 [1 #{1 {:a 1 :b '(:foo bar)}}]]
[1 [1 #{1 {:a (- 3 2) :b (quote (:foo bar))}}]])
;; ... but that was a detour, back to special forms.
;; Official docs:
;; https://clojure.org/reference/special_forms#_other_special_forms
;; A very important special form is `fn` (which is
;; actually four special forms, but anyway).
;; Without this form we can't define new functions.
;; The following form evaluates to a function which
;; adds 2 to its argument.
(fn [arg] (+ arg 2))
;; Calling the function with the argument 3:
((fn [arg] (+ arg 2)) 3)
;; Another special form is `def`. It defines things,
;; giving them namespaced names.
(def foo :foo)
;; ”Defining a thing” means that a var is created,
;; holding the value, and that a symbol is bound
;; to the var. Evaluating the symbol picks up the
;; value from the var it is bound to.
foo
;; The var can be accessed using the `var` special
;; form.
(var foo)
;; You will most often see the var-quote shorthand
#'foo
;; With these two special forms we can define functions
(def add2-2 (fn [arg] (+ arg 2)))
(add2-2 3)
;; This is what the macro `defn` does. You will most
;; often be defining functions like what we saw
;; earlier, (when discussing the function position of
;; a form):
(defn add2-3
[arg]
(+ arg 2))
;; We can use the function `macroexpand` to see that
;; what the macro produces:
(macroexpand '(defn add2-3
[arg]
(+ arg 2)))
;; Yet another super duper important special form:
(if 'test
'value-if-true
'value-if-false)
;; Rumour has it that all conditional constructs (macros)
;; are built using `if`. Try to imagine a programming
;; language without conditionals!
;; We'll return to `if` and conditionals.
;; == `let` ==
;; `let` is a special form that lets you bind values to
;; variables that will be used in the body of the form.
(let [x 1
y 2]
(str x y))
;; The bindings are provided as the first ”argument”,
;; in a vector. This is a pattern that is used by
;; other special forms and macros that let you define
;; bindings. It is similar to the lexical scope of other
;; programming languages (even if this rather is
;; structural). Sibling and parent forms do not
;; ”see” these bindings (they have no way they could
;; possibly reach it). Here's an example:
(do
(def x :namespace-x)
(println "`x` in `do` _before_ `let`: " x)
(let [x :let-x]
(println "`x` from `let`: " x))
(println "`x` in `do`, _after_ `let`: " x))
(println "`x` _outside_ `do`: " x)
;; As noted before in this guide, the `def` special
;; form defines things ”globally”, though namespaced.
;; If you have followed the instructions to examine
;; things mentioned here, for instance by
;; ctrl/cmd-clicking the `let` symbol in the code
;; snippets, you'll find that in `core.clj`, `let`
;; is defined as a macro. Never mind that. It is
;; actually referred to as a special form here
;; https://clojure.org/reference/special_forms#let
;; Let's (pun unintended) wrap the special forms section
;; up with noting that together with _how_ Clojure
;; reads and evaluates code, the special forms make up
;; the Clojure language itself. The next level och
;; building blocks are macros.
;; But let us investigate this thing with how code
;; is read first...
)
(comment
;; = THE READER =
;; https://clojure.org/reference/reader
;; The Clojure Reader is responsible for reading text,
;; making data from it, which is what the compiler gets.
;; The Reader is where literals, symbols, strings, lists,
;; vectors, maps, and sets are picked apart and
;; re-assembled, figuring out what is a function,
;; a macro or special form.
;; In doing this whitespace plays a key role and there
;; are also some extra syntax rules are in play.
;; == WHITESPACE ==
;; Most things you would think counts as whitespace
;; is whitespace, and then there is also that Clojure,
;; being a LISP, does not need commas to separate
;; list items. However, commas can be used for this
;; anyway, since commas are whitespace.
(= '(1 2 3)
'(1,2,3)
'(1, 2, 3)
'(1,,,,2,,,,3))
;; (There are no operators in Clojure, `=` is a
;; function. It will check for equality of all
;; arguments it is passed.)
;; == LINE COMMENTS ==
;; The Reader skips reading everything on a line from
;; a semicolon. This is unstructured comments in
;; that if you start a form
(range 1 ; 10)
;; and then place a line comment so that the closing
;; bracket of that form gets commented out, the
;; structure breaks.
)
;; ^ Healing the structure.
;; If you remove the semicolon on the opening form
;; above, make sure to also remove this closing paren.
;; Since everything on the line is ignored, you can
;; add as many semicolons as you want.
;;;;;;;;;; (skipped by the Reader)
;; It's common to use two semicolons to start a full
;; line comment.
;; == EXTRA SYNTAX ===
;; We've already seen the single quote
'something
;; Which is, as we have seen, transformed to
(quote something)
;; `quote` is needed to stop the Reader from treating
;; things as something that should be evaluated.
;; See what happens if you evaluate `something`
;; without the quoting:
something
;; as well as the difference between evaluating these:
(1 2 3 4)
'(1 2 3 4)
;; There are some more quoting, and even splicing
;; symbols, which I won't cover in this guide.
;; === Deref ===
;; Clojure also has reference types, we'll discuss
;; (briefly) the most common one, `atom`, later.
(def an-atom (atom [1 2 3]))
(type an-atom)
;; To access value from a reference:
(deref an-atom)
(type (deref an-atom))
;; Again, `deref` is used for dereferencing a lot
;; different reference types, including futures,
;; https://clojure.org/reference/refs
;; https://clojure.org/about/concurrent_programming
;; Anyway, `deref` is so common that there is
;; shorthand syntax for it
@an-atom
(= (deref an-atom)
@an-atom)
;; It's a common mistake to forget to deref
(first an-atom)
(first @an-atom)
;; === THE DISPATCHER (HASH SIGN) ===
;; That hash sign shows up now and then. It has a
;; special role. It is aka Dispatch. Depending on
;; what character is following it, different cool
;; things happen. Here follows some common ones:
;; Regular expressions have literal syntax, they are
;; written like strings, but with a hash sign in front
#"reg(?:ular )?exp(?:ression)?"
;; Regexps are handled by the host platform, so they
;; are Java regexps in this tutorial. If you
;; evaluated the above regexp, we can test it.
(re-seq *1 "regexp regular expression")
;; `*1` is a special symbol for a variable holding
;; the value of the last evaluation result. It might
;; be easier to get a regexp right by using it
;; directly:
(re-seq #"fooo*" "fo foo fooo")
(re-find #"fooo*" "fo foo fooo")
;; If the hash sign is followed by a `(`, the Reader
;; will start expecting a function body.
#(+ % 2)
;; This is special syntax for ”function literals”, a
;; way to specify a function. The example above is
;; equivalent to this anonymous function.
(fn [arg] (+ arg 2))
;; Nesting function literals is forbidden activity
;(#(+ % (#(- % 2) 3)))
;; (thankfully)
;; In addition to sets, regexps and function literals
;; we have seen var-quotes earlier in this guide
#'add2
;; There was also a brief discussion about `vars`.
;; You might want to revisit it and also read more
;; about it, because it is a very important concept.
;; https://clojure.org/reference/vars
;; There is a very useful hash-dispatcher which
;; is used to make the Reader ignore the next form
#_(println "The reader will not send this function call
to the compiler") "This is not ignored"
;; To test this select the ignore marker together with
;; the function call and the string, then use Ctrl+Enter,
;; to make Calva send it all to the Reader, which will
;; read it, ignore the function call, and only evaluate
;; the string.
;; Since #_ ignores the next form it is a structural
;; comment mechanism, often used to temporarily disable
;; some code or some data
(str "a" "b" #_(str 1 2 3 [4 5 6]) "c")
;; Ignore markers stack
(str "a" #_#_"b" (str 1 2 3 [4 5 6]) "c")
;; Note that the Reader _will_ read the ignored form.
;; If there are syntactic errors in there, the
;; Reader will get sad, complain, and stop reading.
;; Select from the marker up to and including the string
;; here and press Ctrl+Enter
;#_(#(+ % (#(- % 2) 3))) "foo"
;; Two more common #-variants you will see, and use,
;; are namespaced map keyword shorthand syntax and
;; tagged literals, aka, data readers. Let's start
;; with the former:
(= #:foo {:bar 'bar
:baz 'baz}
{:foo/bar 'bar
:foo/baz 'baz})
;; Unrelated to the #: There is another shorthand for
;; specifying namespaced keywords. Double colon
;; keywords get namespaced with the current namespace
::foo
(= ::foo :welcome-to-clojure/foo)
;; Tagged literals, then. It's a way to invoke functions
;; bound to the tags on the form following it.
;; https://clojure.org/reference/reader#tagged_literals
;; They are also referred to as data readers. You can
;; define your own. Here let it suffice with mentioning
;; the two build in ones.
;; #inst will convert the string it tags to an instance.
;; (I.e. an instance in time, not an instance in the
;; Object Orientation sense of the word.)
#inst "2018-03-28T10:48:00.000"
(type *1)
;; #uuid will make an UUID of the string it tags
#uuid "0000000-0000-0000-0000-000000000016"
(java.util.UUID/fromString "0000000-0000-0000-0000-000000000016")
;; You now know how to read (in the sense of you
;; being a Clojure Reader) most Clojure code.
;; That said, let's skip going into the syntax
;; sugar and special forms for making host platform
;; interop extra nice.
;; https://clojure.org/reference/java_interop
;; Just a sneak peek:
(.before #inst "2018-03-28T10:48:00.000"
#inst "2021-02-17T00:27:00.000")
;; This invokes the method `before` on the date
;; object for year 2018 giving it the date from
;; year 2021 as argument. You'll see some little
;; more Java interop in this guide and probably
;; notice how available the host platform is when
;; coding Clojure. The same goes for
;; ClojureScript and for Clojure CLR.
;; Repeating this important resource on the Reader:
;; https://clojure.org/reference/reader
;; And in addition to that, read about All Those
;; Weird Characters here:
;; https://clojure.org/guides/weird_characters
)
(comment
;; = MACROS =
;; Clojure has powerful data transformation
;; capabilities. We'll touch on that a bit later.
;; Here I want to highlight that this power can
;; be wielded for extending the language itself.
;; Since Clojure code is structured and code is
;; data, Clojure can be used to produce Clojure
;; code from Clojure code. It is similar to the
;; preprocessor facilitates that some languages
;; offer, like C's `#pragma`, but it is much more
;; convenient and powerful. A lot of what you
;; will learn to love and recognize as Clojure
;; is actually created with Clojure, as macros.
;; This guide is mostly concerned with letting you
;; know that macros are a thing, to help you to
;; quickly realize when you are using a macro rather
;; than a function. I.e. I will not go into the
;; subject of how to create macros.
;; The distinction is important, because even if
;; macro calls look a lot like function calls,
;; macros are not first class. They can't be
;; passed as arguments, or returned as results.
;; More about ”first class” in the section about
;; functions, later.
;; == `when` ==
;; Let's just briefly examine the macro`when`.
;; This macro helps with writing more readable code.
;; How? Let's say you want to conditionally evaluate
;; something. Above you learnt that there is
;; a special form named `if` that can be used for
;; this. Like so:
(if 'this-is-true
'evaluate-this
'else-evaluate-this)
;; Now say you don't have something to evaluate
;; in the else case. `if` allows you to write this
(if 'this-is-true
'evaluate-this)
;; Which is fine, but you will have to scan the
;; code a bit extra to see that there is no else
;; branch. Easy with this short example, but can
;; get pretty hairy in real code. To address this,
;; you could write:
(if 'this-is-true
'evaluate-this
nil)
;; But that is a bit silly, what if there was a
;; way to tell the human reading the code that
;; there is no else branch? There is!
(when 'this-is-true
'evaluate-this)
;; Let's look at how `when` is defined, you can
;; ctrl/cmd-click `when` to navigate to where
;; it is defined in Clojure `core.clj`.
;; You can also use the function `macroexpand`
(macroexpand '(when 'this-is-true
'evaluate-this))
;; You'll notice that `when` wraps the body in
;; a `(do ...)`, which is a special form that lets
;; you evaluate several expressions, returning the
;; results of the last one.
;; https://clojuredocs.org/clojure.core/do
;; `do` is handy when you want to have some side-
;; effect going, in addition to evaluating something.
;; In development this often happens when you
;; want to `println` something before the result
;; of the expression is evaluated and returned.
(do (println "The quick brown fox jumps over the lazy dog")
(+ 2 2))
;; The `when` macro let's you take advantage of that
;; there is only one branch, so you can do this
(when 'this-is-true
(println "The quick brown fox jumps over the lazy dog")
(+ 2 2))
;; Without `when` you would write:
(if 'this-is-true
(do
(println "The quick brown fox jumps over the lazy dog")
(+ 2 2)))
;; Here `when` saves us both the extra scanning for
;; the else-branch and the use of `do`.
;; As far as macros go, `when` is about as simple as
;; they get. From two built-in special forms,
;; `if` and `do`, it composes a form that helps us
;; write easy to write and easy to read code.
;; == `for` ==
;; The `for` macro really demonstrates how Clojure
;; can be extended using Clojure. You might think
;; it provides looping like the for loop in many
;; other languages, but in Clojure there are no for
;; loops. Instead `for` is about list comprehensions
;; (if you have Python experience, yes, that kind of
;; list comprehensions). Here's how to produce the
;; cartesian product of two vectors, `x` and `y`:
(for [x [1 2 3]
y [1 2 3 4]]
[x y])
;; If you recall the `let` form above, and how it
;; lets you bind variables to use in the body of the
;; form, this is similar, only that `x` and `y` will
;; get bound to each value in the sequences and the
;; body will get evaluated for all combinations of
;; `x` and `y`.
;; All values? Well, `for` also lets you filter the
;; results
(for [x [1 2 3]
y [1 2 3 4]
:when (not= x y)]
[x y])
;; You can bind variable names in the comprehension
;; to store intermediate calculations and generally
;; make code more readable
(for [x [1 2 3]
y [1 2 3 4]
:let [d' (- x y)
d (Math/abs d')]]
d)
;; Is the same as:
(for [x [1 2 3]
y [1 2 3 4]]
(Math/abs (- x y)))
;; Debatable what is more readable in this particular
;; case... ¯\_(ツ)_/¯
;; A note about the variable name `d'` above:
;; `d'` is just a symbol name like any other. The
;; single-quote has no special meaning unless it is
;; the first character
;; Filters and bindings can be used together.
;; Use both `:let` and `:when` to make this
;; comprehension return a list of all `[x y]` where
;; their sum is odd. The functions `+` and `odd?`
;; are your friends here.
(for [x [1 2 3]
y [1 2 3 4]]
[x y])
;; (Yes, it can be solved without `:let` or `:when`.
;; Humour me. 😎)
;; See https://www.youtube.com/watch?v=5lvV9ICwaMo for
;; a great primer on Clojure list comprehensions
;; See https://clojuredocs.org/clojure.core/for for
;; example usages and tips.
;; Note that even though `let` and `for` look like
;; functions, they are not. The compiler would not
;; like it if you are passing undefined symbols to a
;; function. This is legal code:
(let [abc 1]
2)
;; This isn't.
(str [abc 1]
1)
;; (Notice that the clj-kondo linter is marking the
;; first with a warning, and the second as an error)
;; Macros extend the Clojure compiler.
;; https://clojure.org/reference/macros
;; == Threading macros ==
;; Macros can totally rearrange your code. The
;; built-in ”threading” macros do this. Sometimes
;; when the nesting of function(-ish) calls get
;; deep it can get a bit hard to read and to keep
;; track of all the parens
(Math/abs
(apply -
(:d (zipmap
[:a :b :c :d]
(partition 2 [1 1 2 3 5 8 13 21])))))
;; You read Clojure from the innermost expression
;; and out, which gets easier with time, but an
;; experienced Clojure coder would still find it
;; easier to read this
(->> [1 1 2 3 5 8 13 21]
(partition 2)
(zipmap [:a :b :c :d])
:d
(apply -)
(Math/abs))
;; Let's read this together. The thread-last macro,
;; `->>` is used, it takes its first argument and
;; places it (threads it) as the last argument to
;; following function. The first such step in
;; isolation:
(->> [1 1 2 3 5 8 13 21]
(partition 2))
;; The first argument/element passed to `->>` is
;; `[1 1 2 3 5 8 13 21]`
;; This is inserted as the last element of the
;; function call `(partition 2)`, yielding:
(partition 2 [1 1 2 3 5 8 13 21])
;; This partitions the list into lists of
;; 2 elements => `((1 1) (2 3) (5 8) (13 21))`
;; This new list is then inserted (threaded)
;; as the last argument to the next function,
;; yielding:
(zipmap [:a :b :c :d] '((1 1) (2 3) (5 8) (13 21)))
;; Which ”zips” together a Clojure map using
;; the first list as keys and the second list
;; as values
;; => `{:a (1 1), :b (2 3), :c (5 8), :d (13 21)}`
;; This map is then threaded as the last argument
;; to the function `:d`
(:d '{:a (1 1), :b (2 3), :c (5 8), :d (13 21)})
;; (In clojure keywords are functions that look
;; themselves up in the map handed to them.)
;; => `(13 21)`
;; You know the drill by now, this is threaded
(apply - '(13 21))
;; Which applies the `-` function over the list
;; => `-8`
;; Then this is threaded to `Math/abs`
(Math/abs -8)
;; 🎉
;; (In many Clojure capable editors, including
;; Calva, there are commands for ”unwinding”
;; a thread, and for converting a nested
;; expressions into a thread. Search for ”thread”
;; among the commands.)
;; https://github.com/clojure-emacs/clj-refactor.el/wiki/cljr-unwind-all
;; There is also a thread-first macro
;; `->` https://clojuredocs.org/clojure.core/-%3E
;; Sometimes you neither want to thread first
;; of last. There is a macro for this too.
;; `as->` lets you bind a variable name to the
;; threaded thing and place it wherever you
;; fancy in each function call.
(as-> 15 foo
(range 1 foo 3)
(interpose ":" foo))
;; https://clojuredocs.org/clojure.core/as-%3E
;; It's common to utilize the fact that most characters
;; are available when naming Clojure symbols. I often
;; use `$` for this threading macro:
(as-> 15 $
(range 1 $ 3)
(interpose ":" $))
;; Others use other names 😄
(as-> 15 <>
(range 1 <> 3)
(interpose ":" <>))
;; I think emojis should be avoided, the official
;; docs only mention alphanumerics plus:
;; `*`, `+`, `!`, `-`, `_`, `'`, `?`, `<`, `>`, and `=`
;; (so not even `$`) but here goes:
(as-> 15 ❤️
(range 1 ❤️ 3)
(interpose ":" ❤️))
;; Other core threading macros are:
;; `cond->`, `cond->>`, `some->`, and `some->>`
;; https://clojuredocs.org/clojure.core/cond-%3E
;; Please feel encouraged to copy the examples
;; from ClojureDocs here and play with them.
;; Here's one:
(cond-> 1 ; we start with 1
true inc ; the condition is true so (inc 1) => 2
false (* 42) ; the condition is false so the operation is skipped
(= 2 2) (* 3)) ; (= 2 2) is true so (* 2 3) => 6
;; See ”Threading with Style” by PI:NAME:<NAME>END_PI
;; for idiomatic use of the threading facilities.
;; https://stuartsierra.com/2018/07/06/threading-with-style
)
;; With special forms, the special syntax of the Reader,
;; and macros, the foundations of what is the Clojure
;; language you use are laid. You can of course extend
;; the language further with libraries including macros
;; or create your own. However the core language, with
;; its macros is very expressive. Taking data oriented
;; approaches is often enough. Even to prefer, rather
;; than creating more macros.
;; On to flow control!
(comment
;; = Flow Control, Conditionals, Branching =
;; Clojure is richer than most languages in what it
;; offers us to let our programs flow the way we want
;; them to. Almost all the core library features for
;; this are implemented using the primitive (special
;; form) `if`. This is still the staple for us as
;; Clojure coders. It takes three forms as its
;; arguments:
;; 1. A condition to evaluate
;; 2. What to evaluate if the condition evaluates
;; to something true (truthy)
;; 3. The form to evaluate if the condition does not
;; evaluate to something truthy (the ”else” branch)
;; Roll this dice, some ten-twenty times, checking if
;; it is a six:
(if (= 6 (inc (rand-int 6)))
"One time out of six you get a six"
"Five times out of six you get something else")
;; Since there are no statements in Clojure `if` is
;; the equivalent to the ternary `if` expression you
;; find in C and many other languages:
;; test ? true-expression : false-expression
;; Pseudo code for our dice:
;; int(rand() * 6) + 1 == 6 ?
;; "One time out of six you get a six" :
;; "Five times out of six you get something else";
;; == The Search for Truth ==
;; Again, in Clojure we use expressions evaluating to
;; values. When examined for branching all values
;; are either truthy or falsy. In fact, almost all
;; values are truthy
(if true :truthy :falsy)
(if :foo :truthy :falsy)
(if '() :truthy :falsy)
(if 0 :truthy :falsy)
(if "" :truthy :falsy)
;; The only falsy values are `false` and `nil`
(if false :truthy :falsy)
(if nil :truthy :falsy)
(when false :truthy)
;; About that last one: `when` evaluates to `nil`
;; when the condition is falsy. Since `nil` is
;; falsy the above `when` expression would be
;; making the ”else” branch of an `if` to be
;; evaluated
(if (when false :truthy) :true :falsy)
;; (Super extra bad code, but anyway)
;; When only boolean truth or falsehood can cut
;; it for you, there is the `true?` function
(true? true)
(true? 0)
(true? '())
(true? nil)
(true? false)
;; Thus
(if (true? 0) :true :false)
;; == `when` ==
;; As mentioned before, `when` is a one-branch
;; `if`, only for the truthy branch, which is
;; wrapped in a `do` for you. Try this and then
;; try it replacing the `when` with an `if`:
(when :truthy
(println "That sounds true to me")
:truthy-for-you)
;; If the `when` condition is not truthy,
;; `nil` will be returned.
(when nil :true-enough?)
;; == `cond` ==
;; Since deeply nested if/else structures can be
;; hard to write, read, and maintain, Clojure core
;; offers several more constructs for flow control,
;; one very common such is the `cond` macro. It
;; takes pairs of condition/result forms, tests
;; each condition, if it is true, then the result
;; form is evaluated and ”returned”, short-circuiting
;; so that no more condition is tested.
(let [dice-roll (inc (rand-int 6))]
(cond
(= 6 dice-roll) "Six is as high as it gets"
(odd? dice-roll) (str "An odd roll " dice-roll " is")
:else (str "Not six, nor odd, instead: " dice-roll)))
;; The `:else` is just the keyword `:else` which
;; evaluates to itself and is truthy. It is the
;; conventional way to give your cond forms a
;; default value. Without a default clause, the
;; form would evaluate to `nil` for anything not-six
;; not-odd. Try it by placing two ignore markers
;; (`#_ #_`) in front of the `:else` keyword.
;; Gotta love ClojureDocs
;; https://clojuredocs.org/clojure.core/cond
;; Paste examples from there here and play around:
;; See also links to `cond->` info above
;; == `case` ==
;; A bit similar to `switch/case` constructs in
;; other languages, Clojure core has the `case`
;; macro which takes a test expression, followed by
;; zero or more clauses (pairs) of test constant/expr,
;; followed by an optional expr. (However, the body
;; after the test expression may not be empty.)
(let [test-str "foo bar"]
(case test-str
"foo bar" (str "That's very " :foo-bar)
"baz" :baz
(count test-str)))
;; The trailing expression, if any, is ”returned” as
;; the default value.
(let [test-str "foo bar"]
(case test-str
#_#_"foo bar" (str "That's very " :foo-bar)
"baz" :baz
(count test-str)))
;; If no clause matches and there is no default,
;; a run time error happens
(let [test-str "foo bar"]
(case test-str
#_#_"foo bar" (str "That's very " :foo-bar)
"baz" :baz
#_(count test-str)))
;; WATCH OUT! A test constant must be a compile
;; time literal, and the compiler won't help you
;; find bugs like this:
(let [test-int 2
two 2]
(case test-int
1 :one
two (str "That's not a literal 2")
(str test-int ": Probably not expected")))
;; https://clojuredocs.org/clojure.core/case
;; Paste some `case` examples here and experiment
;; The Functional Design in Clojure podcast has a
;; fantastic episode about branching
;; https://clojuredesign.club/episode/089-branching-out/
;; == Less branching is good, right? ==
;; The core library is rich with functions that
;; helps you avoid writing branching code. Instead
;; you provide the condition as a predicate.
;; An often used predicate function is `filter`
(filter even? [0 1 2 3 4 5 6 7 8 9 10 11 12])
;; and its ”sibling” `remove`
(remove odd? [0 1 2 3 4 5 6 7 8 9 10 11 12])
;; Filtering sequences of values is a common task
;; and your programming time can instead be used
;; to decide _how_ it should be filtered, by writing
;; the predicate. Sometimes you don't even need to
;; do that, Clojure core is rich with predicates
(zero? 0)
(even? 0)
(neg? 0)
(pos? 0)
(nat-int? 0)
(empty? "")
(empty? [])
(empty? (take 0 [1 2 3]))
(integer? -2/1)
(indexed? [1 2 3])
(indexed? '(1 2 3))
;; What's a predicate? For the purpose of this guide
;; A predicate is a function testing things for
;; truthiness. It is convention that these functions
;; end with `?`. Many take only one argument.
;; A handy predicate is `some?` which tests for
;; "somethingness”, if it is not `nil` it is
;; something
(some? nil)
(some? false)
(some? '())
;; You can use it to test for if something is `nil`
;; by wrapping it in a call to the `not` function
(not (some? nil))
(not (some? false))
;; You get the urge to define a function named `nil?`,
;; right? You don't have to
(nil? nil)
(nil? false)
;; Clojure core also contains predicates that take
;; a predicate plus a collection to apply it on.
;; Such as `every?`
(every? nat-int? [0 1 2])
(every? nat-int? [-1 0 1 2])
;; Check the docs for `nat-int? and come up
;; with some more lists to test, like
(every? nat-int? [0 1 2N]) ; 2N is not fixed precision
(doc nat-int?)
;; This pattern with functions that take functions
;; as argument is common in Clojure. It spans beyond
;; predicates. Functions that take functions as
;; arguments are referred to as ”higher order
;; functions”.
;; https://en.wikipedia.org/wiki/Higher-order_function
)
(comment
;; = Functions =
;; Before diving into higher order functions, let's
;; look at functions.Functions are first class
;; Clojure citizens and the main building blocks for
;; solving your business problems.
;; We have seen a few ways you can create functions.
;; Here's an anonymous function that returns the
;; integer given to it, unless it is divisible by
;; 15, in which case it returns "fizz buzz".
;; (Not the full Fizz Buzz problem by any means.)
(fn [n]
(if (zero? (mod n 15))
"fizz buzz"
n))
;; Let's define it (bind it to a symbol we can use)
(def fizz-buzz-1 (fn [n]
(if (zero? (mod n 15))
"fizz buzz"
n)))
(fizz-buzz-1 2)
(fizz-buzz-1 15)
;; There's a macro that lets us define and create
;; the function in one call
(defn fizz-buzz-2 [n]
(if (zero? (mod n 15))
"fizz buzz"
n))
(fizz-buzz-2 4)
;; `defn` lets us provide documentation for the
;; function
(defn fizz-buzz-3
"Says 'fizz buzz' if `n` is divisible by 15,
otherwise says `n`"
[n]
(if (zero? (mod n 15))
"fizz buzz"
n))
(doc fizz-buzz-3) ; (or hover `fizz-buzz-3`)
;; It is easy to place the doc string wrong,
;; especially since it is common to write the `defn`
;; form like we did with `fizz-buzz-2` above.
(defn fizz-buzz-4
[n]
"Says 'fizz buzz' if `n` is divisible by 15,
otherwise says `n`"
(if (zero? (mod n 15))
"fizz buzz"
n))
;; This specifies a fully valid function body, so
;; Clojure won't complain about it. But:
(doc fizz-buzz-4)
;; clj-kondo's default configuration will help you
;; spot these errors. However, it can't help with
;; this:
(defn only-the-last-eval-returns [x]
[1 x]
[2 x])
(only-the-last-eval-returns "foo")
;; It is easy enough to spot like this and also to
;; wonder why you would ever write a function that
;; way. Yet you probably will do this mistake,
;; especially if you ever write some Hiccup, which
;; is a super nice way of writing HTML with Clojure
;; data structures. It's used by the popular Reagent
;; library
;; https://purelyfunctional.tv/guide/reagent/#hiccup
;; When you do the mistake and finish your hour-long
;; bug hunt, you will hear this guide whisper
;; ”Called it!”
;; The argument binding vector of `fn` (and
;; therefore `defn`) binds each argument in order
;; to a name.
(defn coords->str [x y]
(str "x: " x ", y: " y))
;; == Variadic Functions ==
;; You can define functions that take an arbitrary
;; number of arguments by placing a `&` in front
;; of the last argument name. That binds the name
;; to a sequence that contains all the remaining
;; arguments.
(defn lead+members [lead & members]
{:lead lead
:members members})
(lead+members "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI")
;; == Multi-arity ==
;; Clojure supports function signatures based on
;; the number of arguments. The `defn` macro lets
;; you define each arity as a separate list. This
;; is often used to provide default values
(defn hello
([] (hello "World"))
([s] (str "Hello " s "!")))
(hello)
(hello "Clojure Friend")
;; Or to create an ”identity” value for a function,
;; (A starting value that the rest of the operation
;; uses.) Say you want to add two x-y coordinates
(defn add-coords-1 [coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))})
(add-coords-1 {:x -2 :y 10}
{:x 4 :y 6})
;; What if the requirements were that if the
;; function is called with ne argument it should
;; add it to the origin? (See what I did there?
;; The identity value is where the function
;; should start, so start from the origin. 😎)
;; We can see that `add-coords-1` fails here
(add-coords-1 {:x -2 :y 10})
;; we need to add a one-arity
(defn add-coords-2
([coord]
(add-coords-2 {:x 0
:y 0}
coord))
([coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))}))
(add-coords-2 {:x -2 :y 10})
;; Now if called with no arguments it should
;; return the origin, because if you do not add
;; any coordinate you stay at the start.
;; Write a function `add-coords-3` that returns
;; the origin when called like this
(add-coords-3)
;; It should still handle to be called like this
(add-coords-3 {:x 3 :y 4})
(add-coords-3 {:x 2 :y 4}
{:x -4 :y -4})
;; It has to do with making the function compose
;; with other functions. E.g. the `apply` function
;; which is a higher order function that ”applies”
;; a function over a sequence. Right now we can
;; apply our `add-coords-2` function like this
(apply add-coords-2 [{:x 1 :y 1} {:x 4 :y 4}])
;; And like this
(apply add-coords-2 [{:x 1 :y 1}])
;; But not like this
(apply add-coords-2 [])
;; But the `add-coords-3` function you created can
(apply add-coords-3 [])
;; It will not handle an arbitrary long sequence
;; of coords, though. For that we would need one
;; more arity like so
(defn add-coords-4
;; add zero-arity from your `add-coords-3` here
;; add one-arity from your `add-coords-3` here
([coord-1 coord-2]
{:x (+ (:x coord-1)
(:x coord-2))
:y (+ (:y coord-1)
(:y coord-2))})
([coord-1 coord-2 & more-coords]
;; Implement this arity when you have learnt
;; about the higher order function `reduce`
))
(apply add-coords-4 [{:x 1 :y 1}
{:x 1 :y 1}
{:x 1 :y 1}
{:x -6 :y -6}])
;; Listen to Eric Normand explain in more detail
;; why the identity of a function is important:
;; https://lispcast.com/what-is-a-functions-identity/
;; == Closures ==
;; When you create functions on the fly, lambdas,
;; if you like, you use either the `fn` special
;; form directly, or by proxy with the `#()` syntax.
;; This creates a closure, like it does in JavaScript
;; and other languages. That is, these function can
;; access snapshots of variables with the values they
;; had when the function was created
(defn named-coords-factory [name]
(fn [x y] {:name name
:coords {:x x
:y y}}))
(def bob-coords-fn (named-coords-factory "PI:NAME:<NAME>END_PI"))
(def fred-coords-fn (named-coords-factory "PI:NAME:<NAME>END_PI"))
(bob-coords-fn 0 0)
(fred-coords-fn 5 5)
(bob-coords-fn 7 7)
;; Closures are handy to create low-arity functions
;; inside let binding boxes for the function body
;; to use:
(defn whisper-or-yell-or-ask [command sentence]
(let [whisper (fn []
(str (string/lower-case sentence) command))
yell (fn []
(str (string/upper-case sentence) command))
ask (fn []
(str sentence "?"))
default (fn []
(str sentence command " ¯\\_(ツ)_/¯"))]
(case command
"" (whisper)
"!" (yell)
"?" (ask)
(default))))
;; All functions created in the let binding box
;; ”close in” the `command` and the `sentence` so
;; the `case` can be kept terse and readable.
(whisper-or-yell-or-ask "" "How wOnDerFuLLY NIce To seE")
(whisper-or-yell-or-ask "!" "Hello tHERE")
(whisper-or-yell-or-ask "?" "How are you doing")
(whisper-or-yell-or-ask ":" "Oh well")
;; == The Attributes Map ==
;; The `defn` macro lets you add attributes to the
;; function in the form of a map. This gets added
;; as meta-data (some little more on that later)
;; to the var holding the function. The map goes
;; after the function name, and after any docs,
;; and before the arguments vector (or any arities)
(defn i-have-attributes
{:doc "Docs can be added like this too"
:foo "Any attributes you fancy"}
[]
"Good for you")
(doc i-have-attributes)
(meta #'i-have-attributes)
;; One handy attribute you can add is a test
;; function. Test runners will pick this up
(defn fizz-buzz-5
"That limited fizz-buzz function again"
{:test (fn []
(is (= "fizz-buzz" (fizz-buzz-5 15)))
(is (= 3 (fizz-buzz-5 3))))}
[n]
(if (pos? (rem 15 n))
"fizz-buzz"
n))
(clojure.test/test-var #'fizz-buzz-5)
;; Oops! You'll need to fix the bugs. 😀
;; How about implementing the complete Fizz Buzz?
;; https://en.wikipedia.org/wiki/Fizz_buzz
(defn fizz-buzz
"My Fizz Buzz solution"
{:test (fn []
(are [arg expected]
(= expected (fizz-buzz arg))
1 1
3 "Fizz"
4 4
5 "Buzz"
7 7
15 "Fizz Buzz"
20 "Buzz"))}
[n])
(clojure.test/test-var #'fizz-buzz)
(map fizz-buzz (range 1 40))
;; The meta-data that has special meaning to
;; the compiler and various Clojure core
;; facilities is listed here:
;; https://clojure.org/reference/special_forms
;; Now, on to higher order functions!
)
(comment
;; = Higher order functions =
;; A big contribution to what makes Clojure such a
;; powerful language is that functions are
;; ”first-class”
;; https://en.wikipedia.org/wiki/First-class_function
;; They can be values in collections (also keys
;; in maps) and can be passed as arguments to other
;; functions, and ”returned ”as results from
;; evaluations. You might be familiar with the
;; concept from languages like JavaScript.
;; Let's look at some higher order functions in
;; Clojure core. `some` calls the function on the
;; elements of its collection, one-by-one, and
;; returns the first truthy result, and will return
;; `nil` if the list is exhausted before some element
;; results in something truthy.
(some even? [1 1 2 3 5 8 13 21])
;; Not to be confused with `some?`, which is not
;; a higher order function.
(some some? [nil false])
(some some? [nil nil])
;; A common idiom in Clojure is to look for things
;; in collection using a `set` as the predicate.
;; Yes, sets are functions. Used as functions they
;; will look up the argument given to them in
;; themselves.
(#{"foo" "bar"} "bar")
;; Thus
(some #{"foo"} ["foo" "bar" "baz"])
(some #{"fubar"} ["foo" "bar" "baz"])
;; `apply` takes a function and a collection and
;; ”applies” the function on the collection. Say you
;; have a collection of numbers and want to add them.
;; This won't work:
(+ [1 1 2 3 5 8 13 21])
;; `apply` to the rescue
(apply + [1 1 2 3 5 8 13 21])
;; Concatenate the numbers as a string:
(apply str [1 1 2 3 5 8 13 21])
;; Contrast with
(str [1 1 2 3 5 8 13 21])
;; We've also seen `filter` and `remove` above, two
;; very commonly used higher order functions. They
;; play in the same league as `map`, and `reduce`.
;; Read on. 😎
)
(comment
;; = `map` and `reduce` =
;; Among the higher order functions you might have
;; used in other languages with first class
;; functions are `map` and `reduce`. They are worth
;; studying and practicing in much detail, here's
;; a super nice teaser:
;; https://purelyfunctional.tv/courses/3-functional-tools/
;; Let's also check them out briefly here.
;; `map` calls a function on the elements of one or
;; more collection from start to end and returns a
;; (lazy, more on that later) sequence of the results
;; in the same order. Let's say we want to decrement
;; each element in a list of numbers by one
(map dec '(1 1 2 3 5 8 13 21))
;; Let's say we then want to dec them again
(->> '(1 1 2 3 5 8 13 21)
(map dec)
(map dec))
;; Hmmm, better to subtract by two, maybe?
(map (fn [n] (- n 2)) '(1 1 2 3 5 8 13 21))
;; If you give `map` more collections to work on
;; it will repeatedly:
;; 1. pick the next item from each collection
;; 2. give them to the mapping function as arguments
;; 3. add the result to its return sequence
;; Until the shortest collection is exhausted
(map + [1 2 3] '(0 2 4 6 8))
(map (fn [n1 s n2] (str n1 ": " s "-" n2))
(range)
["foo" "bar" "baz"]
(range 2 -1 -1))
;; (We haven't talked much about `range`, it is a
;; function producing sequences of numbers. Given no
;; arguments it produces an infinite, watch out 😀,
;; sequence of integers
;; 0, 0+1, 0+2, 0+3, 0+4, 0+5, 0.6 ...
;; Good thing the other sequences got exhausted!)
;; A lot of the tasks you might solve with `for`
;; loops in other languages, are solved with `map`
;; in Clojure.
;; With other such ”for loopy” tasks you will
;; be wielding `reduce`. Unlike `map` it is not
;; limited to producing results of the same length
;; or shape as the input collection. Instead it
;; accumulates a result of any shape. For instance,
;; it can create a string from a collection of
;; numbers
(reduce (fn [acc n]
(str acc ":" n))
[1 1 2 3 5 8 13 21])
;; `reduce` will call the function with two
;; arguments: the result of the last function
;; call and the next number from the list. The
;; start of the process is special, since then
;; there are no results yet. `reduce` has two
;; ways to deal with this, two arities to be
;; specific. Called with two arguments, it
;; uses the two first elements from the list
;; for the first function call.
;; Here's reducing the `+` function using the
;; two-arity version of `reduce`
(reduce + [1 1 2 3 5 8 13 21])
;; The process then starts with calling `+`
;; like so
(+ 1 1)
;; Giving `reduce` three arguments makes it us
;; the second argument as the starting ”result”.
(reduce + 100 [1 1 2 3 5 8 13 21])
;; You might have noticed that the `+` function
;; takes more (and less) than 2 arguments.
(+)
(+ 1)
(+ 1 1)
(+ 1 1 2 3 5 8 13 21)
;; `+` will take the first argument, if any, and
;; add it to ”the current” value (which is zero),
;; then the next argument and add that to the new
;; current value, and so on, and so forth, until
;; there is a result. This process sounds a bit
;; like I just described a reduce, right?
;; In fact it is.
;; If we were to implement the `+` function, how
;; could we do it? We could start by implementing
;; something that adds two numbers together, then
;; use it as as the reducing function with
;; `reduce`.
;; Of course, now we have the task of adding two
;; numbers together, without using the existing
;; `+` function... 🤔
;; Hmmm... Let's keep it simple and only do
;; integer math. Then we can use the Java's
;; `Integer.sum(x, y)` method.
(Integer/sum 1 1)
;; Awesome, with this we can create an `add-two`
;; function
(defn add-two [x y]
(Integer/sum x y))
(add-two 1 1)
;; Unlike `+`, this one is not fully composable
;; with a higher order function like apply
(apply add-two [])
(apply add-two [1])
(apply add-two [1 1])
(apply add-two [1 1 2 3 5 8 13 21])
;; We need `add-many`. With `reduce` and our
;; `add-two` we can define `add-many` like so
(defn add-many [& numbers]
(reduce add-two numbers))
;; That does it, right?
(apply add-many [1])
(apply add-many [1 1])
(apply add-many [1 1 2 3 5 8 13 21])
;; What about the zero-arity version of `+`, you
;; ask? Correct, that will blow up
(add-many)
;; The built-in `+` function has a default ”current”
;; value of zero, remember? We can add that to
;; `add-many` in two ways: Either add a zero-arity
;; signature, or use the three-arity `reduce`. Let's
;; go for the latter option, since we are learning
;; about reduce here:
(defn add* [& numbers]
(reduce add-two 0 numbers))
(add*)
(add* 1)
(add* 1 1)
(add* 1 1 2 3)
;; BOOM.
;; We can use it with `apply` as well:
(apply add* [])
(apply add* [1])
(apply add* [1 1])
(apply add* [1 1 2 3 5 8 13 21])
;; Or `reduce`:
(reduce add* [])
(reduce add* [1])
(reduce add* [1 1])
(reduce add* [1 1 2 3 5 8 13 21])
;; Apart from that we only handle integers, our `add*`
;; is very much like how `+` is implemented in
;; Clojure core. Check it out (in the output window):
(source +)
;; Hmmm, well, they seem to be using multi-arity
;; function signatures for the low-arity cases, probably
;; because of the casting, but anyway, 😀
;; There's one more thing with `reduce` we want to
;; mention. When writing reducing functions you can
;; stop the process before the input sequence is
;; exhausted, using the `reduced` function. Say we
;; want the input sequence as a string separated by
;; `:`, as above, but stop when we see a `nil` item.
;; Here's the last version for comparison:
(reduce (fn [acc n]
(str acc ":" n))
[1 1 2 3 5 8 nil 13 21])
;; We can short circuit the process by calling
;; `reduced` with the accumulated value when we
;; encounter a `nil` item
(reduce (fn [acc n]
(if (nil? n)
(reduced acc)
(str acc ":" n)))
[1 1 2 3 5 8 nil 13 21])
;; Here is what is going on
(doc reduced)
;; Reducing is a mighty important concept in Clojure
;; since it is a ”functional first” language. Or as
;; it is worded in this Functional Design episode
;; https://clojuredesign.club/episode/058-reducing-it-down/
;; ”Reducing functions are a backbone of functional
;; programming, because we don’t have mutation.”
;; In fact in Clojure reducing is so important that
;; PI:NAME:<NAME>END_PI has added a whole library with reducers
;; packing even more punch
;; https://clojure.org/reference/reducers
;; Again, the Functional Design duo, PI:NAME:<NAME>END_PI, and
;; PI:NAME:<NAME>END_PI have examined this library
;; a bit:
;; https://clojuredesign.club/episode/060-reduce-done-quick/
;; Amazing quote from that episode:
;; “The seq abstraction, it’s rather lazy.”
;; We are not going down the rabbit hole of the
;; `reducers` library, though...
)
;; ... Instead we are picking up that Nate and
;; PI:NAME:<NAME>END_PI mention three super important concepts
;; in those two above quotes.
;; * immutability
;; * the `seq` abstraction
;; * laziness
;; They are related, and maybe it is best to start with
;; immutability...
(comment
;; = Immutability =
;; It is rather crazy that we have been talking about
;; Clojure for this long without discussing how
;; it encourages us to avoid mutating our data as
;; it is being processed. Clojurians never shut up
;; about immutability, right? We can almost sound
;; like Rothbardians in defining ourselves as
;; Enemies of the State 😄
;; https://www.youtube.com/watch?v=qe60zwUAOqE
;; This is to some extent true, as Clojurians we
;; often try to stay in a data transformation mode
;; for the duration of an operation and only deal
;; with the impure world, at the ”boundaries”. at
;; the start we might be reading some input, and
;; at the end we might be updating a database,
;; printing the results to a file (or to the
;; screen), or mutating the DOM of a web page.
;; Clojure encourages us to walk the immutable
;; path in many ways, two of which I am going
;; to mention a bit here:
;; * Persistent Data Structures
;; * Pure Functions
;; == Persistent Data Structures ==
;; Clojure helps us to stay in immutable land by
;; providing us with immutable data structures.
;; The implementation of these is called Persistent
;; Data Structure:
;; https://en.wikipedia.org/wiki/Persistent_data_structure
;; In effect it means that the data structures are
;; never changed, The functions we use to transform
;; them actually create copies. (In a very smart
;; way, so don't you start worrying now.)
;; Say we define a a vector of some digits
(def eighteen [1 0 0 1 0])
eighteen
;; Now we want to change that last `0` to a `1`
;; We can use the `assoc` function. When used on
;; a vector, takes an index and the new value
(def nineteen (assoc eighteen 4 1))
nineteen
;; Examining `eighteen` again ...
eighteen
;; ... we see that it is still true to its name.
;; Associng a `1` at index 4 of it created a
;; copy, which was then defined as `nineteen`
;; Perhaps obvious, this stands true in local
;; bindings as well.
(let [origin {:x 0
:y 0}
x-travel (assoc origin :x 100)]
[origin x-travel])
;; This provides for a very deterministic program
;; flow. Data does not willy-nilly change under our
;; feet. And, transformation processes that do not
;; mutate state are much easier to parallelize,
;; other threads can't change the data you are
;; transforming. A whole category of bugs never get
;; the chance to hatch!
;; Another benefit we get from immutability is
;; that Clojure can efficiently offer us value
;; equality. Values are immutable, by definition.
;; In Clojure, even the deepest data structures can
;; be compared in less than a jiffy.
;; Let's show this with a not so deep structure
;; (except in the name)
(def universa {:one {"PI:NAME:<NAME>END_PI" {:x 100
:y 100
:z 100}
"PI:NAME:<NAME>END_PI" {:x 100
:y 100
:z 100}}
:two {"PI:NAME:<NAME>END_PI" {:x 100
:y 100
:z 100}
"PI:NAME:<NAME>END_PI" {:x 100
:y 100
:z 99}}})
(= (:one universa)
(:two universa))
;; `update-in` is a higher order function for
;; transforming data structures given an
;; ”address” and a function. We can use it
;; to make two-Bob find two-Alice, just like
;; one-Bob and one-Alice have found each other
(def unified-universa
(update-in universa [:two "Bob" :z] inc))
unified-universa
(= (:one unified-universa)
(:two unified-universa))
(= universa unified-universa)
;; You'll never have to write an `equals()`
;; method again! 😄
;; Immutability also makes our programs different
;; than they are when you can change the value of
;; a variable at will. It can take a while to get
;; used to this. (I am still at the point where I
;; have an easier time to see mutating solutions
;; to many problems. It is less and less so, but
;; anyway. Probably you will grok it quicker than
;; I am doing.)
;; It is totally worth it to insist on getting it.
;; The payoff is huge. If you are only going to
;; check out one of the resources I am recommending
;; in this guide, I suggest it be this one about
;; solving problems the Clojure way, by PI:NAME:<NAME>END_PI
;; PI:NAME:<NAME>END_PI:
;; https://www.youtube.com/watch?v=vK1DazRK_a0
;; Spoiler: He is not using Clojure in the video
;; Of course, in the talk, PI:NAME:<NAME>END_PI is not only
;; pretending data is immutable. He is also
;; employing function purity.
;; == Pure functions
;; Clojure doesn't force purity on you, like
;; some languages do (looking at you Haskell), but
;; it makes it easy to fall into the habit of
;; writing pure functions and thus push side effects
;; towards the ”edges” of your program.
;; A function is considered pure if it abides to
;; these rules:
;; 1. Always return the same value for the same input
;; 2. Does not effect anything in its environment.
;; So, not mutating anything, including not printing
;; anything anywhere, or hitting mutating API
;; endpoints.
;; A pure function is deterministic and you can
;; safely call it without worrying that it will update
;; application state or do anything else than
;; compute its return value based on the input you
;; hand it, and nothing but the input you hand it.
)
;; Before examining the `seq` abstraction, let's divert
;; a bit into some common Clojure core functions for
;; transforming data structures.
(comment
;; = Transforming Data Structures =
;; Clojure has a core library that makes it easy,
;; fun, and readable to ”reach in” to a data
;; data structure and manipulate it, creating a
;; copy with holding the result.
;; We have seen `assoc`, which creates a copy of
;; the data structure with a new value at the index
;; (in case of a `vector`) or key (in case of a map)
(def colt-express
{:name "Colt Express"
:categories ["Family"
"Strategy"]
:play-time 40
:ratings {:pez 5
:kat 5
:wiv 5
:vig 3
:rex 5
:lun 4}})
(def exit-haunted
{:name "EXIT: The Haunted Roller Coaster"
:categories ["Family"
"Co-op"
"Puzzle"
"Cards"]
:ratings {:pez 5
:kat 5
:wiv 5
:vig 4
:rex 5}})
;; `assoc` can add a new key to a map
(def colt-express-w-age
(assoc colt-express :age-from 10))
;; With a vector you can only add a new item right
;; behind the last item, not beyond
(def board-games-empty
[])
(def board-games-w-c-e
(assoc board-games-empty 0 colt-express))
;; board-games-empty is still empty. Thus
(def board-games-w-c-e-and-exit-fail
(assoc board-games-empty 1 exit-haunted))
(def board-games-w-c-e-and-exit
(assoc board-games-w-c-e 1 exit-haunted))
;; Not that it is very common to add things
;; to a vector using `assoc`. For this `conj`
;; often makes more sense
(conj board-games-empty colt-express exit-haunted)
;; `assoc` on maps can replace existing values
;; (in the copy)
(def colt-express-w-age-and-adjusted-playtime
(assoc colt-express-w-age :play-time 45))
;; `assoc` on vectors can do this too
(def board-games-w-adjusted-c-e
(assoc board-games-w-c-e
0
colt-express-w-age-and-adjusted-playtime))
;; You can `assoc` multiple things in one call
(assoc colt-express
:play-time 50
:age-from 10)
(assoc board-games-empty
0 colt-express
1 exit-haunted)
;; (Again, there is `conj` for this.)
;; With maps there is also `merge`, letting you
;; merge two or more maps together
(merge colt-express
{:play-time 45
:age-from 10})
;; NB: it is a ”shallow” merge, so adding a family
;; member rating like this won't work.
(merge exit-haunted
{:play-time 90
:ratings {:lun 5}
:age-from 10})
;; `assoc` does the same
(assoc exit-haunted :ratings {:lun 5})
;; There is no deep-merge in Clojure core, but
;; there is `assoc-in` for reaching in deeper
;; Instead of an key (or index) it takes a ”path”
(assoc-in exit-haunted [:ratings :lun] 5)
(assoc-in colt-express [:categories 2] "Planning")
;; (But... don't, see below under `update` for
;; how to `conj` the category instead.)
;; Unlike with `assoc`, you can only add one thing
;; at a time with `assoc-in`
;; Removing things from a map is done with
;; `dissoc`
(dissoc colt-express :play-time :ratings :categories)
;; You will probably use `dissoc` often with
;; the REPL (like you do in this file) to
;; examine some data structures that might
;; have some large data structures in them,
;; like a log or something
(dissoc colt-express :log)
;; (This data structure didn't have any log,
;; so it was left unchanged, but anyway.)
;; There is no `dissoc-in` in Clojure core, but
;; let's return to that after we have visited
;; `update` and `update-in`.
;; `update` and `update-in` are similar to
;; their `assoc` counterparts, but instead of a
;; value, they take a function which is used to
;; manipulate the value.
(update exit-haunted :name string/upper-case)
;; An exercise for you: Update the `:play-time`
;; of the `colt-express` entry with 5 or so
;; Arguments that you add after the function
;; get passed to the function
(update colt-express :categories conj "Planning")
;; Exercise: Make your update of the :play-time
;; take the `5` (or so) as an argument.
;; Exercise: Remove the `:pez` and `:wiv` entries
;; from the `:ratings` of `exit-haunted`
;; `update-in` is to `assoc-in` what `update` is
;; to `assoc`.
(update-in colt-express [:ratings :lun] inc)
(update-in colt-express [:ratings :lun] + 9000)
;; https://www.youtube.com/watch?v=PCHxU7witPA
;; Exercise: There is no `dissoc-in`, but it does
;; look like you can use `update-in` for this,
;; in'it?
;; The reward is one less visit to StackOverflow
;; for you when lacking `dissoc-in` 😄
;; https://stackoverflow.com/a/21942548/44639
;; We have been using keywords as map lookup
;; functions earlier. That's fine, but you might
;; sometimes prefer the `get` function
(get colt-express :ratings)
(= (:ratings colt-express)
(get colt-express :ratings))
;; `get` takes a third argument that will be used
;; as the default, should the entry be missing
(get exit-haunted :play-time 0)
;; keywords as lookup functions also supports
;; this
(:play-time exit-haunted 0)
;; Without the default, `nil` will be returned.
;; Which might blow up, depending on what you
;; use the value for
(* (get colt-express :play-time) 2)
(* (get exit-haunted :play-time) 2)
;; Better safe than sorry, in cases like this
(* (get colt-express :play-time 0) 2)
(* (get exit-haunted :play-time 0) 2)
;; Yes, there is `get-in` as well
;; Exercise: Use `get-in` to grab my rating
;; on these two wonderful family games
;; You might have noticed that all the
;; functions in this section take the collection
;; as their first argument. That makes them
;; easy to use with the Thread First, `->`,
;; macro. This is by design and highly idiomatic
;; Clojure.
;; It is common to see data transformation pipe-
;; lines like this
(-> exit-haunted
(assoc :play-time 90)
(update :categories conj "Scary")
(assoc-in [:ratings :lun] 5)
(update-in [:ratings :vig] + 1)
(dissoc :name)
(update :log vec)
(update :log conj "Name redacted")
(update :log conj "(Because scary)"))
;; (Although, perhaps more meaningful than that)
;; I can recommend ”See also”-browsing ClojureDocs
;; some starting here:
;; https://clojuredocs.org/clojure.core/update-in
;; And pasting a lot of examples here to
;; experiment with.
)
(comment
;; == Manipulating `sets` ==
;; Maps, vectors and sets are the bread and
;; butter for most Clojure programs. With the
;; amazing literal syntax for these the code gets
;; gets easy to read and reason about. And
;; manipulating them is easy and intuitive.
;; `sets` are `seqs` (more on that later)
)
;; To be continued...
;; Until there's more material to read here, maybe
;; it's time you check how to connect Calva to
;; your Clojure/ClojureScript projects:
;; https://calva.io/connect/
;; Things on the to-write-about list:
;; meta-data
;; comments
;; destructuring
;; atoms
;; nil, nil safety, nil punning
;; seqs
;; laziness
;; loop, recur
;; debugging
;; some wrapping up exercises here and there
;; Learn much more Clojure at https://clojure.org/
;; There is also ClojureScript, the same wonderful language,
;; for JavaScript VMs: https://clojurescript.org
;; There is so much about Clojure not mentioned in this
;; short guide. https://clojure.org/ is where you
;; go for the complete story.
;; To get help with your Clojure questions, check these
;; resources out:
;; https://ask.clojure.org/
;; https://clojurians.net
;; https://clojureverse.org
;; https://www.reddit.com/r/Clojure/
;; https://exercism.io/tracks/clojure
;; And there are also many other resources, such as:
;; https://clojuredocs.org
;; https://clojure.org/api/cheatsheet
"File loaded. Welcome to Clojure! ♥️"
;; This guide is downloaded from:
;; https://github.com/BetterThanTomorrow/dram
;; Please consider contributing.
|
[
{
"context": ";; Copyright (c) 2014-2016 Andrey Antukh <[email protected]>\n;; Copyright (c) 2014-2016 Alejand",
"end": 40,
"score": 0.9998933672904968,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2014-2016 Andrey Antukh <[email protected]>\n;; Copyright (c) 2014-2016 Alejandro Gómez <alej",
"end": 54,
"score": 0.9999276399612427,
"start": 42,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "y Antukh <[email protected]>\n;; Copyright (c) 2014-2016 Alejandro Gómez <[email protected]>\n;; All rights reserved.\n;",
"end": 98,
"score": 0.9998899102210999,
"start": 83,
"tag": "NAME",
"value": "Alejandro Gómez"
},
{
"context": "i.nz>\n;; Copyright (c) 2014-2016 Alejandro Gómez <[email protected]>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 121,
"score": 0.9999329447746277,
"start": 100,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/cats/monad/exception.cljc
|
klausharbo/cats
| 5 |
;; Copyright (c) 2014-2016 Andrey Antukh <[email protected]>
;; Copyright (c) 2014-2016 Alejandro Gómez <[email protected]>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns cats.monad.exception
"The Exception monad.
Also known as Try monad, popularized by Scala.
It represents a computation that may either result
in an exception or return a successfully computed
value. Is very similar to Either monad, but is
semantically different.
It consists in two types: Success and Failure. The
Success type is a simple wrapper like Right of Either
monad. But the Failure type is slightly different
from Left, because it is forced to wrap an instance
of Throwable (or Error in cljs).
The most common use case of this monad is for wrap
third party libraries that uses standard Exception
based error handling. In normal circumstances you
should use Either instead.
The types defined for Exception monad (Success and
Failure) also implementes the clojure IDeref interface
which facilitates libraries developing using monadic
composition without forcing a user of that library
to use or understand monads.
That is because when you will dereference the
failure instance, it will reraise the containing
exception."
(:require [cats.protocols :as p]
[cats.util :as util]
#?(:clj [cats.context :as ctx]
:cljs [cats.context :as ctx :include-macros true]))
#?(:cljs
(:require-macros [cats.monad.exception :refer (try-on)])))
;; --- Helpers
(defn throw-exception
[^String message]
(throw (#?(:clj IllegalArgumentException.
:cljs js/Error.)
message)))
(defn throwable?
"Return true if `v` is an instance of
the Throwable or js/Error type."
[e]
(instance? #?(:clj Exception :cljs js/Error) e))
;; --- Types and implementations.
(declare context)
(defrecord Success [success]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] success)
p/Printable
(-repr [_]
(str "#<Success " (pr-str success) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] success)]
:clj [clojure.lang.IDeref
(deref [_] success)]))
(defrecord Failure [failure]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] failure)
p/Printable
(-repr [_]
(str "#<Failure " (pr-str failure) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] (throw failure))]
:clj [clojure.lang.IDeref
(deref [_] (throw failure))]))
(alter-meta! #'->Success assoc :private true)
(alter-meta! #'->Failure assoc :private true)
(util/make-printable Success)
(util/make-printable Failure)
(defn success
"A Success type constructor.
It wraps any arbitrary value into
success type."
[v]
(Success. v))
(defn failure
"A failure type constructor.
If a provided parameter is an exception, it wraps
it in a `Failure` instance and return it. But if
a provided parameter is arbitrary data, it tries
create an exception from it using clojure `ex-info`
function.
Take care that `ex-info` function in clojurescript
differs a little bit from clojure."
([e] (failure e ""))
([e message]
(if (throwable? e)
(Failure. e)
(Failure. (ex-info message e)))))
(defn success?
"Return true if `v` is an instance of
the Success type."
[v]
(instance? Success v))
(defn failure?
"Return true if `v` is an instance of
the Failure type."
[v]
(instance? Failure v))
(defn exception?
"Return true in case of `v` is instance
of Exception monad."
[v]
(cond
(or (instance? Failure v)
(instance? Success v))
true
(satisfies? p/Contextual v)
(identical? (p/-get-context v) context)
:else false))
(defn extract
"Return inner value from exception monad.
This is a specialized version of `cats.core/extract`
for Exception monad types that allows set up
the default value.
If a provided `mv` is an instance of Failure type
it will re raise the inner exception. If you need
extract value without raising it, use `cats.core/extract`
function for it."
([mv]
{:pre [(exception? mv)]}
(if (success? mv)
(p/-extract mv)
(throw (p/-extract mv))))
([mv default]
{:pre [(exception? mv)]}
(if (success? mv)
(p/-extract mv)
default)))
(defn ^{:no-doc true}
exec-try-on
[func]
(try
(let [result (func)]
(cond
(throwable? result) (failure result)
(exception? result) result
:else (success result)))
(catch #?(:clj Exception
:cljs js/Error) e (failure e))))
(defn ^{:no-doc true}
exec-try-or-else
[func defaultvalue]
(let [result (exec-try-on func)]
(if (failure? result)
(success defaultvalue)
result)))
(defn ^{:no-doc true}
exec-try-or-recover
[func recoverfn]
(let [result (exec-try-on func)]
(ctx/with-context context
(if (failure? result)
(recoverfn (.-failure ^Failure result))
result))))
#?(:clj
(defmacro try-on
"Wraps a computation and return success of failure."
[expr]
`(let [func# (fn [] ~expr)]
(exec-try-on func#))))
#?(:clj
(defmacro try-or-else
[expr defaultvalue]
`(let [func# (fn [] ~expr)]
(exec-try-or-else func# ~defaultvalue))))
#?(:clj
(defmacro try-or-recover
[expr func]
`(let [func# (fn [] ~expr)]
(exec-try-or-recover func# ~func))))
(defn wrap
"Wrap a function in a try monad.
Is a high order function that accept a function
as parameter and returns an other that returns
success or failure depending of result of the
first function."
[func]
(let [metadata (meta func)]
(-> (fn [& args] (try-on (apply func args)))
(with-meta metadata))))
;; --- Monad definition
(def ^{:no-doc true}
context
(reify
p/Context
p/Functor
(-fmap [_ f s]
(if (success? s)
(try-on (f (p/-extract s)))
s))
p/Applicative
(-pure [_ v]
(success v))
(-fapply [m af av]
(if (success? af)
(p/-fmap m (p/-extract af) av)
af))
p/Monad
(-mreturn [_ v]
(success v))
(-mbind [_ s f]
(assert (exception? s) (str "Context mismatch: " (p/-repr s)
" is not allowed to use with exception context."))
(if (success? s)
(f (p/-extract s))
s))
p/Printable
(-repr [_]
"#<Exception>")))
(util/make-printable (type context))
|
27835
|
;; Copyright (c) 2014-2016 <NAME> <<EMAIL>>
;; Copyright (c) 2014-2016 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns cats.monad.exception
"The Exception monad.
Also known as Try monad, popularized by Scala.
It represents a computation that may either result
in an exception or return a successfully computed
value. Is very similar to Either monad, but is
semantically different.
It consists in two types: Success and Failure. The
Success type is a simple wrapper like Right of Either
monad. But the Failure type is slightly different
from Left, because it is forced to wrap an instance
of Throwable (or Error in cljs).
The most common use case of this monad is for wrap
third party libraries that uses standard Exception
based error handling. In normal circumstances you
should use Either instead.
The types defined for Exception monad (Success and
Failure) also implementes the clojure IDeref interface
which facilitates libraries developing using monadic
composition without forcing a user of that library
to use or understand monads.
That is because when you will dereference the
failure instance, it will reraise the containing
exception."
(:require [cats.protocols :as p]
[cats.util :as util]
#?(:clj [cats.context :as ctx]
:cljs [cats.context :as ctx :include-macros true]))
#?(:cljs
(:require-macros [cats.monad.exception :refer (try-on)])))
;; --- Helpers
(defn throw-exception
[^String message]
(throw (#?(:clj IllegalArgumentException.
:cljs js/Error.)
message)))
(defn throwable?
"Return true if `v` is an instance of
the Throwable or js/Error type."
[e]
(instance? #?(:clj Exception :cljs js/Error) e))
;; --- Types and implementations.
(declare context)
(defrecord Success [success]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] success)
p/Printable
(-repr [_]
(str "#<Success " (pr-str success) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] success)]
:clj [clojure.lang.IDeref
(deref [_] success)]))
(defrecord Failure [failure]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] failure)
p/Printable
(-repr [_]
(str "#<Failure " (pr-str failure) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] (throw failure))]
:clj [clojure.lang.IDeref
(deref [_] (throw failure))]))
(alter-meta! #'->Success assoc :private true)
(alter-meta! #'->Failure assoc :private true)
(util/make-printable Success)
(util/make-printable Failure)
(defn success
"A Success type constructor.
It wraps any arbitrary value into
success type."
[v]
(Success. v))
(defn failure
"A failure type constructor.
If a provided parameter is an exception, it wraps
it in a `Failure` instance and return it. But if
a provided parameter is arbitrary data, it tries
create an exception from it using clojure `ex-info`
function.
Take care that `ex-info` function in clojurescript
differs a little bit from clojure."
([e] (failure e ""))
([e message]
(if (throwable? e)
(Failure. e)
(Failure. (ex-info message e)))))
(defn success?
"Return true if `v` is an instance of
the Success type."
[v]
(instance? Success v))
(defn failure?
"Return true if `v` is an instance of
the Failure type."
[v]
(instance? Failure v))
(defn exception?
"Return true in case of `v` is instance
of Exception monad."
[v]
(cond
(or (instance? Failure v)
(instance? Success v))
true
(satisfies? p/Contextual v)
(identical? (p/-get-context v) context)
:else false))
(defn extract
"Return inner value from exception monad.
This is a specialized version of `cats.core/extract`
for Exception monad types that allows set up
the default value.
If a provided `mv` is an instance of Failure type
it will re raise the inner exception. If you need
extract value without raising it, use `cats.core/extract`
function for it."
([mv]
{:pre [(exception? mv)]}
(if (success? mv)
(p/-extract mv)
(throw (p/-extract mv))))
([mv default]
{:pre [(exception? mv)]}
(if (success? mv)
(p/-extract mv)
default)))
(defn ^{:no-doc true}
exec-try-on
[func]
(try
(let [result (func)]
(cond
(throwable? result) (failure result)
(exception? result) result
:else (success result)))
(catch #?(:clj Exception
:cljs js/Error) e (failure e))))
(defn ^{:no-doc true}
exec-try-or-else
[func defaultvalue]
(let [result (exec-try-on func)]
(if (failure? result)
(success defaultvalue)
result)))
(defn ^{:no-doc true}
exec-try-or-recover
[func recoverfn]
(let [result (exec-try-on func)]
(ctx/with-context context
(if (failure? result)
(recoverfn (.-failure ^Failure result))
result))))
#?(:clj
(defmacro try-on
"Wraps a computation and return success of failure."
[expr]
`(let [func# (fn [] ~expr)]
(exec-try-on func#))))
#?(:clj
(defmacro try-or-else
[expr defaultvalue]
`(let [func# (fn [] ~expr)]
(exec-try-or-else func# ~defaultvalue))))
#?(:clj
(defmacro try-or-recover
[expr func]
`(let [func# (fn [] ~expr)]
(exec-try-or-recover func# ~func))))
(defn wrap
"Wrap a function in a try monad.
Is a high order function that accept a function
as parameter and returns an other that returns
success or failure depending of result of the
first function."
[func]
(let [metadata (meta func)]
(-> (fn [& args] (try-on (apply func args)))
(with-meta metadata))))
;; --- Monad definition
(def ^{:no-doc true}
context
(reify
p/Context
p/Functor
(-fmap [_ f s]
(if (success? s)
(try-on (f (p/-extract s)))
s))
p/Applicative
(-pure [_ v]
(success v))
(-fapply [m af av]
(if (success? af)
(p/-fmap m (p/-extract af) av)
af))
p/Monad
(-mreturn [_ v]
(success v))
(-mbind [_ s f]
(assert (exception? s) (str "Context mismatch: " (p/-repr s)
" is not allowed to use with exception context."))
(if (success? s)
(f (p/-extract s))
s))
p/Printable
(-repr [_]
"#<Exception>")))
(util/make-printable (type context))
| true |
;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns cats.monad.exception
"The Exception monad.
Also known as Try monad, popularized by Scala.
It represents a computation that may either result
in an exception or return a successfully computed
value. Is very similar to Either monad, but is
semantically different.
It consists in two types: Success and Failure. The
Success type is a simple wrapper like Right of Either
monad. But the Failure type is slightly different
from Left, because it is forced to wrap an instance
of Throwable (or Error in cljs).
The most common use case of this monad is for wrap
third party libraries that uses standard Exception
based error handling. In normal circumstances you
should use Either instead.
The types defined for Exception monad (Success and
Failure) also implementes the clojure IDeref interface
which facilitates libraries developing using monadic
composition without forcing a user of that library
to use or understand monads.
That is because when you will dereference the
failure instance, it will reraise the containing
exception."
(:require [cats.protocols :as p]
[cats.util :as util]
#?(:clj [cats.context :as ctx]
:cljs [cats.context :as ctx :include-macros true]))
#?(:cljs
(:require-macros [cats.monad.exception :refer (try-on)])))
;; --- Helpers
(defn throw-exception
[^String message]
(throw (#?(:clj IllegalArgumentException.
:cljs js/Error.)
message)))
(defn throwable?
"Return true if `v` is an instance of
the Throwable or js/Error type."
[e]
(instance? #?(:clj Exception :cljs js/Error) e))
;; --- Types and implementations.
(declare context)
(defrecord Success [success]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] success)
p/Printable
(-repr [_]
(str "#<Success " (pr-str success) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] success)]
:clj [clojure.lang.IDeref
(deref [_] success)]))
(defrecord Failure [failure]
p/Contextual
(-get-context [_] context)
p/Extract
(-extract [_] failure)
p/Printable
(-repr [_]
(str "#<Failure " (pr-str failure) ">"))
#?@(:cljs [cljs.core/IDeref
(-deref [_] (throw failure))]
:clj [clojure.lang.IDeref
(deref [_] (throw failure))]))
(alter-meta! #'->Success assoc :private true)
(alter-meta! #'->Failure assoc :private true)
(util/make-printable Success)
(util/make-printable Failure)
(defn success
"A Success type constructor.
It wraps any arbitrary value into
success type."
[v]
(Success. v))
(defn failure
"A failure type constructor.
If a provided parameter is an exception, it wraps
it in a `Failure` instance and return it. But if
a provided parameter is arbitrary data, it tries
create an exception from it using clojure `ex-info`
function.
Take care that `ex-info` function in clojurescript
differs a little bit from clojure."
([e] (failure e ""))
([e message]
(if (throwable? e)
(Failure. e)
(Failure. (ex-info message e)))))
(defn success?
"Return true if `v` is an instance of
the Success type."
[v]
(instance? Success v))
(defn failure?
"Return true if `v` is an instance of
the Failure type."
[v]
(instance? Failure v))
(defn exception?
"Return true in case of `v` is instance
of Exception monad."
[v]
(cond
(or (instance? Failure v)
(instance? Success v))
true
(satisfies? p/Contextual v)
(identical? (p/-get-context v) context)
:else false))
(defn extract
"Return inner value from exception monad.
This is a specialized version of `cats.core/extract`
for Exception monad types that allows set up
the default value.
If a provided `mv` is an instance of Failure type
it will re raise the inner exception. If you need
extract value without raising it, use `cats.core/extract`
function for it."
([mv]
{:pre [(exception? mv)]}
(if (success? mv)
(p/-extract mv)
(throw (p/-extract mv))))
([mv default]
{:pre [(exception? mv)]}
(if (success? mv)
(p/-extract mv)
default)))
(defn ^{:no-doc true}
exec-try-on
[func]
(try
(let [result (func)]
(cond
(throwable? result) (failure result)
(exception? result) result
:else (success result)))
(catch #?(:clj Exception
:cljs js/Error) e (failure e))))
(defn ^{:no-doc true}
exec-try-or-else
[func defaultvalue]
(let [result (exec-try-on func)]
(if (failure? result)
(success defaultvalue)
result)))
(defn ^{:no-doc true}
exec-try-or-recover
[func recoverfn]
(let [result (exec-try-on func)]
(ctx/with-context context
(if (failure? result)
(recoverfn (.-failure ^Failure result))
result))))
#?(:clj
(defmacro try-on
"Wraps a computation and return success of failure."
[expr]
`(let [func# (fn [] ~expr)]
(exec-try-on func#))))
#?(:clj
(defmacro try-or-else
[expr defaultvalue]
`(let [func# (fn [] ~expr)]
(exec-try-or-else func# ~defaultvalue))))
#?(:clj
(defmacro try-or-recover
[expr func]
`(let [func# (fn [] ~expr)]
(exec-try-or-recover func# ~func))))
(defn wrap
"Wrap a function in a try monad.
Is a high order function that accept a function
as parameter and returns an other that returns
success or failure depending of result of the
first function."
[func]
(let [metadata (meta func)]
(-> (fn [& args] (try-on (apply func args)))
(with-meta metadata))))
;; --- Monad definition
(def ^{:no-doc true}
context
(reify
p/Context
p/Functor
(-fmap [_ f s]
(if (success? s)
(try-on (f (p/-extract s)))
s))
p/Applicative
(-pure [_ v]
(success v))
(-fapply [m af av]
(if (success? af)
(p/-fmap m (p/-extract af) av)
af))
p/Monad
(-mreturn [_ v]
(success v))
(-mbind [_ s f]
(assert (exception? s) (str "Context mismatch: " (p/-repr s)
" is not allowed to use with exception context."))
(if (success? s)
(f (p/-extract s))
s))
p/Printable
(-repr [_]
"#<Exception>")))
(util/make-printable (type context))
|
[
{
"context": " username (:username es-config)\n password (:password es-config)\n client (delay (s/client {:hosts ",
"end": 456,
"score": 0.5670373439788818,
"start": 448,
"tag": "PASSWORD",
"value": "password"
}
] |
src/log_service/es.clj
|
chargegrid/log-service
| 0 |
(ns log-service.es
(:require [log-service.settings :refer [config]]
[org.httpkit.client :as http]
[clojure.string :refer [join]]
[clojure.tools.logging :as log]
[clojure.data.json :as json]
[qbits.spandex :as s]
[qbits.spandex.utils :as s-utils]))
(let [es-config (:elasticsearch config)
hosts (:hosts es-config)
username (:username es-config)
password (:password es-config)
client (delay (s/client {:hosts hosts
:http-client {:basic-auth {:user username :password password}}}))
index-name "ocpp-logs"
type-name "ocpp-logs"
;TODO: Create-automatically for new tenant
space-x-tenant "5pVvHNXhpi0h06lcKqwGxi"
tesla-tenant "kOKcPQlWrFBVYLCV5DCPF"
mappings {type-name {:properties {:charge-box-serial {:type "keyword"}
:ocpp-message {:type "text"}
:timestamp {:type "date"}
:direction {:type "keyword"}
:response-to {:type "keyword"}
:wamp-type {:type "keyword"}
:wamp-msg-id {:type "keyword"}
:wamp-action {:type "keyword"}
:wamp-payload {:type "object"}
:tenant-id {:type "keyword"}}}}
aliases {space-x-tenant {:filter {:term {:tenant-id space-x-tenant}}
:routing space-x-tenant}
tesla-tenant {:filter {:term {:tenant-id tesla-tenant}}
:routing tesla-tenant}}]
(defn- index-exists? []
(let [url (s-utils/url [index-name])
res (s/request @client {:url url
:method :HEAD})]
(= (:status res) 200)))
(defn- index-create! []
(log/info "Creating index" index-name)
(let [url (s-utils/url [index-name])
payload {:mappings mappings
:aliases aliases}
res (s/request @client {:url url
:method :PUT
:body payload})]
(when (not (= (:status res) 200))
; TODO: Send to Sentry
(throw (Exception. (str "Cannot create ES index " res))))))
(defn setup! []
(if (index-exists?)
(log/info "Index exists")
(index-create!)))
(defn index-ocpp-msg! [doc]
(let [tenant-id (:tenant-id doc)
url (s-utils/url [tenant-id type-name])
res (s/request @client {:url url
:method :POST
:body doc})]
(when (not (= (:status res) 201))
; TODO: Send to Sentry
(throw (Exception. (str "Cannot index the doc " res))))))
(defn search-ocpp-log [client-query tenant-id]
(let [url (s-utils/url [tenant-id type-name "_search"])
res (s/request @client {:url url
:method :GET
:body client-query})]
(log/info "Searching OCPP logs on url " url " with query " client-query)
{:data (:body res)
:ok? (= (:status res) 200)})))
|
38170
|
(ns log-service.es
(:require [log-service.settings :refer [config]]
[org.httpkit.client :as http]
[clojure.string :refer [join]]
[clojure.tools.logging :as log]
[clojure.data.json :as json]
[qbits.spandex :as s]
[qbits.spandex.utils :as s-utils]))
(let [es-config (:elasticsearch config)
hosts (:hosts es-config)
username (:username es-config)
password (:<PASSWORD> es-config)
client (delay (s/client {:hosts hosts
:http-client {:basic-auth {:user username :password password}}}))
index-name "ocpp-logs"
type-name "ocpp-logs"
;TODO: Create-automatically for new tenant
space-x-tenant "5pVvHNXhpi0h06lcKqwGxi"
tesla-tenant "kOKcPQlWrFBVYLCV5DCPF"
mappings {type-name {:properties {:charge-box-serial {:type "keyword"}
:ocpp-message {:type "text"}
:timestamp {:type "date"}
:direction {:type "keyword"}
:response-to {:type "keyword"}
:wamp-type {:type "keyword"}
:wamp-msg-id {:type "keyword"}
:wamp-action {:type "keyword"}
:wamp-payload {:type "object"}
:tenant-id {:type "keyword"}}}}
aliases {space-x-tenant {:filter {:term {:tenant-id space-x-tenant}}
:routing space-x-tenant}
tesla-tenant {:filter {:term {:tenant-id tesla-tenant}}
:routing tesla-tenant}}]
(defn- index-exists? []
(let [url (s-utils/url [index-name])
res (s/request @client {:url url
:method :HEAD})]
(= (:status res) 200)))
(defn- index-create! []
(log/info "Creating index" index-name)
(let [url (s-utils/url [index-name])
payload {:mappings mappings
:aliases aliases}
res (s/request @client {:url url
:method :PUT
:body payload})]
(when (not (= (:status res) 200))
; TODO: Send to Sentry
(throw (Exception. (str "Cannot create ES index " res))))))
(defn setup! []
(if (index-exists?)
(log/info "Index exists")
(index-create!)))
(defn index-ocpp-msg! [doc]
(let [tenant-id (:tenant-id doc)
url (s-utils/url [tenant-id type-name])
res (s/request @client {:url url
:method :POST
:body doc})]
(when (not (= (:status res) 201))
; TODO: Send to Sentry
(throw (Exception. (str "Cannot index the doc " res))))))
(defn search-ocpp-log [client-query tenant-id]
(let [url (s-utils/url [tenant-id type-name "_search"])
res (s/request @client {:url url
:method :GET
:body client-query})]
(log/info "Searching OCPP logs on url " url " with query " client-query)
{:data (:body res)
:ok? (= (:status res) 200)})))
| true |
(ns log-service.es
(:require [log-service.settings :refer [config]]
[org.httpkit.client :as http]
[clojure.string :refer [join]]
[clojure.tools.logging :as log]
[clojure.data.json :as json]
[qbits.spandex :as s]
[qbits.spandex.utils :as s-utils]))
(let [es-config (:elasticsearch config)
hosts (:hosts es-config)
username (:username es-config)
password (:PI:PASSWORD:<PASSWORD>END_PI es-config)
client (delay (s/client {:hosts hosts
:http-client {:basic-auth {:user username :password password}}}))
index-name "ocpp-logs"
type-name "ocpp-logs"
;TODO: Create-automatically for new tenant
space-x-tenant "5pVvHNXhpi0h06lcKqwGxi"
tesla-tenant "kOKcPQlWrFBVYLCV5DCPF"
mappings {type-name {:properties {:charge-box-serial {:type "keyword"}
:ocpp-message {:type "text"}
:timestamp {:type "date"}
:direction {:type "keyword"}
:response-to {:type "keyword"}
:wamp-type {:type "keyword"}
:wamp-msg-id {:type "keyword"}
:wamp-action {:type "keyword"}
:wamp-payload {:type "object"}
:tenant-id {:type "keyword"}}}}
aliases {space-x-tenant {:filter {:term {:tenant-id space-x-tenant}}
:routing space-x-tenant}
tesla-tenant {:filter {:term {:tenant-id tesla-tenant}}
:routing tesla-tenant}}]
(defn- index-exists? []
(let [url (s-utils/url [index-name])
res (s/request @client {:url url
:method :HEAD})]
(= (:status res) 200)))
(defn- index-create! []
(log/info "Creating index" index-name)
(let [url (s-utils/url [index-name])
payload {:mappings mappings
:aliases aliases}
res (s/request @client {:url url
:method :PUT
:body payload})]
(when (not (= (:status res) 200))
; TODO: Send to Sentry
(throw (Exception. (str "Cannot create ES index " res))))))
(defn setup! []
(if (index-exists?)
(log/info "Index exists")
(index-create!)))
(defn index-ocpp-msg! [doc]
(let [tenant-id (:tenant-id doc)
url (s-utils/url [tenant-id type-name])
res (s/request @client {:url url
:method :POST
:body doc})]
(when (not (= (:status res) 201))
; TODO: Send to Sentry
(throw (Exception. (str "Cannot index the doc " res))))))
(defn search-ocpp-log [client-query tenant-id]
(let [url (s-utils/url [tenant-id type-name "_search"])
res (s/request @client {:url url
:method :GET
:body client-query})]
(log/info "Searching OCPP logs on url " url " with query " client-query)
{:data (:body res)
:ok? (= (:status res) 200)})))
|
[
{
"context": "n an agenda token is placed.\n; Example: Hayley Kaplan will not show a prompt if there are no valid targ",
"end": 8375,
"score": 0.8818985819816589,
"start": 8362,
"tag": "NAME",
"value": "Hayley Kaplan"
}
] |
src/clj/game/core/engine.clj
|
darmac/netrunner
| 1 |
(ns game.core.engine
(:require
[clojure.set :as clj-set]
[clojure.stacktrace :refer [print-stack-trace]]
[clojure.string :as string]
[clj-uuid :as uuid]
[game.core.board :refer [clear-empty-remotes]]
[game.core.card :refer [active? facedown? get-card get-cid has-subtype? installed? rezzed?]]
[game.core.card-defs :refer [card-def]]
[game.core.effects :refer [any-effects effect-pred get-effect-maps unregister-floating-effects]]
[game.core.eid :refer [complete-with-result effect-completed make-eid]]
[game.core.payment :refer [build-spend-msg can-pay? merge-costs handler]]
[game.core.prompt-state :refer [add-to-prompt-queue]]
[game.core.prompts :refer [clear-wait-prompt show-prompt show-select show-wait-prompt]]
[game.core.say :refer [system-msg]]
[game.core.update :refer [update!]]
[game.core.winning :refer [check-win-by-agenda]]
[game.macros :refer [continue-ability req wait-for]]
[game.utils :refer [dissoc-in distinct-by in-coll? server-cards remove-once same-card? side-str to-keyword]]
[jinteki.utils :refer [other-side]]))
;; resolve-ability docs
; Perhaps the most important function in the game logic.
; Resolves an ability defined by the given ability map. Checks :req functions; shows prompts, psi games,
; traces, etc. as needed; charges costs; invokes :effect functions. All card effects and most engine effects
; should run through this method. Unless noted, every key listed is optional.
; How to read this:
; :key -- type
; Description, reasoning, expected return value, etc.
; Types:
; integer, string, keyword: clojure literals
; boolean: clojure literal, but should generally only be true (as leaving it off counts as false)
; vector: can be a literal [] or '(), can also be the return value of a function, but
; must not be a function definition that returns a vector or list
; map of X: clojure literal. X is a comma-separated list of allowed keys.
; The description will be laid out recursively, and keys will be marked as required or optional.
; ability map: an ability map as defined here.
; enum: a comma-separated list of values, one of which can be used.
; 5-fn: typically (req), but any function definition that takes state, side, eid, card, targets.
; Something that accepts different types will have the types separated by "or".
; For example, "string or 5-fn" means it accepts a string or a 5-fn. The description will
; say what the 5-fn should return, if anything.
; COMMON KEYS
; :req -- 5-fn
; Must return true or false. If false, the ability will not be resolved.
; :cost -- vector
; A vector of cost pairs to charge, for example [:credit 1 :click 1].
; If the costs cannot be paid, the ability will not be resolved.
; :msg -- string or 5-fn.
; Must return a string. (`msg` is expressly built for this.)
; Prints to the log when the ability is finished. Will be used as the :label if no :label is provided.
; The output is written as:
; (with cost) "{Player} pays {X} to use {card title} to {msg result}."
; (with no cost) "{Player} uses {card title} to {msg result}."
; so the returned string should always be written imperatively.
; :label -- string
; If this ability is in an :abilities map on a card, the label will be prepended with a string
; of the costs, and both will be displayed in the ability button. If this is not defined
; and a label is needed, :msg will be used if it is a string.
; :effect -- 5-fn
; Will be called if the ability will be resolved (if :req is true or not present,
; costs can be paid, and any prompts are resolved).
; :player -- enum: :corp, :runner
; Manually specifies which player the ability should affect, rather than leave it implicit.
; :async -- boolean
; Mark the ability as "async", meaning the :effect function must call effect-completed itself.
; Without this being set to true, resolve-ability will call effect-completed once it's done.
; This part of the engine is really dumb and complicated, so ask someone on slack about it.
; :cost-req -- 1-fn
; A function which will be applied to the cost of an ability immediatly prior to being paid. See all-stealth or min-stealth for examples.
; PROMPT KEYS
; :prompt -- string or 5-fn
; Must return a string to display in the prompt menu.
; :choices -- 5-fn or :credit or :counter or map
; This key signals a prompt of some kind. (It should be split into multiple keys, but that's a lot of work lol)
; * 5-fn
; Must return a vector of card objects or strings.
; User chooses one. This is called a 'choice' prompt.
; * :credit
; User chooses an integer up to their current credit amount.
; * :counter
; User chooses an integer up to the :counter value of the current card.
; * map of :number, :default
; User chooses an integer between 0 and some number
; :number -- 5-fn
; Required. Must return a number, which is the maximum allowed.
; :default -- 5-fn
; Optional. Must return a number, which is the number the dropdown will display initially.
; * map of :card or :req, :all, :max, :not-self
; Triggers a 'select' prompt with targeting cursor for "selecting" one or more cards.
; :card -- 1-argument function
; Either this or :req is required, but not both.
; Accepts a single card object, must return true or false to indicate if selection is successful.
; :req -- 5-fn
; Either this or :card is required, but not both.
; "target" is the clicked card. Must return true or false to indicate if selection is successful.
; :all -- boolean
; Optional. Changes the select prompt from optional (can click "Done" to not select anything) to
; mandatory. When :max is also set to true, enforces selecting the specified number of cards.
; :max -- integer
; Optional. Changes the select from to resolving after selecting a single card to
; resolving when either a number of cards (as set by :max) have been selected or a number
; of cards less than that set by :max are selected and the "Done" button has been clicked.
; When :all is also set to true, enforces selecting the specified number of cards.
; :not-self -- boolean
; Certain abilities can target any card on the table, others can only target other cards.
; For example, Yusuf vs Aesop's. Setting this is the same as adding
; `(not (same-card? % card))` to your :card function or `(not (same-card? target card))`
; to your :req function.
; :not-distinct -- boolean
; By default, duplicate entries of the same string will be combined into a single button.
; If set to true, duplicate entries of the same string will be shown as multiple buttons.
; :cancel-effect -- 5-fn
; If a prompt with the choice "Cancel" is clicked, the prompt exits without doing anything else
; and this function will be called.
; SIMULTANEOUS EFFECT RESOLUTION KEYS
; :interactive -- 5-fn. when simultaneous effect resolution has been enabled for a specific event, the user receives
; a menu of cards that handle the effect and get to choose the order of their resolution. This menu is
; only shown if at least one ability handling the event has an :interactive function that returns true.
; If none are interactive, then all handlers will be resolved automatically, one at a time in an
; arbitrary order. In general, handlers should be marked ':interactive (req true)' if they have
; important order-of-effect interactions with other cards. The :interactive function can be coded to
; have smarter logic if necessary -- see Replicator, which is only interactive if there is another
; copy of the installed card remaining in the Stack.
; :silent -- any handler that does not require user interaction under any circumstances can be marked :silent. If a
; handler's :silent function returns true, then no menu entry will be shown for the handler. In that case,
; the ability will only be resolved once all non-silent abilities are resolved. Example: AstroScript has no
; important interactions with other 'agenda scored' effects, and doesn't care when an agenda token is placed.
; Example: Hayley Kaplan will not show a prompt if there are no valid targets in the grip.
; OTHER KEYS
; :once -- either :per-turn or :per-run. signifies an effect that can only be triggered once per turn.
; :once-key -- keyword. by default, each :once is distinct per card. If multiple copies of a card can only resolve
; some ability once between all of them, then the card should specify a manual :once-key that can
; be any value, preferrably a unique keyword.
; :install-req -- a function which returns a list of servers a card may be installed into
; :makes-run -- boolean. indicates if the ability makes a run.
; COMPLEX ABILITY WRAPPERS
; These are wrappers around more complex/cumbersome functionality. They all call into a flow that would
; be cumbersome to write out every time in a "normal" ability map.
; :psi -- map of :req, :equal, :not-equal
; Handles psi games.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :equal -- ability map
; At least one of :equal and :not-equal are required.
; Async ability that is executed if the players reveal the same number of credits.
; :not-equal -- ability map
; At least one of :equal and :not-equal are required.
; Async ability that is executed if the players reveal the a differen number of credits.
; :trace -- map of :req, :label, :base, :successful, :unsuccessful, :kicker, :kicker-min
; Handles traces.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :label -- 5-fn
; Optional. Works same as :label in an ability map.
; :base -- integer or 5-fn
; Required. Must return an integer, which sets the "base" initial value for the trace.
; :successful -- ability map
; At least one of :successful and :unsuccessful are required.
; Async ability that is executed if the trace is successful.
; :unsuccessful -- ability map
; At least one of :successful and :unsuccessful are required.
; Async ability that is executed if the trace is unsuccessful.
; :kicker -- ability map
; Optional. Async ability that is executed if the corp's trace strength is equal to or greater
; than :kicker-min.
; :kicker-min -- integer
; Required if :kicker is defined. The number the corp's strength must be equal to or greater
; to execute the :kicker ability.
; :optional -- map of :req, :prompt, :player, :yes-ability, :no-ability, :end-effect, :autoresolve
; Shows a "Yes/No" prompt to handle the user deciding whether to resolve the ability.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :prompt -- string or 5-fn
; Required. Must return a string to display in the prompt menu.
; :player -- enum: :corp, :runner
; Optional. Hardcodes which player will resolve this prompt.
; :yes-ability -- ability-map
; At least one of :yes-ability and :no-ability are required. (Normally, this should always
; be defined, but sometimes it's easier to word things in the negative, such that only
; defining :no-ability is the most natural way to write the ability.)
; Async ability that is executed if "Yes" is chosen.
; :no-ability -- ability-map
; At least one of :yes-ability and :no-ability are required. (See note above.)
; Async ability that is executed if "No" is chosen, or if "Yes" is chosen but there's
; no :yes-ability defined, or :yes-ability has a :cost that the player can't afford.
; :end-effect -- 5-fn
; Called after :yes- or :no-ability has been resolved.
; Must not be async as it is not awaited.
; :autoresolve -- 5-fn
; Optional. Used to set an optional prompt to either ask, always choose "Yes", or always choose "No".
; Must use the (get-autoresolve kw) helper function, where kw is an ability-specific
; keyword that will be stored in the card's [:special] map.
; Must use the (set-autoresolve kw) helper function in the card's :abilities vector,
; to allow for changing the autoresolve settings, where kw is the same keyword as used in
; the (get-autoresolve kw) call.
(declare do-ability resolve-ability-eid check-ability pay prompt! check-choices do-choices)
(def ability-types (atom {}))
(defn register-ability-type
[kw ability-fn]
(swap! ability-types assoc kw ability-fn))
(defn select-ability-kw
[ability]
(first (keys (select-keys ability (keys @ability-types)))))
(defn dissoc-req
[ability]
(if-let [ab (select-ability-kw ability)]
(dissoc-in ability [ab :req])
(dissoc ability :req)))
(defn should-trigger?
"Checks if the specified ability definition should trigger.
Checks for a :req, either in the top level map, or in an :optional or :psi sub-map
Returns true if no :req found, returns nil if the supplied ability is nil"
([state side eid card targets {:keys [req] :as ability}]
(when ability
(let [ab (select-ability-kw ability)]
(cond
ab (should-trigger? state side eid card targets (get ability ab))
req (req state side eid card targets)
:else true)))))
(defn not-used-once?
[state {:keys [once once-key]} {:keys [cid]}]
(if once
(not (get-in @state [once (or once-key cid)]))
true))
(defn can-trigger?
"Checks if ability can trigger. Checks that once-per-turn is not violated."
[state side eid ability card targets]
(and (not-used-once? state ability card)
(should-trigger? state side eid card targets ability)))
(defn is-ability?
"Checks to see if a given map represents a card ability."
[{:keys [effect msg]}]
(or effect msg (seq (keys @ability-types))))
(defn resolve-ability
([state side {:keys [eid] :as ability} card targets]
(resolve-ability state side (or eid (make-eid state {:source card :source-type :ability})) ability card targets))
([state side eid ability card targets]
(resolve-ability-eid state side (assoc ability :eid eid) card targets)))
(defn- resolve-ability-eid
[state side {:keys [eid choices] :as ability} card targets]
(cond
;; Only has the eid, in effect a nil ability
(and eid (= 1 (count ability)))
(effect-completed state side eid)
;; This was called directly without an eid present
(and ability (not eid))
(resolve-ability-eid state side (assoc ability :eid (make-eid state eid)) card targets)
;; Both ability and eid are present, so we're good to go
(and ability eid)
(let [ab (select-ability-kw ability)
ability-fn (get @ability-types ab)]
(cond
ab (ability-fn state side ability card targets)
choices (check-choices state side ability card targets)
:else (check-ability state side ability card targets)))
;; Something has gone terribly wrong, error out
:else
(.println *err* (with-out-str
(print-stack-trace
(Exception. (str "Ability is nil????" ability card targets))
2500)))))
;;; Checking functions for resolve-ability
(defn- check-choices
[state side {:keys [eid] :as ability} card targets]
(if (can-trigger? state side eid ability card targets)
(do-choices state side ability card targets)
(effect-completed state side eid)))
(defn- check-ability
[state side {:keys [eid] :as ability} card targets]
(if (can-trigger? state side eid ability card targets)
(do-ability state side ability card targets)
(effect-completed state side eid)))
(defn- print-msg
"Prints the ability message"
[state side {:keys [eid] :as ability} card targets payment-str]
(when-let [message (:msg ability)]
(let [desc (if (string? message) message (message state side eid card targets))
cost-spend-msg (build-spend-msg payment-str "use")]
(system-msg state (to-keyword (:side card))
(str cost-spend-msg (:title card) (str " to " desc))))))
(defn register-once
"Register ability as having happened if :once specified"
[state _ {:keys [once once-key]} {:keys [cid]}]
(when once
(swap! state assoc-in [once (or once-key cid)] true)))
(defn- do-effect
"Trigger the effect"
[state side {:keys [eid] :as ability} card targets]
(if-let [ability-effect (:effect ability)]
(ability-effect state side eid card targets)
(effect-completed state side eid)))
(defn- ugly-counter-hack
"This is brought over from the old do-ability because using `get-card` or `find-latest`
currently doesn't work properly with `pay-counters`"
[card cost]
;; TODO: Remove me some day
(let [[counter-type counter-amount]
(->> cost
(remove map?)
merge-costs
(filter #(some #{:advancement :agenda :power :virus} %))
first)]
(if counter-type
(let [counter (if (= :advancement counter-type)
[:advance-counter]
[:counter counter-type])]
(update-in card counter - counter-amount))
card)))
(declare checkpoint)
(defn merge-costs-paid
([cost-paid]
(into {} (map (fn [[k {:keys [type value targets]}]]
[k {:type type
:value value
:targets targets}])
cost-paid)))
([cost-paid1 cost-paid2]
(let [costs-paid [cost-paid1 cost-paid2]
cost-keys (mapcat keys costs-paid)]
(reduce (fn [acc cur]
(let [costs (map cur costs-paid)
cost-obj {:type cur
:value (apply + (keep :value costs))
:targets (seq (apply concat (keep :targets costs)))}]
(assoc acc cur cost-obj)))
{}
cost-keys)))
([cost-paid1 cost-paid2 & costs-paid]
(reduce merge-costs-paid (merge-costs-paid cost-paid1 cost-paid2) costs-paid)))
(defn- do-ability
"Perform the ability, checking all costs can be paid etc."
[state side {:keys [async eid cost player waiting-prompt] :as ability} card targets]
(when waiting-prompt
(add-to-prompt-queue
state (cond
player (if (= :corp player) :runner :corp)
(= :corp side) :runner
:else :corp)
{:eid (select-keys eid [:eid])
:card card
:prompt-type :waiting
:msg (str "Waiting for " waiting-prompt)}))
;; Ensure that any costs can be paid
(wait-for (pay state side (make-eid state eid) card cost {:action (:cid card)})
;; If the cost can be and is paid, perform the ablity
(let [payment-str (:msg async-result)
cost-paid (merge-costs-paid (:cost-paid eid) (:cost-paid async-result))]
(if payment-str
(wait-for (checkpoint state side (make-eid state eid) nil)
(let [ability (assoc-in ability [:eid :cost-paid] cost-paid)]
;; Print the message
(print-msg state side ability card targets payment-str)
;; Trigger the effect
(register-once state side ability card)
(do-effect state side ability (ugly-counter-hack card cost) targets)
;; If the ability isn't async, complete it
(when-not async
(effect-completed state side eid))))
(effect-completed state side eid)))))
(defn- do-choices
"Handle a choices ability"
[state side {:keys [choices eid not-distinct player prompt] :as ability} card targets]
(let [s (or player side)
ab (dissoc ability :choices :waiting-prompt)
args (-> ability
(select-keys [:priority :cancel-effect :prompt-type :show-discard :end-effect :waiting-prompt])
(assoc :targets targets))]
(if (map? choices)
;; Two types of choices use maps: select prompts, and :number prompts.
(cond
;; a counter prompt
(:counter choices)
(prompt! state s card prompt choices ab args)
;; a select prompt
(or (:req choices)
(:card choices))
(show-select state s card ability update! resolve-ability args)
;; a :number prompt
(:number choices)
(let [n ((:number choices) state side eid card targets)
d (if-let [dfunc (:default choices)]
(dfunc state side (make-eid state eid) card targets)
0)]
(prompt! state s card prompt {:number n :default d} ab args))
(:card-title choices)
(let [card-titles (sort (map :title (filter #((:card-title choices) state side (make-eid state eid) nil [%])
(server-cards))))
choices (assoc choices :autocomplete card-titles)
args (assoc args :prompt-type :card-title)]
(prompt! state s card prompt choices ab args))
;; unknown choice
:else nil)
;; Not a map; either :credit, :counter, or a vector of cards or strings.
(let [cs (if-not (fn? choices)
choices ; :credit or :counter
(let [cards (choices state side eid card targets)] ; a vector of cards or strings
(if not-distinct cards (distinct-by :title cards))))]
(prompt! state s card prompt cs ab args)))))
;;; Prompts
(defn prompt!
"Shows a prompt with the given message and choices. The given ability will be resolved
when the user resolves the prompt. Cards should generally not call this function directly; they
should use resolve-ability to resolve a map containing prompt data.
Please refer to the documentation at the top of resolve_ability.clj for a full description."
([state side card message choices ability] (prompt! state side card message choices ability nil))
([state side card message choices ability args]
(let [f #(resolve-ability state side ability card [%])]
(show-prompt state side (:eid ability) card message choices f
(if-let [f (:cancel-effect args)]
(assoc args :cancel-effect #(f state side (:eid ability) card [%]))
args)))))
;; EVENTS
; Functions for registering trigger suppression events
(defn register-suppress
"Registers each suppression handler in the given card definition. Suppression handlers
can prevent the dispatching of a particular event."
([state side card] (register-suppress state side card (:suppress (card-def card))))
([state _ card events]
(when events
(let [abilities
(->> (for [ability events]
{:event (:event ability)
:ability (dissoc ability :event)
:card card
:uuid (uuid/v1)})
(into []))]
(when (seq abilities)
(swap! state update :suppress #(apply conj % abilities)))
abilities))))
(defn unregister-suppress
"Removes all event handler suppression effects as defined for the given card"
([state side card] (unregister-suppress state side card (:suppress (card-def card))))
([state _ card events]
(let [abilities (map :event events)]
(swap! state assoc :suppress
(->> (:suppress @state)
(remove #(and (same-card? card (:card %))
(in-coll? abilities (:event %))))
(into []))))))
(defn unregister-suppress-by-uuid
"Removes a single event handler with matching uuid"
[state _ uuid]
(swap! state assoc :suppress (remove-once #(= uuid (:uuid %)) (:suppress @state))))
(defn- default-locations
[card]
(case (to-keyword (:type card))
:agenda #{:scored}
(:asset :ice :upgrade) #{:servers}
(:event :operation) #{:current :play-area}
(:hardware :program :resource) #{:rig}
(:identity :fake-identity) #{:identity}))
; Functions for registering and dispatching events.
(defn register-events
"Registers each event handler defined in the given card definition.
Also registers any suppression events."
([state side card] (register-events state side card nil))
([state side card events]
(let [events (or (seq events) (remove :location (:events (card-def card))))
abilities
(->> (for [ability events]
{:event (:event ability)
:location (let [location (:location ability)]
(cond
(or (list? location)
(vector? location))
(into #{} location)
(keyword? location)
#{location}
:else
(default-locations card)))
:duration (or (:duration ability) :while-installed)
:condition (or (:condition ability) :active)
:unregister-once-resolved (or (:unregister-once-resolved ability) false)
:once-per-instance (or (:once-per-instance ability) false)
:ability (dissoc ability :event :duration :condition)
:card card
:uuid (uuid/v1)})
(into []))]
(when (seq abilities)
(swap! state update :events #(apply conj % abilities)))
(register-suppress state side card)
abilities)))
(defn unregister-events
"Removes all event handlers defined for the given card.
Optionally input a partial card-definition map to remove only some handlers"
([state side card] (unregister-events state side card nil))
([state side card cdef]
;; Combine normal events and derezzed events. Any merge conflicts should not matter
;; as they should cause all relevant events to be removed anyway.
(let [events (or (seq (concat (:events cdef) (:derezzed-events cdef)))
(let [cdef (card-def card)]
(remove :location (concat (:events cdef) (:derezzed-events cdef)))))
abilities (map :event events)]
(swap! state assoc :events
(->> (:events @state)
(remove #(and (same-card? card (:card %))
(in-coll? abilities (:event %))
(= :while-installed (:duration %))))
(into [])))
(unregister-suppress state side card))))
(defn unregister-floating-events
"Removes all event handlers with a non-persistent duration"
[state _ duration]
(when (not= :while-installed duration)
(swap! state assoc :events
(->> (:events @state)
(remove #(= duration (:duration %)))
(into [])))))
(defn unregister-floating-events-for-card
"Removes all event handlers with a non-persistent duration on a single card"
[state _ card duration]
(swap! state assoc :events
(->> (:events @state)
(remove #(and (same-card? card (:card %))
(= duration (:duration %))))
(into []))))
(defn unregister-event-by-uuid
"Removes a single event handler with matching uuid"
[state _ uuid]
(swap! state assoc :events (remove-once #(= uuid (:uuid %)) (:events @state))))
;; triggering events
(defn- get-side
[ability]
(to-keyword (get-in ability [:card :side])))
(defn- get-ability-side
[ability]
(get-in ability [:ability :side]))
(defn- is-active-player
[state ability]
(= (:active-player @state) (get-side ability)))
(defn- card-for-ability
[state ability]
(if (#{:while-installed :pending} (:duration ability))
(when-let [card (get-card state (:card ability))]
(if (and (= :while-installed (:duration ability))
(not-empty
(clj-set/intersection (:location ability) (default-locations card))))
(case (:condition ability)
:active
(when (active? card)
card)
:facedown
(when (and (installed? card)
(facedown? card))
card)
:derezzed
(when (and (installed? card)
(not (rezzed? card)))
card)
:hosted
(when (:host card)
card)
; else
nil)
card))
(:card ability)))
(defn trigger-suppress
"Returns true if the given event on the given targets should be suppressed, by triggering
each suppression handler and returning true if any suppression handler returns true."
[state side event & targets]
(->> (:suppress @state)
(filter #(= event (:event %)))
(some #((:req (:ability %)) state side (make-eid state) (card-for-ability state %) targets))))
(defn gather-events
"Prepare the list of the given player's handlers for this event.
Gather all registered handlers from the state, then append the card-abilities if appropriate,
then filter to remove suppressed handlers and those whose req is false.
This is essentially Phase 9.3 and 9.6.7a of CR 1.1:
http://nisei.net/files/Comprehensive_Rules_1.1.pdf"
([state side event targets] (gather-events state side event targets nil))
([state side event targets card-abilities] (gather-events state side (make-eid state) event targets nil))
([state side eid event targets card-abilities]
(->> (:events @state)
(filter #(= event (:event %)))
(concat card-abilities)
(filter identity)
(filter (fn [ability]
(let [card (card-for-ability state ability)]
(and (not (apply trigger-suppress state side event card targets))
(can-trigger? state side eid (:ability ability) card targets)))))
(sort-by (complement #(is-active-player state %)))
doall)))
(defn- log-event
[state event targets]
(swap! state update :turn-events #(cons [event targets] %))
(when (:run @state)
(swap! state update-in [:run :events] #(cons [event targets] %))))
(defn trigger-event
"Resolves all abilities registered as handlers for the given event key, passing them
the targets given."
[state side event & targets]
(when (some? event)
(log-event state event targets)
(let [handlers (gather-events state side event targets)]
(doseq [to-resolve handlers]
(when-let [card (card-for-ability state to-resolve)]
(resolve-ability state side (dissoc-req (:ability to-resolve)) card targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve))))))))
(defn- trigger-event-sync-next
[state side eid handlers event targets]
(if-let [to-resolve (first handlers)]
(if-let [card (card-for-ability state to-resolve)]
(wait-for (resolve-ability state side (make-eid state (assoc eid :source card :source-type :ability)) (dissoc-req (:ability to-resolve)) card targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(trigger-event-sync-next state side eid (rest handlers) event targets))
(trigger-event-sync-next state side eid (rest handlers) event targets))
(effect-completed state side eid)))
(defn trigger-event-sync
"Triggers the given event synchronously, requiring each handler to complete before alerting the next handler. Does not
give the user a choice of what order to resolve handlers."
[state side eid event & targets]
(if (nil? event)
(effect-completed state side eid)
(do (log-event state event targets)
(let [handlers (gather-events state side eid event targets nil)]
(trigger-event-sync-next state side eid handlers event targets)))))
(defn- trigger-event-simult-player
"Triggers the simultaneous event handlers for the given event trigger and player.
If none of the handlers require interaction, then they are all resolved automatically, each waiting for the previous
to fully resolve as in trigger-event-sync. If at least one requires interaction, then a menu is shown to manually
choose the order of resolution.
:silent abilities are not shown in the list of handlers, and are resolved last in an arbitrary order."
[state side eid handlers cancel-fn event-targets]
(if (not-empty handlers)
(letfn [;; Allow resolution as long as there is no cancel-fn, or if the cancel-fn returns false.
(should-continue [state handlers]
(and (< 1 (count handlers))
(not (and cancel-fn (cancel-fn state)))))
(choose-handler [handlers]
(let [handlers (when-not (and cancel-fn (cancel-fn state))
(filter #(and (card-for-ability state %)
(not (:disabled (card-for-ability state %))))
handlers))
non-silent (filter #(let [silent-fn (:silent (:ability %))
card (card-for-ability state %)]
(not (and silent-fn
(silent-fn state side (make-eid state) card event-targets))))
handlers)
titles (map :card non-silent)
interactive (filter #(let [interactive-fn (:interactive (:ability %))
card (card-for-ability state %)]
(and interactive-fn
(interactive-fn state side (make-eid state) card event-targets)))
handlers)]
;; If there is only 1 non-silent ability, resolve that then recurse on the rest
(if (or (= 1 (count handlers)) (empty? interactive) (= 1 (count non-silent)))
(let [to-resolve (if (= 1 (count non-silent))
(first non-silent)
(first handlers))
ability-to-resolve (dissoc-req (:ability to-resolve))
others (if (= 1 (count non-silent))
(remove-once #(= (get-cid to-resolve) (get-cid %)) handlers)
(rest handlers))]
(if-let [the-card (card-for-ability state to-resolve)]
{:async true
:effect (req (wait-for (resolve-ability state (to-keyword (:side the-card))
(make-eid state (assoc eid :source the-card :source-type :ability))
ability-to-resolve
the-card event-targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(if (should-continue state handlers)
(continue-ability state side
(choose-handler others) nil event-targets)
(effect-completed state side eid))))}
{:async true
:effect (req (if (should-continue state handlers)
(continue-ability state side (choose-handler (rest handlers)) nil event-targets)
(effect-completed state side eid)))}))
{:prompt "Choose a trigger to resolve"
:choices titles
:async true
:effect (req (let [to-resolve (some #(when (same-card? target (:card %)) %) handlers)
ability-to-resolve (dissoc-req (:ability to-resolve))
the-card (card-for-ability state to-resolve)]
(wait-for
(resolve-ability state (to-keyword (:side the-card))
(make-eid state (assoc eid :source the-card :source-type :ability))
ability-to-resolve the-card event-targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(if (should-continue state handlers)
(continue-ability state side
(choose-handler
(remove-once #(same-card? target (:card %)) handlers))
nil event-targets)
(effect-completed state side eid)))))})))]
(continue-ability state side (choose-handler handlers) nil event-targets))
(effect-completed state side eid)))
(defn ability-as-handler
"Wraps a card ability as an event handler."
[card ability]
{:duration (or (:duration ability) :pending)
:card card
:ability ability})
(defn card-as-handler
"Wraps a card's definition as an event handler."
[card]
(let [{:keys [effect prompt choices psi optional trace] :as cdef} (card-def card)]
(when (or effect prompt choices psi optional trace)
(ability-as-handler card cdef))))
(defn effect-as-handler
"Wraps a five-argument function as an event handler."
[card effect]
(ability-as-handler card {:effect effect}))
(defn- event-title
"Gets a string describing the internal engine event keyword"
[event]
(if (keyword? event)
(name event)
(str event)))
(defn trigger-event-simult
"Triggers the given event by showing a prompt of all handlers for the event, allowing manual resolution of
simultaneous trigger handlers. effect-completed is fired once all registered event handlers have completed.
Parameters:
state, side: as usual
eid: the eid of the entire triggering sequence, which will be completed when all handlers are completed
event: the event keyword to trigger handlers for
first-ability: an ability map (fed to resolve-ability) that should be resolved after the list of handlers is determined
but before any of them is actually fired. Typically used for core rules that happen in the same window
as triggering handlers, such as trashing a corp Current when an agenda is stolen. Necessary for
interaction with New Angeles Sol and Employee Strike
card-ability: a card's ability that triggers at the same time as the event trigger, but is coded as a card ability
and not an event handler. (For example, :stolen on agendas happens in the same window as :agenda-stolen
after-active-player: an ability to resolve after the active player's triggers resolve, before the opponent's get to act
cancel-fn: a function that takes one argument (the state) and returns true if we should stop the event resolution
process, likely because an event handler caused a change to the game state that cancels future handlers.
(Film Critic)
targets: a varargs list of targets to the event, as usual"
[state side eid event {:keys [first-ability card-abilities after-active-player cancel-fn]} & targets]
(if (nil? event)
(effect-completed state side eid)
(do (log-event state event targets)
(let [active-player (:active-player @state)
opponent (other-side active-player)
is-player (fn [player ability]
(or (= player (get-side ability))
(= player (get-ability-side ability))))
card-abilities (if (and (some? card-abilities)
(not (sequential? card-abilities)))
[card-abilities]
card-abilities)
handlers (gather-events state side eid event targets card-abilities)
get-handlers (fn [player-side]
(filterv (partial is-player player-side) handlers))
active-player-events (get-handlers active-player)
opponent-events (get-handlers opponent)]
(wait-for (resolve-ability state side (make-eid state eid) first-ability nil nil)
(show-wait-prompt state opponent
(str (side-str active-player) " to resolve " (event-title event) " triggers")
{:priority -1})
; let active player activate their events first
(wait-for (trigger-event-simult-player state side (make-eid state eid) active-player-events cancel-fn targets)
(when after-active-player
(resolve-ability state side eid after-active-player nil nil))
(clear-wait-prompt state opponent)
(show-wait-prompt state active-player
(str (side-str opponent) " to resolve " (event-title event) " triggers")
{:priority -1})
(wait-for (trigger-event-simult-player state opponent (make-eid state eid) opponent-events cancel-fn targets)
(clear-wait-prompt state active-player)
(effect-completed state side eid))))))))
;; EVENT QUEUEING
(defn queue-event
([state event] (queue-event state event nil))
([state event context-map]
(when (keyword? event)
(swap! state update-in [:queued-events event] conj (assoc context-map :event event)))))
(defn make-pending-event
[state event card ability]
(let [ability {:event event
:duration :pending
:unregister-once-resolved true
:once-per-instance (or (:once-per-instance ability) false)
:ability ability
:card card
:uuid (uuid/v1)}]
(swap! state update :events conj ability)))
(defn- gather-queued-event-handlers
[state event-maps]
(for [[event context-maps] event-maps]
{:handlers (filterv #(= event (:event %)) (:events @state))
:context-maps (into [] context-maps)}))
(defn- create-instances
[{:keys [handlers context-maps]}]
(apply concat
(for [handler handlers]
(if (:once-per-instance handler)
[{:handler handler
:context context-maps}]
(for [context context-maps]
{:handler handler
:context [context]})))))
(defn- create-handlers
[state eid event-maps]
(->> (gather-queued-event-handlers state event-maps)
(mapcat create-instances)
(filter (fn [{:keys [handler context]}]
(let [card (card-for-ability state handler)
ability (:ability handler)]
(and (not (apply trigger-suppress state (to-keyword (:side card)) (:event handler) card context))
(can-trigger? state (to-keyword (:side card)) eid ability card context)))))
(sort-by (complement #(is-active-player state (:handler %))))
(seq)))
(defn- trigger-queued-event-player
[state side eid handlers {:keys [cancel-fn] :as args}]
(if (empty? handlers)
(effect-completed state nil eid)
(let [handlers (when-not (and cancel-fn (cancel-fn state))
(filter #(let [card (card-for-ability state (:handler %))]
(and card
(not (:disabled card))
(not (apply trigger-suppress state (to-keyword (:side card))
(get-in % [:handler :event]) card (:context %)))))
handlers))
non-silent (filter #(let [silent-fn (:silent (:ability (:handler %)))]
(not (and silent-fn
(silent-fn state side
(make-eid state eid)
(card-for-ability state (:handler %))
(:context %)))))
handlers)
titles (keep #(card-for-ability state (:handler %)) non-silent)
interactive (filter #(let [interactive-fn (:interactive (:ability (:handler %)))]
(and interactive-fn
(interactive-fn state side
(make-eid state eid)
(card-for-ability state (:handler %))
(:context %))))
handlers)]
(if (or (= 1 (count handlers))
(empty? interactive)
(= 1 (count non-silent)))
(let [handler (first handlers)
to-resolve (:handler handler)
ability (:ability to-resolve)
context (:context handler)
ability-card (card-for-ability state to-resolve)]
(if ability-card
(wait-for (resolve-ability state (to-keyword (:side ability-card))
(make-eid state (assoc eid :source ability-card :source-type :ability))
(dissoc-req ability)
ability-card
context)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(trigger-queued-event-player state side eid (rest handlers) args))
(trigger-queued-event-player state side eid (rest handlers) args)))
(continue-ability
state side
(when (pos? (count handlers))
{:async true
:prompt "Choose a trigger to resolve"
:choices titles
:effect (req (let [handler (some #(when (same-card? target (card-for-ability state (:handler %))) %) handlers)
to-resolve (:handler handler)
ability (:ability to-resolve)
context (:context handler)
ability-card (card-for-ability state to-resolve)]
(wait-for
(resolve-ability state (to-keyword (:side ability-card))
(make-eid state (assoc eid :source ability-card :source-type :ability))
(dissoc-req ability)
ability-card
context)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(let [handlers (remove-once #(same-card? target (card-for-ability state (:handler %))) handlers)]
(trigger-queued-event-player state side eid handlers args)))))})
nil nil)))))
(defn- is-player
[player {:keys [handler]}]
(or (= player (get-side handler))
(= player (get-ability-side handler))))
(defn- filter-handlers
[handlers player-side]
(filterv #(is-player player-side %) handlers))
(defn- mark-pending-abilities
[state eid args]
(let [event-maps (:queued-events @state)]
(doseq [[event context-map] event-maps]
(log-event state event context-map))
(when-not (empty? event-maps)
(let [handlers (create-handlers state eid event-maps)]
(swap! state assoc
:queued-events {}
:events (->> (:events @state)
(remove #(= :pending (:duration %)))
(into [])))
{:handlers handlers
:context-maps (apply concat (vals event-maps))}))))
(defn- trigger-pending-abilities
[state eid handlers args]
(if (seq handlers)
(let [active-player (:active-player @state)
opponent (other-side active-player)
active-player-handlers (filter-handlers handlers active-player)
opponent-handlers (filter-handlers handlers opponent)]
(show-wait-prompt state opponent (str (side-str active-player) " to resolve pending triggers"))
(wait-for (trigger-queued-event-player state active-player (make-eid state eid) active-player-handlers args)
(clear-wait-prompt state opponent)
(show-wait-prompt state active-player (str (side-str opponent) " to resolve pending triggers"))
(wait-for (trigger-queued-event-player state opponent (make-eid state eid) opponent-handlers args)
(clear-wait-prompt state active-player)
(effect-completed state nil eid))))
(effect-completed state nil eid)))
;; CHECKPOINT
(defn internal-trash-cards
[state _ eid maps]
(if (seq maps)
(let [{:keys [card value]} (first maps)]
(wait-for (value state nil (make-eid state eid) card)
(internal-trash-cards state nil eid (next maps))))
(effect-completed state nil eid)))
(defn trash-when-expired
[state _ eid context-maps]
(if (seq context-maps)
(->> context-maps
(get-effect-maps state nil eid :trash-when-expired)
(internal-trash-cards state nil eid))
(effect-completed state nil eid)))
(defn unregister-expired-durations
[state _ eid duration context-maps]
(wait-for (trash-when-expired state nil (make-eid state eid) context-maps)
(if duration
(unregister-floating-effects state nil duration)
(unregister-floating-events state nil duration))
(effect-completed state nil eid)))
(defn checkpoint
([state eid] (checkpoint state nil eid nil))
([state _ eid] (checkpoint state nil eid nil))
([state _ eid {:keys [duration] :as args}]
;; a: Any ability that has met its condition creates the appropriate instances of itself and marks them as pending
(let [{:keys [handlers context-maps]} (mark-pending-abilities state eid args)]
;; b: Any ability with a duration that has passed is removed from the game state
(wait-for
(unregister-expired-durations state nil (make-eid state eid) duration context-maps)
;; c: Check winning or tying by agenda points
(check-win-by-agenda state)
;; d: uniqueness check
;; unimplemented
;; e: restrictions on card abilities or game rules, MU
;; unimplemented
;; f: stuff on agendas moved from score zone
;; unimplemented
;; g: stuff on installed cards that were trashed
;; unimplemented
;; h: empty servers
(clear-empty-remotes state)
;; i: card counters/agendas become cards again
;; unimplemented
;; j: counters in discard are returned to the bank
;; unimplemented
;; 10.3.2: reaction window
(trigger-pending-abilities state eid handlers args)))))
(defn end-of-phase-checkpoint
([state _ eid event] (end-of-phase-checkpoint state nil eid event nil))
([state _ eid event context]
(when event
(queue-event state event context))
(checkpoint state nil eid {:duration event})))
;; PAYMENT
(defn- pay-next
[state side eid costs card actions msgs]
(if (empty? costs)
(complete-with-result state side eid msgs)
(wait-for (handler (first costs) state side (make-eid state eid) card actions)
(pay-next state side eid (rest costs) card actions (conj msgs async-result)))))
(defn- sentence-join
[strings]
(if (<= (count strings) 2)
(string/join " and " strings)
(str (apply str (interpose ", " (butlast strings))) ", and " (last strings))))
(defn pay
"Same as pay, but awaitable."
[state side eid card & args]
(let [args (flatten args)
raw-costs (remove map? args)
actions (filter map? args)]
(if-let [costs (can-pay? state side eid card (:title card) raw-costs)]
(wait-for (pay-next state side (make-eid state eid) costs card actions [])
(let [payment-result async-result]
(wait-for (checkpoint state nil (make-eid state eid) nil)
(complete-with-result
state side eid
{:msg (->> payment-result
(keep :msg)
sentence-join)
:cost-paid (->> payment-result
(keep #(not-empty (select-keys % [:type :targets :value])))
(reduce
(fn [acc cost]
(assoc acc (:type cost) cost))
{}))}))))
(complete-with-result state side eid nil))))
|
40682
|
(ns game.core.engine
(:require
[clojure.set :as clj-set]
[clojure.stacktrace :refer [print-stack-trace]]
[clojure.string :as string]
[clj-uuid :as uuid]
[game.core.board :refer [clear-empty-remotes]]
[game.core.card :refer [active? facedown? get-card get-cid has-subtype? installed? rezzed?]]
[game.core.card-defs :refer [card-def]]
[game.core.effects :refer [any-effects effect-pred get-effect-maps unregister-floating-effects]]
[game.core.eid :refer [complete-with-result effect-completed make-eid]]
[game.core.payment :refer [build-spend-msg can-pay? merge-costs handler]]
[game.core.prompt-state :refer [add-to-prompt-queue]]
[game.core.prompts :refer [clear-wait-prompt show-prompt show-select show-wait-prompt]]
[game.core.say :refer [system-msg]]
[game.core.update :refer [update!]]
[game.core.winning :refer [check-win-by-agenda]]
[game.macros :refer [continue-ability req wait-for]]
[game.utils :refer [dissoc-in distinct-by in-coll? server-cards remove-once same-card? side-str to-keyword]]
[jinteki.utils :refer [other-side]]))
;; resolve-ability docs
; Perhaps the most important function in the game logic.
; Resolves an ability defined by the given ability map. Checks :req functions; shows prompts, psi games,
; traces, etc. as needed; charges costs; invokes :effect functions. All card effects and most engine effects
; should run through this method. Unless noted, every key listed is optional.
; How to read this:
; :key -- type
; Description, reasoning, expected return value, etc.
; Types:
; integer, string, keyword: clojure literals
; boolean: clojure literal, but should generally only be true (as leaving it off counts as false)
; vector: can be a literal [] or '(), can also be the return value of a function, but
; must not be a function definition that returns a vector or list
; map of X: clojure literal. X is a comma-separated list of allowed keys.
; The description will be laid out recursively, and keys will be marked as required or optional.
; ability map: an ability map as defined here.
; enum: a comma-separated list of values, one of which can be used.
; 5-fn: typically (req), but any function definition that takes state, side, eid, card, targets.
; Something that accepts different types will have the types separated by "or".
; For example, "string or 5-fn" means it accepts a string or a 5-fn. The description will
; say what the 5-fn should return, if anything.
; COMMON KEYS
; :req -- 5-fn
; Must return true or false. If false, the ability will not be resolved.
; :cost -- vector
; A vector of cost pairs to charge, for example [:credit 1 :click 1].
; If the costs cannot be paid, the ability will not be resolved.
; :msg -- string or 5-fn.
; Must return a string. (`msg` is expressly built for this.)
; Prints to the log when the ability is finished. Will be used as the :label if no :label is provided.
; The output is written as:
; (with cost) "{Player} pays {X} to use {card title} to {msg result}."
; (with no cost) "{Player} uses {card title} to {msg result}."
; so the returned string should always be written imperatively.
; :label -- string
; If this ability is in an :abilities map on a card, the label will be prepended with a string
; of the costs, and both will be displayed in the ability button. If this is not defined
; and a label is needed, :msg will be used if it is a string.
; :effect -- 5-fn
; Will be called if the ability will be resolved (if :req is true or not present,
; costs can be paid, and any prompts are resolved).
; :player -- enum: :corp, :runner
; Manually specifies which player the ability should affect, rather than leave it implicit.
; :async -- boolean
; Mark the ability as "async", meaning the :effect function must call effect-completed itself.
; Without this being set to true, resolve-ability will call effect-completed once it's done.
; This part of the engine is really dumb and complicated, so ask someone on slack about it.
; :cost-req -- 1-fn
; A function which will be applied to the cost of an ability immediatly prior to being paid. See all-stealth or min-stealth for examples.
; PROMPT KEYS
; :prompt -- string or 5-fn
; Must return a string to display in the prompt menu.
; :choices -- 5-fn or :credit or :counter or map
; This key signals a prompt of some kind. (It should be split into multiple keys, but that's a lot of work lol)
; * 5-fn
; Must return a vector of card objects or strings.
; User chooses one. This is called a 'choice' prompt.
; * :credit
; User chooses an integer up to their current credit amount.
; * :counter
; User chooses an integer up to the :counter value of the current card.
; * map of :number, :default
; User chooses an integer between 0 and some number
; :number -- 5-fn
; Required. Must return a number, which is the maximum allowed.
; :default -- 5-fn
; Optional. Must return a number, which is the number the dropdown will display initially.
; * map of :card or :req, :all, :max, :not-self
; Triggers a 'select' prompt with targeting cursor for "selecting" one or more cards.
; :card -- 1-argument function
; Either this or :req is required, but not both.
; Accepts a single card object, must return true or false to indicate if selection is successful.
; :req -- 5-fn
; Either this or :card is required, but not both.
; "target" is the clicked card. Must return true or false to indicate if selection is successful.
; :all -- boolean
; Optional. Changes the select prompt from optional (can click "Done" to not select anything) to
; mandatory. When :max is also set to true, enforces selecting the specified number of cards.
; :max -- integer
; Optional. Changes the select from to resolving after selecting a single card to
; resolving when either a number of cards (as set by :max) have been selected or a number
; of cards less than that set by :max are selected and the "Done" button has been clicked.
; When :all is also set to true, enforces selecting the specified number of cards.
; :not-self -- boolean
; Certain abilities can target any card on the table, others can only target other cards.
; For example, Yusuf vs Aesop's. Setting this is the same as adding
; `(not (same-card? % card))` to your :card function or `(not (same-card? target card))`
; to your :req function.
; :not-distinct -- boolean
; By default, duplicate entries of the same string will be combined into a single button.
; If set to true, duplicate entries of the same string will be shown as multiple buttons.
; :cancel-effect -- 5-fn
; If a prompt with the choice "Cancel" is clicked, the prompt exits without doing anything else
; and this function will be called.
; SIMULTANEOUS EFFECT RESOLUTION KEYS
; :interactive -- 5-fn. when simultaneous effect resolution has been enabled for a specific event, the user receives
; a menu of cards that handle the effect and get to choose the order of their resolution. This menu is
; only shown if at least one ability handling the event has an :interactive function that returns true.
; If none are interactive, then all handlers will be resolved automatically, one at a time in an
; arbitrary order. In general, handlers should be marked ':interactive (req true)' if they have
; important order-of-effect interactions with other cards. The :interactive function can be coded to
; have smarter logic if necessary -- see Replicator, which is only interactive if there is another
; copy of the installed card remaining in the Stack.
; :silent -- any handler that does not require user interaction under any circumstances can be marked :silent. If a
; handler's :silent function returns true, then no menu entry will be shown for the handler. In that case,
; the ability will only be resolved once all non-silent abilities are resolved. Example: AstroScript has no
; important interactions with other 'agenda scored' effects, and doesn't care when an agenda token is placed.
; Example: <NAME> will not show a prompt if there are no valid targets in the grip.
; OTHER KEYS
; :once -- either :per-turn or :per-run. signifies an effect that can only be triggered once per turn.
; :once-key -- keyword. by default, each :once is distinct per card. If multiple copies of a card can only resolve
; some ability once between all of them, then the card should specify a manual :once-key that can
; be any value, preferrably a unique keyword.
; :install-req -- a function which returns a list of servers a card may be installed into
; :makes-run -- boolean. indicates if the ability makes a run.
; COMPLEX ABILITY WRAPPERS
; These are wrappers around more complex/cumbersome functionality. They all call into a flow that would
; be cumbersome to write out every time in a "normal" ability map.
; :psi -- map of :req, :equal, :not-equal
; Handles psi games.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :equal -- ability map
; At least one of :equal and :not-equal are required.
; Async ability that is executed if the players reveal the same number of credits.
; :not-equal -- ability map
; At least one of :equal and :not-equal are required.
; Async ability that is executed if the players reveal the a differen number of credits.
; :trace -- map of :req, :label, :base, :successful, :unsuccessful, :kicker, :kicker-min
; Handles traces.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :label -- 5-fn
; Optional. Works same as :label in an ability map.
; :base -- integer or 5-fn
; Required. Must return an integer, which sets the "base" initial value for the trace.
; :successful -- ability map
; At least one of :successful and :unsuccessful are required.
; Async ability that is executed if the trace is successful.
; :unsuccessful -- ability map
; At least one of :successful and :unsuccessful are required.
; Async ability that is executed if the trace is unsuccessful.
; :kicker -- ability map
; Optional. Async ability that is executed if the corp's trace strength is equal to or greater
; than :kicker-min.
; :kicker-min -- integer
; Required if :kicker is defined. The number the corp's strength must be equal to or greater
; to execute the :kicker ability.
; :optional -- map of :req, :prompt, :player, :yes-ability, :no-ability, :end-effect, :autoresolve
; Shows a "Yes/No" prompt to handle the user deciding whether to resolve the ability.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :prompt -- string or 5-fn
; Required. Must return a string to display in the prompt menu.
; :player -- enum: :corp, :runner
; Optional. Hardcodes which player will resolve this prompt.
; :yes-ability -- ability-map
; At least one of :yes-ability and :no-ability are required. (Normally, this should always
; be defined, but sometimes it's easier to word things in the negative, such that only
; defining :no-ability is the most natural way to write the ability.)
; Async ability that is executed if "Yes" is chosen.
; :no-ability -- ability-map
; At least one of :yes-ability and :no-ability are required. (See note above.)
; Async ability that is executed if "No" is chosen, or if "Yes" is chosen but there's
; no :yes-ability defined, or :yes-ability has a :cost that the player can't afford.
; :end-effect -- 5-fn
; Called after :yes- or :no-ability has been resolved.
; Must not be async as it is not awaited.
; :autoresolve -- 5-fn
; Optional. Used to set an optional prompt to either ask, always choose "Yes", or always choose "No".
; Must use the (get-autoresolve kw) helper function, where kw is an ability-specific
; keyword that will be stored in the card's [:special] map.
; Must use the (set-autoresolve kw) helper function in the card's :abilities vector,
; to allow for changing the autoresolve settings, where kw is the same keyword as used in
; the (get-autoresolve kw) call.
(declare do-ability resolve-ability-eid check-ability pay prompt! check-choices do-choices)
(def ability-types (atom {}))
(defn register-ability-type
[kw ability-fn]
(swap! ability-types assoc kw ability-fn))
(defn select-ability-kw
[ability]
(first (keys (select-keys ability (keys @ability-types)))))
(defn dissoc-req
[ability]
(if-let [ab (select-ability-kw ability)]
(dissoc-in ability [ab :req])
(dissoc ability :req)))
(defn should-trigger?
"Checks if the specified ability definition should trigger.
Checks for a :req, either in the top level map, or in an :optional or :psi sub-map
Returns true if no :req found, returns nil if the supplied ability is nil"
([state side eid card targets {:keys [req] :as ability}]
(when ability
(let [ab (select-ability-kw ability)]
(cond
ab (should-trigger? state side eid card targets (get ability ab))
req (req state side eid card targets)
:else true)))))
(defn not-used-once?
[state {:keys [once once-key]} {:keys [cid]}]
(if once
(not (get-in @state [once (or once-key cid)]))
true))
(defn can-trigger?
"Checks if ability can trigger. Checks that once-per-turn is not violated."
[state side eid ability card targets]
(and (not-used-once? state ability card)
(should-trigger? state side eid card targets ability)))
(defn is-ability?
"Checks to see if a given map represents a card ability."
[{:keys [effect msg]}]
(or effect msg (seq (keys @ability-types))))
(defn resolve-ability
([state side {:keys [eid] :as ability} card targets]
(resolve-ability state side (or eid (make-eid state {:source card :source-type :ability})) ability card targets))
([state side eid ability card targets]
(resolve-ability-eid state side (assoc ability :eid eid) card targets)))
(defn- resolve-ability-eid
[state side {:keys [eid choices] :as ability} card targets]
(cond
;; Only has the eid, in effect a nil ability
(and eid (= 1 (count ability)))
(effect-completed state side eid)
;; This was called directly without an eid present
(and ability (not eid))
(resolve-ability-eid state side (assoc ability :eid (make-eid state eid)) card targets)
;; Both ability and eid are present, so we're good to go
(and ability eid)
(let [ab (select-ability-kw ability)
ability-fn (get @ability-types ab)]
(cond
ab (ability-fn state side ability card targets)
choices (check-choices state side ability card targets)
:else (check-ability state side ability card targets)))
;; Something has gone terribly wrong, error out
:else
(.println *err* (with-out-str
(print-stack-trace
(Exception. (str "Ability is nil????" ability card targets))
2500)))))
;;; Checking functions for resolve-ability
(defn- check-choices
[state side {:keys [eid] :as ability} card targets]
(if (can-trigger? state side eid ability card targets)
(do-choices state side ability card targets)
(effect-completed state side eid)))
(defn- check-ability
[state side {:keys [eid] :as ability} card targets]
(if (can-trigger? state side eid ability card targets)
(do-ability state side ability card targets)
(effect-completed state side eid)))
(defn- print-msg
"Prints the ability message"
[state side {:keys [eid] :as ability} card targets payment-str]
(when-let [message (:msg ability)]
(let [desc (if (string? message) message (message state side eid card targets))
cost-spend-msg (build-spend-msg payment-str "use")]
(system-msg state (to-keyword (:side card))
(str cost-spend-msg (:title card) (str " to " desc))))))
(defn register-once
"Register ability as having happened if :once specified"
[state _ {:keys [once once-key]} {:keys [cid]}]
(when once
(swap! state assoc-in [once (or once-key cid)] true)))
(defn- do-effect
"Trigger the effect"
[state side {:keys [eid] :as ability} card targets]
(if-let [ability-effect (:effect ability)]
(ability-effect state side eid card targets)
(effect-completed state side eid)))
(defn- ugly-counter-hack
"This is brought over from the old do-ability because using `get-card` or `find-latest`
currently doesn't work properly with `pay-counters`"
[card cost]
;; TODO: Remove me some day
(let [[counter-type counter-amount]
(->> cost
(remove map?)
merge-costs
(filter #(some #{:advancement :agenda :power :virus} %))
first)]
(if counter-type
(let [counter (if (= :advancement counter-type)
[:advance-counter]
[:counter counter-type])]
(update-in card counter - counter-amount))
card)))
(declare checkpoint)
(defn merge-costs-paid
([cost-paid]
(into {} (map (fn [[k {:keys [type value targets]}]]
[k {:type type
:value value
:targets targets}])
cost-paid)))
([cost-paid1 cost-paid2]
(let [costs-paid [cost-paid1 cost-paid2]
cost-keys (mapcat keys costs-paid)]
(reduce (fn [acc cur]
(let [costs (map cur costs-paid)
cost-obj {:type cur
:value (apply + (keep :value costs))
:targets (seq (apply concat (keep :targets costs)))}]
(assoc acc cur cost-obj)))
{}
cost-keys)))
([cost-paid1 cost-paid2 & costs-paid]
(reduce merge-costs-paid (merge-costs-paid cost-paid1 cost-paid2) costs-paid)))
(defn- do-ability
"Perform the ability, checking all costs can be paid etc."
[state side {:keys [async eid cost player waiting-prompt] :as ability} card targets]
(when waiting-prompt
(add-to-prompt-queue
state (cond
player (if (= :corp player) :runner :corp)
(= :corp side) :runner
:else :corp)
{:eid (select-keys eid [:eid])
:card card
:prompt-type :waiting
:msg (str "Waiting for " waiting-prompt)}))
;; Ensure that any costs can be paid
(wait-for (pay state side (make-eid state eid) card cost {:action (:cid card)})
;; If the cost can be and is paid, perform the ablity
(let [payment-str (:msg async-result)
cost-paid (merge-costs-paid (:cost-paid eid) (:cost-paid async-result))]
(if payment-str
(wait-for (checkpoint state side (make-eid state eid) nil)
(let [ability (assoc-in ability [:eid :cost-paid] cost-paid)]
;; Print the message
(print-msg state side ability card targets payment-str)
;; Trigger the effect
(register-once state side ability card)
(do-effect state side ability (ugly-counter-hack card cost) targets)
;; If the ability isn't async, complete it
(when-not async
(effect-completed state side eid))))
(effect-completed state side eid)))))
(defn- do-choices
"Handle a choices ability"
[state side {:keys [choices eid not-distinct player prompt] :as ability} card targets]
(let [s (or player side)
ab (dissoc ability :choices :waiting-prompt)
args (-> ability
(select-keys [:priority :cancel-effect :prompt-type :show-discard :end-effect :waiting-prompt])
(assoc :targets targets))]
(if (map? choices)
;; Two types of choices use maps: select prompts, and :number prompts.
(cond
;; a counter prompt
(:counter choices)
(prompt! state s card prompt choices ab args)
;; a select prompt
(or (:req choices)
(:card choices))
(show-select state s card ability update! resolve-ability args)
;; a :number prompt
(:number choices)
(let [n ((:number choices) state side eid card targets)
d (if-let [dfunc (:default choices)]
(dfunc state side (make-eid state eid) card targets)
0)]
(prompt! state s card prompt {:number n :default d} ab args))
(:card-title choices)
(let [card-titles (sort (map :title (filter #((:card-title choices) state side (make-eid state eid) nil [%])
(server-cards))))
choices (assoc choices :autocomplete card-titles)
args (assoc args :prompt-type :card-title)]
(prompt! state s card prompt choices ab args))
;; unknown choice
:else nil)
;; Not a map; either :credit, :counter, or a vector of cards or strings.
(let [cs (if-not (fn? choices)
choices ; :credit or :counter
(let [cards (choices state side eid card targets)] ; a vector of cards or strings
(if not-distinct cards (distinct-by :title cards))))]
(prompt! state s card prompt cs ab args)))))
;;; Prompts
(defn prompt!
"Shows a prompt with the given message and choices. The given ability will be resolved
when the user resolves the prompt. Cards should generally not call this function directly; they
should use resolve-ability to resolve a map containing prompt data.
Please refer to the documentation at the top of resolve_ability.clj for a full description."
([state side card message choices ability] (prompt! state side card message choices ability nil))
([state side card message choices ability args]
(let [f #(resolve-ability state side ability card [%])]
(show-prompt state side (:eid ability) card message choices f
(if-let [f (:cancel-effect args)]
(assoc args :cancel-effect #(f state side (:eid ability) card [%]))
args)))))
;; EVENTS
; Functions for registering trigger suppression events
(defn register-suppress
"Registers each suppression handler in the given card definition. Suppression handlers
can prevent the dispatching of a particular event."
([state side card] (register-suppress state side card (:suppress (card-def card))))
([state _ card events]
(when events
(let [abilities
(->> (for [ability events]
{:event (:event ability)
:ability (dissoc ability :event)
:card card
:uuid (uuid/v1)})
(into []))]
(when (seq abilities)
(swap! state update :suppress #(apply conj % abilities)))
abilities))))
(defn unregister-suppress
"Removes all event handler suppression effects as defined for the given card"
([state side card] (unregister-suppress state side card (:suppress (card-def card))))
([state _ card events]
(let [abilities (map :event events)]
(swap! state assoc :suppress
(->> (:suppress @state)
(remove #(and (same-card? card (:card %))
(in-coll? abilities (:event %))))
(into []))))))
(defn unregister-suppress-by-uuid
"Removes a single event handler with matching uuid"
[state _ uuid]
(swap! state assoc :suppress (remove-once #(= uuid (:uuid %)) (:suppress @state))))
(defn- default-locations
[card]
(case (to-keyword (:type card))
:agenda #{:scored}
(:asset :ice :upgrade) #{:servers}
(:event :operation) #{:current :play-area}
(:hardware :program :resource) #{:rig}
(:identity :fake-identity) #{:identity}))
; Functions for registering and dispatching events.
(defn register-events
"Registers each event handler defined in the given card definition.
Also registers any suppression events."
([state side card] (register-events state side card nil))
([state side card events]
(let [events (or (seq events) (remove :location (:events (card-def card))))
abilities
(->> (for [ability events]
{:event (:event ability)
:location (let [location (:location ability)]
(cond
(or (list? location)
(vector? location))
(into #{} location)
(keyword? location)
#{location}
:else
(default-locations card)))
:duration (or (:duration ability) :while-installed)
:condition (or (:condition ability) :active)
:unregister-once-resolved (or (:unregister-once-resolved ability) false)
:once-per-instance (or (:once-per-instance ability) false)
:ability (dissoc ability :event :duration :condition)
:card card
:uuid (uuid/v1)})
(into []))]
(when (seq abilities)
(swap! state update :events #(apply conj % abilities)))
(register-suppress state side card)
abilities)))
(defn unregister-events
"Removes all event handlers defined for the given card.
Optionally input a partial card-definition map to remove only some handlers"
([state side card] (unregister-events state side card nil))
([state side card cdef]
;; Combine normal events and derezzed events. Any merge conflicts should not matter
;; as they should cause all relevant events to be removed anyway.
(let [events (or (seq (concat (:events cdef) (:derezzed-events cdef)))
(let [cdef (card-def card)]
(remove :location (concat (:events cdef) (:derezzed-events cdef)))))
abilities (map :event events)]
(swap! state assoc :events
(->> (:events @state)
(remove #(and (same-card? card (:card %))
(in-coll? abilities (:event %))
(= :while-installed (:duration %))))
(into [])))
(unregister-suppress state side card))))
(defn unregister-floating-events
"Removes all event handlers with a non-persistent duration"
[state _ duration]
(when (not= :while-installed duration)
(swap! state assoc :events
(->> (:events @state)
(remove #(= duration (:duration %)))
(into [])))))
(defn unregister-floating-events-for-card
"Removes all event handlers with a non-persistent duration on a single card"
[state _ card duration]
(swap! state assoc :events
(->> (:events @state)
(remove #(and (same-card? card (:card %))
(= duration (:duration %))))
(into []))))
(defn unregister-event-by-uuid
"Removes a single event handler with matching uuid"
[state _ uuid]
(swap! state assoc :events (remove-once #(= uuid (:uuid %)) (:events @state))))
;; triggering events
(defn- get-side
[ability]
(to-keyword (get-in ability [:card :side])))
(defn- get-ability-side
[ability]
(get-in ability [:ability :side]))
(defn- is-active-player
[state ability]
(= (:active-player @state) (get-side ability)))
(defn- card-for-ability
[state ability]
(if (#{:while-installed :pending} (:duration ability))
(when-let [card (get-card state (:card ability))]
(if (and (= :while-installed (:duration ability))
(not-empty
(clj-set/intersection (:location ability) (default-locations card))))
(case (:condition ability)
:active
(when (active? card)
card)
:facedown
(when (and (installed? card)
(facedown? card))
card)
:derezzed
(when (and (installed? card)
(not (rezzed? card)))
card)
:hosted
(when (:host card)
card)
; else
nil)
card))
(:card ability)))
(defn trigger-suppress
"Returns true if the given event on the given targets should be suppressed, by triggering
each suppression handler and returning true if any suppression handler returns true."
[state side event & targets]
(->> (:suppress @state)
(filter #(= event (:event %)))
(some #((:req (:ability %)) state side (make-eid state) (card-for-ability state %) targets))))
(defn gather-events
"Prepare the list of the given player's handlers for this event.
Gather all registered handlers from the state, then append the card-abilities if appropriate,
then filter to remove suppressed handlers and those whose req is false.
This is essentially Phase 9.3 and 9.6.7a of CR 1.1:
http://nisei.net/files/Comprehensive_Rules_1.1.pdf"
([state side event targets] (gather-events state side event targets nil))
([state side event targets card-abilities] (gather-events state side (make-eid state) event targets nil))
([state side eid event targets card-abilities]
(->> (:events @state)
(filter #(= event (:event %)))
(concat card-abilities)
(filter identity)
(filter (fn [ability]
(let [card (card-for-ability state ability)]
(and (not (apply trigger-suppress state side event card targets))
(can-trigger? state side eid (:ability ability) card targets)))))
(sort-by (complement #(is-active-player state %)))
doall)))
(defn- log-event
[state event targets]
(swap! state update :turn-events #(cons [event targets] %))
(when (:run @state)
(swap! state update-in [:run :events] #(cons [event targets] %))))
(defn trigger-event
"Resolves all abilities registered as handlers for the given event key, passing them
the targets given."
[state side event & targets]
(when (some? event)
(log-event state event targets)
(let [handlers (gather-events state side event targets)]
(doseq [to-resolve handlers]
(when-let [card (card-for-ability state to-resolve)]
(resolve-ability state side (dissoc-req (:ability to-resolve)) card targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve))))))))
(defn- trigger-event-sync-next
[state side eid handlers event targets]
(if-let [to-resolve (first handlers)]
(if-let [card (card-for-ability state to-resolve)]
(wait-for (resolve-ability state side (make-eid state (assoc eid :source card :source-type :ability)) (dissoc-req (:ability to-resolve)) card targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(trigger-event-sync-next state side eid (rest handlers) event targets))
(trigger-event-sync-next state side eid (rest handlers) event targets))
(effect-completed state side eid)))
(defn trigger-event-sync
"Triggers the given event synchronously, requiring each handler to complete before alerting the next handler. Does not
give the user a choice of what order to resolve handlers."
[state side eid event & targets]
(if (nil? event)
(effect-completed state side eid)
(do (log-event state event targets)
(let [handlers (gather-events state side eid event targets nil)]
(trigger-event-sync-next state side eid handlers event targets)))))
(defn- trigger-event-simult-player
"Triggers the simultaneous event handlers for the given event trigger and player.
If none of the handlers require interaction, then they are all resolved automatically, each waiting for the previous
to fully resolve as in trigger-event-sync. If at least one requires interaction, then a menu is shown to manually
choose the order of resolution.
:silent abilities are not shown in the list of handlers, and are resolved last in an arbitrary order."
[state side eid handlers cancel-fn event-targets]
(if (not-empty handlers)
(letfn [;; Allow resolution as long as there is no cancel-fn, or if the cancel-fn returns false.
(should-continue [state handlers]
(and (< 1 (count handlers))
(not (and cancel-fn (cancel-fn state)))))
(choose-handler [handlers]
(let [handlers (when-not (and cancel-fn (cancel-fn state))
(filter #(and (card-for-ability state %)
(not (:disabled (card-for-ability state %))))
handlers))
non-silent (filter #(let [silent-fn (:silent (:ability %))
card (card-for-ability state %)]
(not (and silent-fn
(silent-fn state side (make-eid state) card event-targets))))
handlers)
titles (map :card non-silent)
interactive (filter #(let [interactive-fn (:interactive (:ability %))
card (card-for-ability state %)]
(and interactive-fn
(interactive-fn state side (make-eid state) card event-targets)))
handlers)]
;; If there is only 1 non-silent ability, resolve that then recurse on the rest
(if (or (= 1 (count handlers)) (empty? interactive) (= 1 (count non-silent)))
(let [to-resolve (if (= 1 (count non-silent))
(first non-silent)
(first handlers))
ability-to-resolve (dissoc-req (:ability to-resolve))
others (if (= 1 (count non-silent))
(remove-once #(= (get-cid to-resolve) (get-cid %)) handlers)
(rest handlers))]
(if-let [the-card (card-for-ability state to-resolve)]
{:async true
:effect (req (wait-for (resolve-ability state (to-keyword (:side the-card))
(make-eid state (assoc eid :source the-card :source-type :ability))
ability-to-resolve
the-card event-targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(if (should-continue state handlers)
(continue-ability state side
(choose-handler others) nil event-targets)
(effect-completed state side eid))))}
{:async true
:effect (req (if (should-continue state handlers)
(continue-ability state side (choose-handler (rest handlers)) nil event-targets)
(effect-completed state side eid)))}))
{:prompt "Choose a trigger to resolve"
:choices titles
:async true
:effect (req (let [to-resolve (some #(when (same-card? target (:card %)) %) handlers)
ability-to-resolve (dissoc-req (:ability to-resolve))
the-card (card-for-ability state to-resolve)]
(wait-for
(resolve-ability state (to-keyword (:side the-card))
(make-eid state (assoc eid :source the-card :source-type :ability))
ability-to-resolve the-card event-targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(if (should-continue state handlers)
(continue-ability state side
(choose-handler
(remove-once #(same-card? target (:card %)) handlers))
nil event-targets)
(effect-completed state side eid)))))})))]
(continue-ability state side (choose-handler handlers) nil event-targets))
(effect-completed state side eid)))
(defn ability-as-handler
"Wraps a card ability as an event handler."
[card ability]
{:duration (or (:duration ability) :pending)
:card card
:ability ability})
(defn card-as-handler
"Wraps a card's definition as an event handler."
[card]
(let [{:keys [effect prompt choices psi optional trace] :as cdef} (card-def card)]
(when (or effect prompt choices psi optional trace)
(ability-as-handler card cdef))))
(defn effect-as-handler
"Wraps a five-argument function as an event handler."
[card effect]
(ability-as-handler card {:effect effect}))
(defn- event-title
"Gets a string describing the internal engine event keyword"
[event]
(if (keyword? event)
(name event)
(str event)))
(defn trigger-event-simult
"Triggers the given event by showing a prompt of all handlers for the event, allowing manual resolution of
simultaneous trigger handlers. effect-completed is fired once all registered event handlers have completed.
Parameters:
state, side: as usual
eid: the eid of the entire triggering sequence, which will be completed when all handlers are completed
event: the event keyword to trigger handlers for
first-ability: an ability map (fed to resolve-ability) that should be resolved after the list of handlers is determined
but before any of them is actually fired. Typically used for core rules that happen in the same window
as triggering handlers, such as trashing a corp Current when an agenda is stolen. Necessary for
interaction with New Angeles Sol and Employee Strike
card-ability: a card's ability that triggers at the same time as the event trigger, but is coded as a card ability
and not an event handler. (For example, :stolen on agendas happens in the same window as :agenda-stolen
after-active-player: an ability to resolve after the active player's triggers resolve, before the opponent's get to act
cancel-fn: a function that takes one argument (the state) and returns true if we should stop the event resolution
process, likely because an event handler caused a change to the game state that cancels future handlers.
(Film Critic)
targets: a varargs list of targets to the event, as usual"
[state side eid event {:keys [first-ability card-abilities after-active-player cancel-fn]} & targets]
(if (nil? event)
(effect-completed state side eid)
(do (log-event state event targets)
(let [active-player (:active-player @state)
opponent (other-side active-player)
is-player (fn [player ability]
(or (= player (get-side ability))
(= player (get-ability-side ability))))
card-abilities (if (and (some? card-abilities)
(not (sequential? card-abilities)))
[card-abilities]
card-abilities)
handlers (gather-events state side eid event targets card-abilities)
get-handlers (fn [player-side]
(filterv (partial is-player player-side) handlers))
active-player-events (get-handlers active-player)
opponent-events (get-handlers opponent)]
(wait-for (resolve-ability state side (make-eid state eid) first-ability nil nil)
(show-wait-prompt state opponent
(str (side-str active-player) " to resolve " (event-title event) " triggers")
{:priority -1})
; let active player activate their events first
(wait-for (trigger-event-simult-player state side (make-eid state eid) active-player-events cancel-fn targets)
(when after-active-player
(resolve-ability state side eid after-active-player nil nil))
(clear-wait-prompt state opponent)
(show-wait-prompt state active-player
(str (side-str opponent) " to resolve " (event-title event) " triggers")
{:priority -1})
(wait-for (trigger-event-simult-player state opponent (make-eid state eid) opponent-events cancel-fn targets)
(clear-wait-prompt state active-player)
(effect-completed state side eid))))))))
;; EVENT QUEUEING
(defn queue-event
([state event] (queue-event state event nil))
([state event context-map]
(when (keyword? event)
(swap! state update-in [:queued-events event] conj (assoc context-map :event event)))))
(defn make-pending-event
[state event card ability]
(let [ability {:event event
:duration :pending
:unregister-once-resolved true
:once-per-instance (or (:once-per-instance ability) false)
:ability ability
:card card
:uuid (uuid/v1)}]
(swap! state update :events conj ability)))
(defn- gather-queued-event-handlers
[state event-maps]
(for [[event context-maps] event-maps]
{:handlers (filterv #(= event (:event %)) (:events @state))
:context-maps (into [] context-maps)}))
(defn- create-instances
[{:keys [handlers context-maps]}]
(apply concat
(for [handler handlers]
(if (:once-per-instance handler)
[{:handler handler
:context context-maps}]
(for [context context-maps]
{:handler handler
:context [context]})))))
(defn- create-handlers
[state eid event-maps]
(->> (gather-queued-event-handlers state event-maps)
(mapcat create-instances)
(filter (fn [{:keys [handler context]}]
(let [card (card-for-ability state handler)
ability (:ability handler)]
(and (not (apply trigger-suppress state (to-keyword (:side card)) (:event handler) card context))
(can-trigger? state (to-keyword (:side card)) eid ability card context)))))
(sort-by (complement #(is-active-player state (:handler %))))
(seq)))
(defn- trigger-queued-event-player
[state side eid handlers {:keys [cancel-fn] :as args}]
(if (empty? handlers)
(effect-completed state nil eid)
(let [handlers (when-not (and cancel-fn (cancel-fn state))
(filter #(let [card (card-for-ability state (:handler %))]
(and card
(not (:disabled card))
(not (apply trigger-suppress state (to-keyword (:side card))
(get-in % [:handler :event]) card (:context %)))))
handlers))
non-silent (filter #(let [silent-fn (:silent (:ability (:handler %)))]
(not (and silent-fn
(silent-fn state side
(make-eid state eid)
(card-for-ability state (:handler %))
(:context %)))))
handlers)
titles (keep #(card-for-ability state (:handler %)) non-silent)
interactive (filter #(let [interactive-fn (:interactive (:ability (:handler %)))]
(and interactive-fn
(interactive-fn state side
(make-eid state eid)
(card-for-ability state (:handler %))
(:context %))))
handlers)]
(if (or (= 1 (count handlers))
(empty? interactive)
(= 1 (count non-silent)))
(let [handler (first handlers)
to-resolve (:handler handler)
ability (:ability to-resolve)
context (:context handler)
ability-card (card-for-ability state to-resolve)]
(if ability-card
(wait-for (resolve-ability state (to-keyword (:side ability-card))
(make-eid state (assoc eid :source ability-card :source-type :ability))
(dissoc-req ability)
ability-card
context)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(trigger-queued-event-player state side eid (rest handlers) args))
(trigger-queued-event-player state side eid (rest handlers) args)))
(continue-ability
state side
(when (pos? (count handlers))
{:async true
:prompt "Choose a trigger to resolve"
:choices titles
:effect (req (let [handler (some #(when (same-card? target (card-for-ability state (:handler %))) %) handlers)
to-resolve (:handler handler)
ability (:ability to-resolve)
context (:context handler)
ability-card (card-for-ability state to-resolve)]
(wait-for
(resolve-ability state (to-keyword (:side ability-card))
(make-eid state (assoc eid :source ability-card :source-type :ability))
(dissoc-req ability)
ability-card
context)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(let [handlers (remove-once #(same-card? target (card-for-ability state (:handler %))) handlers)]
(trigger-queued-event-player state side eid handlers args)))))})
nil nil)))))
(defn- is-player
[player {:keys [handler]}]
(or (= player (get-side handler))
(= player (get-ability-side handler))))
(defn- filter-handlers
[handlers player-side]
(filterv #(is-player player-side %) handlers))
(defn- mark-pending-abilities
[state eid args]
(let [event-maps (:queued-events @state)]
(doseq [[event context-map] event-maps]
(log-event state event context-map))
(when-not (empty? event-maps)
(let [handlers (create-handlers state eid event-maps)]
(swap! state assoc
:queued-events {}
:events (->> (:events @state)
(remove #(= :pending (:duration %)))
(into [])))
{:handlers handlers
:context-maps (apply concat (vals event-maps))}))))
(defn- trigger-pending-abilities
[state eid handlers args]
(if (seq handlers)
(let [active-player (:active-player @state)
opponent (other-side active-player)
active-player-handlers (filter-handlers handlers active-player)
opponent-handlers (filter-handlers handlers opponent)]
(show-wait-prompt state opponent (str (side-str active-player) " to resolve pending triggers"))
(wait-for (trigger-queued-event-player state active-player (make-eid state eid) active-player-handlers args)
(clear-wait-prompt state opponent)
(show-wait-prompt state active-player (str (side-str opponent) " to resolve pending triggers"))
(wait-for (trigger-queued-event-player state opponent (make-eid state eid) opponent-handlers args)
(clear-wait-prompt state active-player)
(effect-completed state nil eid))))
(effect-completed state nil eid)))
;; CHECKPOINT
(defn internal-trash-cards
[state _ eid maps]
(if (seq maps)
(let [{:keys [card value]} (first maps)]
(wait-for (value state nil (make-eid state eid) card)
(internal-trash-cards state nil eid (next maps))))
(effect-completed state nil eid)))
(defn trash-when-expired
[state _ eid context-maps]
(if (seq context-maps)
(->> context-maps
(get-effect-maps state nil eid :trash-when-expired)
(internal-trash-cards state nil eid))
(effect-completed state nil eid)))
(defn unregister-expired-durations
[state _ eid duration context-maps]
(wait-for (trash-when-expired state nil (make-eid state eid) context-maps)
(if duration
(unregister-floating-effects state nil duration)
(unregister-floating-events state nil duration))
(effect-completed state nil eid)))
(defn checkpoint
([state eid] (checkpoint state nil eid nil))
([state _ eid] (checkpoint state nil eid nil))
([state _ eid {:keys [duration] :as args}]
;; a: Any ability that has met its condition creates the appropriate instances of itself and marks them as pending
(let [{:keys [handlers context-maps]} (mark-pending-abilities state eid args)]
;; b: Any ability with a duration that has passed is removed from the game state
(wait-for
(unregister-expired-durations state nil (make-eid state eid) duration context-maps)
;; c: Check winning or tying by agenda points
(check-win-by-agenda state)
;; d: uniqueness check
;; unimplemented
;; e: restrictions on card abilities or game rules, MU
;; unimplemented
;; f: stuff on agendas moved from score zone
;; unimplemented
;; g: stuff on installed cards that were trashed
;; unimplemented
;; h: empty servers
(clear-empty-remotes state)
;; i: card counters/agendas become cards again
;; unimplemented
;; j: counters in discard are returned to the bank
;; unimplemented
;; 10.3.2: reaction window
(trigger-pending-abilities state eid handlers args)))))
(defn end-of-phase-checkpoint
([state _ eid event] (end-of-phase-checkpoint state nil eid event nil))
([state _ eid event context]
(when event
(queue-event state event context))
(checkpoint state nil eid {:duration event})))
;; PAYMENT
(defn- pay-next
[state side eid costs card actions msgs]
(if (empty? costs)
(complete-with-result state side eid msgs)
(wait-for (handler (first costs) state side (make-eid state eid) card actions)
(pay-next state side eid (rest costs) card actions (conj msgs async-result)))))
(defn- sentence-join
[strings]
(if (<= (count strings) 2)
(string/join " and " strings)
(str (apply str (interpose ", " (butlast strings))) ", and " (last strings))))
(defn pay
"Same as pay, but awaitable."
[state side eid card & args]
(let [args (flatten args)
raw-costs (remove map? args)
actions (filter map? args)]
(if-let [costs (can-pay? state side eid card (:title card) raw-costs)]
(wait-for (pay-next state side (make-eid state eid) costs card actions [])
(let [payment-result async-result]
(wait-for (checkpoint state nil (make-eid state eid) nil)
(complete-with-result
state side eid
{:msg (->> payment-result
(keep :msg)
sentence-join)
:cost-paid (->> payment-result
(keep #(not-empty (select-keys % [:type :targets :value])))
(reduce
(fn [acc cost]
(assoc acc (:type cost) cost))
{}))}))))
(complete-with-result state side eid nil))))
| true |
(ns game.core.engine
(:require
[clojure.set :as clj-set]
[clojure.stacktrace :refer [print-stack-trace]]
[clojure.string :as string]
[clj-uuid :as uuid]
[game.core.board :refer [clear-empty-remotes]]
[game.core.card :refer [active? facedown? get-card get-cid has-subtype? installed? rezzed?]]
[game.core.card-defs :refer [card-def]]
[game.core.effects :refer [any-effects effect-pred get-effect-maps unregister-floating-effects]]
[game.core.eid :refer [complete-with-result effect-completed make-eid]]
[game.core.payment :refer [build-spend-msg can-pay? merge-costs handler]]
[game.core.prompt-state :refer [add-to-prompt-queue]]
[game.core.prompts :refer [clear-wait-prompt show-prompt show-select show-wait-prompt]]
[game.core.say :refer [system-msg]]
[game.core.update :refer [update!]]
[game.core.winning :refer [check-win-by-agenda]]
[game.macros :refer [continue-ability req wait-for]]
[game.utils :refer [dissoc-in distinct-by in-coll? server-cards remove-once same-card? side-str to-keyword]]
[jinteki.utils :refer [other-side]]))
;; resolve-ability docs
; Perhaps the most important function in the game logic.
; Resolves an ability defined by the given ability map. Checks :req functions; shows prompts, psi games,
; traces, etc. as needed; charges costs; invokes :effect functions. All card effects and most engine effects
; should run through this method. Unless noted, every key listed is optional.
; How to read this:
; :key -- type
; Description, reasoning, expected return value, etc.
; Types:
; integer, string, keyword: clojure literals
; boolean: clojure literal, but should generally only be true (as leaving it off counts as false)
; vector: can be a literal [] or '(), can also be the return value of a function, but
; must not be a function definition that returns a vector or list
; map of X: clojure literal. X is a comma-separated list of allowed keys.
; The description will be laid out recursively, and keys will be marked as required or optional.
; ability map: an ability map as defined here.
; enum: a comma-separated list of values, one of which can be used.
; 5-fn: typically (req), but any function definition that takes state, side, eid, card, targets.
; Something that accepts different types will have the types separated by "or".
; For example, "string or 5-fn" means it accepts a string or a 5-fn. The description will
; say what the 5-fn should return, if anything.
; COMMON KEYS
; :req -- 5-fn
; Must return true or false. If false, the ability will not be resolved.
; :cost -- vector
; A vector of cost pairs to charge, for example [:credit 1 :click 1].
; If the costs cannot be paid, the ability will not be resolved.
; :msg -- string or 5-fn.
; Must return a string. (`msg` is expressly built for this.)
; Prints to the log when the ability is finished. Will be used as the :label if no :label is provided.
; The output is written as:
; (with cost) "{Player} pays {X} to use {card title} to {msg result}."
; (with no cost) "{Player} uses {card title} to {msg result}."
; so the returned string should always be written imperatively.
; :label -- string
; If this ability is in an :abilities map on a card, the label will be prepended with a string
; of the costs, and both will be displayed in the ability button. If this is not defined
; and a label is needed, :msg will be used if it is a string.
; :effect -- 5-fn
; Will be called if the ability will be resolved (if :req is true or not present,
; costs can be paid, and any prompts are resolved).
; :player -- enum: :corp, :runner
; Manually specifies which player the ability should affect, rather than leave it implicit.
; :async -- boolean
; Mark the ability as "async", meaning the :effect function must call effect-completed itself.
; Without this being set to true, resolve-ability will call effect-completed once it's done.
; This part of the engine is really dumb and complicated, so ask someone on slack about it.
; :cost-req -- 1-fn
; A function which will be applied to the cost of an ability immediatly prior to being paid. See all-stealth or min-stealth for examples.
; PROMPT KEYS
; :prompt -- string or 5-fn
; Must return a string to display in the prompt menu.
; :choices -- 5-fn or :credit or :counter or map
; This key signals a prompt of some kind. (It should be split into multiple keys, but that's a lot of work lol)
; * 5-fn
; Must return a vector of card objects or strings.
; User chooses one. This is called a 'choice' prompt.
; * :credit
; User chooses an integer up to their current credit amount.
; * :counter
; User chooses an integer up to the :counter value of the current card.
; * map of :number, :default
; User chooses an integer between 0 and some number
; :number -- 5-fn
; Required. Must return a number, which is the maximum allowed.
; :default -- 5-fn
; Optional. Must return a number, which is the number the dropdown will display initially.
; * map of :card or :req, :all, :max, :not-self
; Triggers a 'select' prompt with targeting cursor for "selecting" one or more cards.
; :card -- 1-argument function
; Either this or :req is required, but not both.
; Accepts a single card object, must return true or false to indicate if selection is successful.
; :req -- 5-fn
; Either this or :card is required, but not both.
; "target" is the clicked card. Must return true or false to indicate if selection is successful.
; :all -- boolean
; Optional. Changes the select prompt from optional (can click "Done" to not select anything) to
; mandatory. When :max is also set to true, enforces selecting the specified number of cards.
; :max -- integer
; Optional. Changes the select from to resolving after selecting a single card to
; resolving when either a number of cards (as set by :max) have been selected or a number
; of cards less than that set by :max are selected and the "Done" button has been clicked.
; When :all is also set to true, enforces selecting the specified number of cards.
; :not-self -- boolean
; Certain abilities can target any card on the table, others can only target other cards.
; For example, Yusuf vs Aesop's. Setting this is the same as adding
; `(not (same-card? % card))` to your :card function or `(not (same-card? target card))`
; to your :req function.
; :not-distinct -- boolean
; By default, duplicate entries of the same string will be combined into a single button.
; If set to true, duplicate entries of the same string will be shown as multiple buttons.
; :cancel-effect -- 5-fn
; If a prompt with the choice "Cancel" is clicked, the prompt exits without doing anything else
; and this function will be called.
; SIMULTANEOUS EFFECT RESOLUTION KEYS
; :interactive -- 5-fn. when simultaneous effect resolution has been enabled for a specific event, the user receives
; a menu of cards that handle the effect and get to choose the order of their resolution. This menu is
; only shown if at least one ability handling the event has an :interactive function that returns true.
; If none are interactive, then all handlers will be resolved automatically, one at a time in an
; arbitrary order. In general, handlers should be marked ':interactive (req true)' if they have
; important order-of-effect interactions with other cards. The :interactive function can be coded to
; have smarter logic if necessary -- see Replicator, which is only interactive if there is another
; copy of the installed card remaining in the Stack.
; :silent -- any handler that does not require user interaction under any circumstances can be marked :silent. If a
; handler's :silent function returns true, then no menu entry will be shown for the handler. In that case,
; the ability will only be resolved once all non-silent abilities are resolved. Example: AstroScript has no
; important interactions with other 'agenda scored' effects, and doesn't care when an agenda token is placed.
; Example: PI:NAME:<NAME>END_PI will not show a prompt if there are no valid targets in the grip.
; OTHER KEYS
; :once -- either :per-turn or :per-run. signifies an effect that can only be triggered once per turn.
; :once-key -- keyword. by default, each :once is distinct per card. If multiple copies of a card can only resolve
; some ability once between all of them, then the card should specify a manual :once-key that can
; be any value, preferrably a unique keyword.
; :install-req -- a function which returns a list of servers a card may be installed into
; :makes-run -- boolean. indicates if the ability makes a run.
; COMPLEX ABILITY WRAPPERS
; These are wrappers around more complex/cumbersome functionality. They all call into a flow that would
; be cumbersome to write out every time in a "normal" ability map.
; :psi -- map of :req, :equal, :not-equal
; Handles psi games.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :equal -- ability map
; At least one of :equal and :not-equal are required.
; Async ability that is executed if the players reveal the same number of credits.
; :not-equal -- ability map
; At least one of :equal and :not-equal are required.
; Async ability that is executed if the players reveal the a differen number of credits.
; :trace -- map of :req, :label, :base, :successful, :unsuccessful, :kicker, :kicker-min
; Handles traces.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :label -- 5-fn
; Optional. Works same as :label in an ability map.
; :base -- integer or 5-fn
; Required. Must return an integer, which sets the "base" initial value for the trace.
; :successful -- ability map
; At least one of :successful and :unsuccessful are required.
; Async ability that is executed if the trace is successful.
; :unsuccessful -- ability map
; At least one of :successful and :unsuccessful are required.
; Async ability that is executed if the trace is unsuccessful.
; :kicker -- ability map
; Optional. Async ability that is executed if the corp's trace strength is equal to or greater
; than :kicker-min.
; :kicker-min -- integer
; Required if :kicker is defined. The number the corp's strength must be equal to or greater
; to execute the :kicker ability.
; :optional -- map of :req, :prompt, :player, :yes-ability, :no-ability, :end-effect, :autoresolve
; Shows a "Yes/No" prompt to handle the user deciding whether to resolve the ability.
; :req -- 5-fn
; Optional. Works same as :req in an ability map.
; :prompt -- string or 5-fn
; Required. Must return a string to display in the prompt menu.
; :player -- enum: :corp, :runner
; Optional. Hardcodes which player will resolve this prompt.
; :yes-ability -- ability-map
; At least one of :yes-ability and :no-ability are required. (Normally, this should always
; be defined, but sometimes it's easier to word things in the negative, such that only
; defining :no-ability is the most natural way to write the ability.)
; Async ability that is executed if "Yes" is chosen.
; :no-ability -- ability-map
; At least one of :yes-ability and :no-ability are required. (See note above.)
; Async ability that is executed if "No" is chosen, or if "Yes" is chosen but there's
; no :yes-ability defined, or :yes-ability has a :cost that the player can't afford.
; :end-effect -- 5-fn
; Called after :yes- or :no-ability has been resolved.
; Must not be async as it is not awaited.
; :autoresolve -- 5-fn
; Optional. Used to set an optional prompt to either ask, always choose "Yes", or always choose "No".
; Must use the (get-autoresolve kw) helper function, where kw is an ability-specific
; keyword that will be stored in the card's [:special] map.
; Must use the (set-autoresolve kw) helper function in the card's :abilities vector,
; to allow for changing the autoresolve settings, where kw is the same keyword as used in
; the (get-autoresolve kw) call.
(declare do-ability resolve-ability-eid check-ability pay prompt! check-choices do-choices)
(def ability-types (atom {}))
(defn register-ability-type
[kw ability-fn]
(swap! ability-types assoc kw ability-fn))
(defn select-ability-kw
[ability]
(first (keys (select-keys ability (keys @ability-types)))))
(defn dissoc-req
[ability]
(if-let [ab (select-ability-kw ability)]
(dissoc-in ability [ab :req])
(dissoc ability :req)))
(defn should-trigger?
"Checks if the specified ability definition should trigger.
Checks for a :req, either in the top level map, or in an :optional or :psi sub-map
Returns true if no :req found, returns nil if the supplied ability is nil"
([state side eid card targets {:keys [req] :as ability}]
(when ability
(let [ab (select-ability-kw ability)]
(cond
ab (should-trigger? state side eid card targets (get ability ab))
req (req state side eid card targets)
:else true)))))
(defn not-used-once?
[state {:keys [once once-key]} {:keys [cid]}]
(if once
(not (get-in @state [once (or once-key cid)]))
true))
(defn can-trigger?
"Checks if ability can trigger. Checks that once-per-turn is not violated."
[state side eid ability card targets]
(and (not-used-once? state ability card)
(should-trigger? state side eid card targets ability)))
(defn is-ability?
"Checks to see if a given map represents a card ability."
[{:keys [effect msg]}]
(or effect msg (seq (keys @ability-types))))
(defn resolve-ability
([state side {:keys [eid] :as ability} card targets]
(resolve-ability state side (or eid (make-eid state {:source card :source-type :ability})) ability card targets))
([state side eid ability card targets]
(resolve-ability-eid state side (assoc ability :eid eid) card targets)))
(defn- resolve-ability-eid
[state side {:keys [eid choices] :as ability} card targets]
(cond
;; Only has the eid, in effect a nil ability
(and eid (= 1 (count ability)))
(effect-completed state side eid)
;; This was called directly without an eid present
(and ability (not eid))
(resolve-ability-eid state side (assoc ability :eid (make-eid state eid)) card targets)
;; Both ability and eid are present, so we're good to go
(and ability eid)
(let [ab (select-ability-kw ability)
ability-fn (get @ability-types ab)]
(cond
ab (ability-fn state side ability card targets)
choices (check-choices state side ability card targets)
:else (check-ability state side ability card targets)))
;; Something has gone terribly wrong, error out
:else
(.println *err* (with-out-str
(print-stack-trace
(Exception. (str "Ability is nil????" ability card targets))
2500)))))
;;; Checking functions for resolve-ability
(defn- check-choices
[state side {:keys [eid] :as ability} card targets]
(if (can-trigger? state side eid ability card targets)
(do-choices state side ability card targets)
(effect-completed state side eid)))
(defn- check-ability
[state side {:keys [eid] :as ability} card targets]
(if (can-trigger? state side eid ability card targets)
(do-ability state side ability card targets)
(effect-completed state side eid)))
(defn- print-msg
"Prints the ability message"
[state side {:keys [eid] :as ability} card targets payment-str]
(when-let [message (:msg ability)]
(let [desc (if (string? message) message (message state side eid card targets))
cost-spend-msg (build-spend-msg payment-str "use")]
(system-msg state (to-keyword (:side card))
(str cost-spend-msg (:title card) (str " to " desc))))))
(defn register-once
"Register ability as having happened if :once specified"
[state _ {:keys [once once-key]} {:keys [cid]}]
(when once
(swap! state assoc-in [once (or once-key cid)] true)))
(defn- do-effect
"Trigger the effect"
[state side {:keys [eid] :as ability} card targets]
(if-let [ability-effect (:effect ability)]
(ability-effect state side eid card targets)
(effect-completed state side eid)))
(defn- ugly-counter-hack
"This is brought over from the old do-ability because using `get-card` or `find-latest`
currently doesn't work properly with `pay-counters`"
[card cost]
;; TODO: Remove me some day
(let [[counter-type counter-amount]
(->> cost
(remove map?)
merge-costs
(filter #(some #{:advancement :agenda :power :virus} %))
first)]
(if counter-type
(let [counter (if (= :advancement counter-type)
[:advance-counter]
[:counter counter-type])]
(update-in card counter - counter-amount))
card)))
(declare checkpoint)
(defn merge-costs-paid
([cost-paid]
(into {} (map (fn [[k {:keys [type value targets]}]]
[k {:type type
:value value
:targets targets}])
cost-paid)))
([cost-paid1 cost-paid2]
(let [costs-paid [cost-paid1 cost-paid2]
cost-keys (mapcat keys costs-paid)]
(reduce (fn [acc cur]
(let [costs (map cur costs-paid)
cost-obj {:type cur
:value (apply + (keep :value costs))
:targets (seq (apply concat (keep :targets costs)))}]
(assoc acc cur cost-obj)))
{}
cost-keys)))
([cost-paid1 cost-paid2 & costs-paid]
(reduce merge-costs-paid (merge-costs-paid cost-paid1 cost-paid2) costs-paid)))
(defn- do-ability
"Perform the ability, checking all costs can be paid etc."
[state side {:keys [async eid cost player waiting-prompt] :as ability} card targets]
(when waiting-prompt
(add-to-prompt-queue
state (cond
player (if (= :corp player) :runner :corp)
(= :corp side) :runner
:else :corp)
{:eid (select-keys eid [:eid])
:card card
:prompt-type :waiting
:msg (str "Waiting for " waiting-prompt)}))
;; Ensure that any costs can be paid
(wait-for (pay state side (make-eid state eid) card cost {:action (:cid card)})
;; If the cost can be and is paid, perform the ablity
(let [payment-str (:msg async-result)
cost-paid (merge-costs-paid (:cost-paid eid) (:cost-paid async-result))]
(if payment-str
(wait-for (checkpoint state side (make-eid state eid) nil)
(let [ability (assoc-in ability [:eid :cost-paid] cost-paid)]
;; Print the message
(print-msg state side ability card targets payment-str)
;; Trigger the effect
(register-once state side ability card)
(do-effect state side ability (ugly-counter-hack card cost) targets)
;; If the ability isn't async, complete it
(when-not async
(effect-completed state side eid))))
(effect-completed state side eid)))))
(defn- do-choices
"Handle a choices ability"
[state side {:keys [choices eid not-distinct player prompt] :as ability} card targets]
(let [s (or player side)
ab (dissoc ability :choices :waiting-prompt)
args (-> ability
(select-keys [:priority :cancel-effect :prompt-type :show-discard :end-effect :waiting-prompt])
(assoc :targets targets))]
(if (map? choices)
;; Two types of choices use maps: select prompts, and :number prompts.
(cond
;; a counter prompt
(:counter choices)
(prompt! state s card prompt choices ab args)
;; a select prompt
(or (:req choices)
(:card choices))
(show-select state s card ability update! resolve-ability args)
;; a :number prompt
(:number choices)
(let [n ((:number choices) state side eid card targets)
d (if-let [dfunc (:default choices)]
(dfunc state side (make-eid state eid) card targets)
0)]
(prompt! state s card prompt {:number n :default d} ab args))
(:card-title choices)
(let [card-titles (sort (map :title (filter #((:card-title choices) state side (make-eid state eid) nil [%])
(server-cards))))
choices (assoc choices :autocomplete card-titles)
args (assoc args :prompt-type :card-title)]
(prompt! state s card prompt choices ab args))
;; unknown choice
:else nil)
;; Not a map; either :credit, :counter, or a vector of cards or strings.
(let [cs (if-not (fn? choices)
choices ; :credit or :counter
(let [cards (choices state side eid card targets)] ; a vector of cards or strings
(if not-distinct cards (distinct-by :title cards))))]
(prompt! state s card prompt cs ab args)))))
;;; Prompts
(defn prompt!
"Shows a prompt with the given message and choices. The given ability will be resolved
when the user resolves the prompt. Cards should generally not call this function directly; they
should use resolve-ability to resolve a map containing prompt data.
Please refer to the documentation at the top of resolve_ability.clj for a full description."
([state side card message choices ability] (prompt! state side card message choices ability nil))
([state side card message choices ability args]
(let [f #(resolve-ability state side ability card [%])]
(show-prompt state side (:eid ability) card message choices f
(if-let [f (:cancel-effect args)]
(assoc args :cancel-effect #(f state side (:eid ability) card [%]))
args)))))
;; EVENTS
; Functions for registering trigger suppression events
(defn register-suppress
"Registers each suppression handler in the given card definition. Suppression handlers
can prevent the dispatching of a particular event."
([state side card] (register-suppress state side card (:suppress (card-def card))))
([state _ card events]
(when events
(let [abilities
(->> (for [ability events]
{:event (:event ability)
:ability (dissoc ability :event)
:card card
:uuid (uuid/v1)})
(into []))]
(when (seq abilities)
(swap! state update :suppress #(apply conj % abilities)))
abilities))))
(defn unregister-suppress
"Removes all event handler suppression effects as defined for the given card"
([state side card] (unregister-suppress state side card (:suppress (card-def card))))
([state _ card events]
(let [abilities (map :event events)]
(swap! state assoc :suppress
(->> (:suppress @state)
(remove #(and (same-card? card (:card %))
(in-coll? abilities (:event %))))
(into []))))))
(defn unregister-suppress-by-uuid
"Removes a single event handler with matching uuid"
[state _ uuid]
(swap! state assoc :suppress (remove-once #(= uuid (:uuid %)) (:suppress @state))))
(defn- default-locations
[card]
(case (to-keyword (:type card))
:agenda #{:scored}
(:asset :ice :upgrade) #{:servers}
(:event :operation) #{:current :play-area}
(:hardware :program :resource) #{:rig}
(:identity :fake-identity) #{:identity}))
; Functions for registering and dispatching events.
(defn register-events
"Registers each event handler defined in the given card definition.
Also registers any suppression events."
([state side card] (register-events state side card nil))
([state side card events]
(let [events (or (seq events) (remove :location (:events (card-def card))))
abilities
(->> (for [ability events]
{:event (:event ability)
:location (let [location (:location ability)]
(cond
(or (list? location)
(vector? location))
(into #{} location)
(keyword? location)
#{location}
:else
(default-locations card)))
:duration (or (:duration ability) :while-installed)
:condition (or (:condition ability) :active)
:unregister-once-resolved (or (:unregister-once-resolved ability) false)
:once-per-instance (or (:once-per-instance ability) false)
:ability (dissoc ability :event :duration :condition)
:card card
:uuid (uuid/v1)})
(into []))]
(when (seq abilities)
(swap! state update :events #(apply conj % abilities)))
(register-suppress state side card)
abilities)))
(defn unregister-events
"Removes all event handlers defined for the given card.
Optionally input a partial card-definition map to remove only some handlers"
([state side card] (unregister-events state side card nil))
([state side card cdef]
;; Combine normal events and derezzed events. Any merge conflicts should not matter
;; as they should cause all relevant events to be removed anyway.
(let [events (or (seq (concat (:events cdef) (:derezzed-events cdef)))
(let [cdef (card-def card)]
(remove :location (concat (:events cdef) (:derezzed-events cdef)))))
abilities (map :event events)]
(swap! state assoc :events
(->> (:events @state)
(remove #(and (same-card? card (:card %))
(in-coll? abilities (:event %))
(= :while-installed (:duration %))))
(into [])))
(unregister-suppress state side card))))
(defn unregister-floating-events
"Removes all event handlers with a non-persistent duration"
[state _ duration]
(when (not= :while-installed duration)
(swap! state assoc :events
(->> (:events @state)
(remove #(= duration (:duration %)))
(into [])))))
(defn unregister-floating-events-for-card
"Removes all event handlers with a non-persistent duration on a single card"
[state _ card duration]
(swap! state assoc :events
(->> (:events @state)
(remove #(and (same-card? card (:card %))
(= duration (:duration %))))
(into []))))
(defn unregister-event-by-uuid
"Removes a single event handler with matching uuid"
[state _ uuid]
(swap! state assoc :events (remove-once #(= uuid (:uuid %)) (:events @state))))
;; triggering events
(defn- get-side
[ability]
(to-keyword (get-in ability [:card :side])))
(defn- get-ability-side
[ability]
(get-in ability [:ability :side]))
(defn- is-active-player
[state ability]
(= (:active-player @state) (get-side ability)))
(defn- card-for-ability
[state ability]
(if (#{:while-installed :pending} (:duration ability))
(when-let [card (get-card state (:card ability))]
(if (and (= :while-installed (:duration ability))
(not-empty
(clj-set/intersection (:location ability) (default-locations card))))
(case (:condition ability)
:active
(when (active? card)
card)
:facedown
(when (and (installed? card)
(facedown? card))
card)
:derezzed
(when (and (installed? card)
(not (rezzed? card)))
card)
:hosted
(when (:host card)
card)
; else
nil)
card))
(:card ability)))
(defn trigger-suppress
"Returns true if the given event on the given targets should be suppressed, by triggering
each suppression handler and returning true if any suppression handler returns true."
[state side event & targets]
(->> (:suppress @state)
(filter #(= event (:event %)))
(some #((:req (:ability %)) state side (make-eid state) (card-for-ability state %) targets))))
(defn gather-events
"Prepare the list of the given player's handlers for this event.
Gather all registered handlers from the state, then append the card-abilities if appropriate,
then filter to remove suppressed handlers and those whose req is false.
This is essentially Phase 9.3 and 9.6.7a of CR 1.1:
http://nisei.net/files/Comprehensive_Rules_1.1.pdf"
([state side event targets] (gather-events state side event targets nil))
([state side event targets card-abilities] (gather-events state side (make-eid state) event targets nil))
([state side eid event targets card-abilities]
(->> (:events @state)
(filter #(= event (:event %)))
(concat card-abilities)
(filter identity)
(filter (fn [ability]
(let [card (card-for-ability state ability)]
(and (not (apply trigger-suppress state side event card targets))
(can-trigger? state side eid (:ability ability) card targets)))))
(sort-by (complement #(is-active-player state %)))
doall)))
(defn- log-event
[state event targets]
(swap! state update :turn-events #(cons [event targets] %))
(when (:run @state)
(swap! state update-in [:run :events] #(cons [event targets] %))))
(defn trigger-event
"Resolves all abilities registered as handlers for the given event key, passing them
the targets given."
[state side event & targets]
(when (some? event)
(log-event state event targets)
(let [handlers (gather-events state side event targets)]
(doseq [to-resolve handlers]
(when-let [card (card-for-ability state to-resolve)]
(resolve-ability state side (dissoc-req (:ability to-resolve)) card targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve))))))))
(defn- trigger-event-sync-next
[state side eid handlers event targets]
(if-let [to-resolve (first handlers)]
(if-let [card (card-for-ability state to-resolve)]
(wait-for (resolve-ability state side (make-eid state (assoc eid :source card :source-type :ability)) (dissoc-req (:ability to-resolve)) card targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(trigger-event-sync-next state side eid (rest handlers) event targets))
(trigger-event-sync-next state side eid (rest handlers) event targets))
(effect-completed state side eid)))
(defn trigger-event-sync
"Triggers the given event synchronously, requiring each handler to complete before alerting the next handler. Does not
give the user a choice of what order to resolve handlers."
[state side eid event & targets]
(if (nil? event)
(effect-completed state side eid)
(do (log-event state event targets)
(let [handlers (gather-events state side eid event targets nil)]
(trigger-event-sync-next state side eid handlers event targets)))))
(defn- trigger-event-simult-player
"Triggers the simultaneous event handlers for the given event trigger and player.
If none of the handlers require interaction, then they are all resolved automatically, each waiting for the previous
to fully resolve as in trigger-event-sync. If at least one requires interaction, then a menu is shown to manually
choose the order of resolution.
:silent abilities are not shown in the list of handlers, and are resolved last in an arbitrary order."
[state side eid handlers cancel-fn event-targets]
(if (not-empty handlers)
(letfn [;; Allow resolution as long as there is no cancel-fn, or if the cancel-fn returns false.
(should-continue [state handlers]
(and (< 1 (count handlers))
(not (and cancel-fn (cancel-fn state)))))
(choose-handler [handlers]
(let [handlers (when-not (and cancel-fn (cancel-fn state))
(filter #(and (card-for-ability state %)
(not (:disabled (card-for-ability state %))))
handlers))
non-silent (filter #(let [silent-fn (:silent (:ability %))
card (card-for-ability state %)]
(not (and silent-fn
(silent-fn state side (make-eid state) card event-targets))))
handlers)
titles (map :card non-silent)
interactive (filter #(let [interactive-fn (:interactive (:ability %))
card (card-for-ability state %)]
(and interactive-fn
(interactive-fn state side (make-eid state) card event-targets)))
handlers)]
;; If there is only 1 non-silent ability, resolve that then recurse on the rest
(if (or (= 1 (count handlers)) (empty? interactive) (= 1 (count non-silent)))
(let [to-resolve (if (= 1 (count non-silent))
(first non-silent)
(first handlers))
ability-to-resolve (dissoc-req (:ability to-resolve))
others (if (= 1 (count non-silent))
(remove-once #(= (get-cid to-resolve) (get-cid %)) handlers)
(rest handlers))]
(if-let [the-card (card-for-ability state to-resolve)]
{:async true
:effect (req (wait-for (resolve-ability state (to-keyword (:side the-card))
(make-eid state (assoc eid :source the-card :source-type :ability))
ability-to-resolve
the-card event-targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(if (should-continue state handlers)
(continue-ability state side
(choose-handler others) nil event-targets)
(effect-completed state side eid))))}
{:async true
:effect (req (if (should-continue state handlers)
(continue-ability state side (choose-handler (rest handlers)) nil event-targets)
(effect-completed state side eid)))}))
{:prompt "Choose a trigger to resolve"
:choices titles
:async true
:effect (req (let [to-resolve (some #(when (same-card? target (:card %)) %) handlers)
ability-to-resolve (dissoc-req (:ability to-resolve))
the-card (card-for-ability state to-resolve)]
(wait-for
(resolve-ability state (to-keyword (:side the-card))
(make-eid state (assoc eid :source the-card :source-type :ability))
ability-to-resolve the-card event-targets)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(if (should-continue state handlers)
(continue-ability state side
(choose-handler
(remove-once #(same-card? target (:card %)) handlers))
nil event-targets)
(effect-completed state side eid)))))})))]
(continue-ability state side (choose-handler handlers) nil event-targets))
(effect-completed state side eid)))
(defn ability-as-handler
"Wraps a card ability as an event handler."
[card ability]
{:duration (or (:duration ability) :pending)
:card card
:ability ability})
(defn card-as-handler
"Wraps a card's definition as an event handler."
[card]
(let [{:keys [effect prompt choices psi optional trace] :as cdef} (card-def card)]
(when (or effect prompt choices psi optional trace)
(ability-as-handler card cdef))))
(defn effect-as-handler
"Wraps a five-argument function as an event handler."
[card effect]
(ability-as-handler card {:effect effect}))
(defn- event-title
"Gets a string describing the internal engine event keyword"
[event]
(if (keyword? event)
(name event)
(str event)))
(defn trigger-event-simult
"Triggers the given event by showing a prompt of all handlers for the event, allowing manual resolution of
simultaneous trigger handlers. effect-completed is fired once all registered event handlers have completed.
Parameters:
state, side: as usual
eid: the eid of the entire triggering sequence, which will be completed when all handlers are completed
event: the event keyword to trigger handlers for
first-ability: an ability map (fed to resolve-ability) that should be resolved after the list of handlers is determined
but before any of them is actually fired. Typically used for core rules that happen in the same window
as triggering handlers, such as trashing a corp Current when an agenda is stolen. Necessary for
interaction with New Angeles Sol and Employee Strike
card-ability: a card's ability that triggers at the same time as the event trigger, but is coded as a card ability
and not an event handler. (For example, :stolen on agendas happens in the same window as :agenda-stolen
after-active-player: an ability to resolve after the active player's triggers resolve, before the opponent's get to act
cancel-fn: a function that takes one argument (the state) and returns true if we should stop the event resolution
process, likely because an event handler caused a change to the game state that cancels future handlers.
(Film Critic)
targets: a varargs list of targets to the event, as usual"
[state side eid event {:keys [first-ability card-abilities after-active-player cancel-fn]} & targets]
(if (nil? event)
(effect-completed state side eid)
(do (log-event state event targets)
(let [active-player (:active-player @state)
opponent (other-side active-player)
is-player (fn [player ability]
(or (= player (get-side ability))
(= player (get-ability-side ability))))
card-abilities (if (and (some? card-abilities)
(not (sequential? card-abilities)))
[card-abilities]
card-abilities)
handlers (gather-events state side eid event targets card-abilities)
get-handlers (fn [player-side]
(filterv (partial is-player player-side) handlers))
active-player-events (get-handlers active-player)
opponent-events (get-handlers opponent)]
(wait-for (resolve-ability state side (make-eid state eid) first-ability nil nil)
(show-wait-prompt state opponent
(str (side-str active-player) " to resolve " (event-title event) " triggers")
{:priority -1})
; let active player activate their events first
(wait-for (trigger-event-simult-player state side (make-eid state eid) active-player-events cancel-fn targets)
(when after-active-player
(resolve-ability state side eid after-active-player nil nil))
(clear-wait-prompt state opponent)
(show-wait-prompt state active-player
(str (side-str opponent) " to resolve " (event-title event) " triggers")
{:priority -1})
(wait-for (trigger-event-simult-player state opponent (make-eid state eid) opponent-events cancel-fn targets)
(clear-wait-prompt state active-player)
(effect-completed state side eid))))))))
;; EVENT QUEUEING
(defn queue-event
([state event] (queue-event state event nil))
([state event context-map]
(when (keyword? event)
(swap! state update-in [:queued-events event] conj (assoc context-map :event event)))))
(defn make-pending-event
[state event card ability]
(let [ability {:event event
:duration :pending
:unregister-once-resolved true
:once-per-instance (or (:once-per-instance ability) false)
:ability ability
:card card
:uuid (uuid/v1)}]
(swap! state update :events conj ability)))
(defn- gather-queued-event-handlers
[state event-maps]
(for [[event context-maps] event-maps]
{:handlers (filterv #(= event (:event %)) (:events @state))
:context-maps (into [] context-maps)}))
(defn- create-instances
[{:keys [handlers context-maps]}]
(apply concat
(for [handler handlers]
(if (:once-per-instance handler)
[{:handler handler
:context context-maps}]
(for [context context-maps]
{:handler handler
:context [context]})))))
(defn- create-handlers
[state eid event-maps]
(->> (gather-queued-event-handlers state event-maps)
(mapcat create-instances)
(filter (fn [{:keys [handler context]}]
(let [card (card-for-ability state handler)
ability (:ability handler)]
(and (not (apply trigger-suppress state (to-keyword (:side card)) (:event handler) card context))
(can-trigger? state (to-keyword (:side card)) eid ability card context)))))
(sort-by (complement #(is-active-player state (:handler %))))
(seq)))
(defn- trigger-queued-event-player
[state side eid handlers {:keys [cancel-fn] :as args}]
(if (empty? handlers)
(effect-completed state nil eid)
(let [handlers (when-not (and cancel-fn (cancel-fn state))
(filter #(let [card (card-for-ability state (:handler %))]
(and card
(not (:disabled card))
(not (apply trigger-suppress state (to-keyword (:side card))
(get-in % [:handler :event]) card (:context %)))))
handlers))
non-silent (filter #(let [silent-fn (:silent (:ability (:handler %)))]
(not (and silent-fn
(silent-fn state side
(make-eid state eid)
(card-for-ability state (:handler %))
(:context %)))))
handlers)
titles (keep #(card-for-ability state (:handler %)) non-silent)
interactive (filter #(let [interactive-fn (:interactive (:ability (:handler %)))]
(and interactive-fn
(interactive-fn state side
(make-eid state eid)
(card-for-ability state (:handler %))
(:context %))))
handlers)]
(if (or (= 1 (count handlers))
(empty? interactive)
(= 1 (count non-silent)))
(let [handler (first handlers)
to-resolve (:handler handler)
ability (:ability to-resolve)
context (:context handler)
ability-card (card-for-ability state to-resolve)]
(if ability-card
(wait-for (resolve-ability state (to-keyword (:side ability-card))
(make-eid state (assoc eid :source ability-card :source-type :ability))
(dissoc-req ability)
ability-card
context)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(trigger-queued-event-player state side eid (rest handlers) args))
(trigger-queued-event-player state side eid (rest handlers) args)))
(continue-ability
state side
(when (pos? (count handlers))
{:async true
:prompt "Choose a trigger to resolve"
:choices titles
:effect (req (let [handler (some #(when (same-card? target (card-for-ability state (:handler %))) %) handlers)
to-resolve (:handler handler)
ability (:ability to-resolve)
context (:context handler)
ability-card (card-for-ability state to-resolve)]
(wait-for
(resolve-ability state (to-keyword (:side ability-card))
(make-eid state (assoc eid :source ability-card :source-type :ability))
(dissoc-req ability)
ability-card
context)
(when (:unregister-once-resolved to-resolve)
(unregister-event-by-uuid state side (:uuid to-resolve)))
(let [handlers (remove-once #(same-card? target (card-for-ability state (:handler %))) handlers)]
(trigger-queued-event-player state side eid handlers args)))))})
nil nil)))))
(defn- is-player
[player {:keys [handler]}]
(or (= player (get-side handler))
(= player (get-ability-side handler))))
(defn- filter-handlers
[handlers player-side]
(filterv #(is-player player-side %) handlers))
(defn- mark-pending-abilities
[state eid args]
(let [event-maps (:queued-events @state)]
(doseq [[event context-map] event-maps]
(log-event state event context-map))
(when-not (empty? event-maps)
(let [handlers (create-handlers state eid event-maps)]
(swap! state assoc
:queued-events {}
:events (->> (:events @state)
(remove #(= :pending (:duration %)))
(into [])))
{:handlers handlers
:context-maps (apply concat (vals event-maps))}))))
(defn- trigger-pending-abilities
[state eid handlers args]
(if (seq handlers)
(let [active-player (:active-player @state)
opponent (other-side active-player)
active-player-handlers (filter-handlers handlers active-player)
opponent-handlers (filter-handlers handlers opponent)]
(show-wait-prompt state opponent (str (side-str active-player) " to resolve pending triggers"))
(wait-for (trigger-queued-event-player state active-player (make-eid state eid) active-player-handlers args)
(clear-wait-prompt state opponent)
(show-wait-prompt state active-player (str (side-str opponent) " to resolve pending triggers"))
(wait-for (trigger-queued-event-player state opponent (make-eid state eid) opponent-handlers args)
(clear-wait-prompt state active-player)
(effect-completed state nil eid))))
(effect-completed state nil eid)))
;; CHECKPOINT
(defn internal-trash-cards
[state _ eid maps]
(if (seq maps)
(let [{:keys [card value]} (first maps)]
(wait-for (value state nil (make-eid state eid) card)
(internal-trash-cards state nil eid (next maps))))
(effect-completed state nil eid)))
(defn trash-when-expired
[state _ eid context-maps]
(if (seq context-maps)
(->> context-maps
(get-effect-maps state nil eid :trash-when-expired)
(internal-trash-cards state nil eid))
(effect-completed state nil eid)))
(defn unregister-expired-durations
[state _ eid duration context-maps]
(wait-for (trash-when-expired state nil (make-eid state eid) context-maps)
(if duration
(unregister-floating-effects state nil duration)
(unregister-floating-events state nil duration))
(effect-completed state nil eid)))
(defn checkpoint
([state eid] (checkpoint state nil eid nil))
([state _ eid] (checkpoint state nil eid nil))
([state _ eid {:keys [duration] :as args}]
;; a: Any ability that has met its condition creates the appropriate instances of itself and marks them as pending
(let [{:keys [handlers context-maps]} (mark-pending-abilities state eid args)]
;; b: Any ability with a duration that has passed is removed from the game state
(wait-for
(unregister-expired-durations state nil (make-eid state eid) duration context-maps)
;; c: Check winning or tying by agenda points
(check-win-by-agenda state)
;; d: uniqueness check
;; unimplemented
;; e: restrictions on card abilities or game rules, MU
;; unimplemented
;; f: stuff on agendas moved from score zone
;; unimplemented
;; g: stuff on installed cards that were trashed
;; unimplemented
;; h: empty servers
(clear-empty-remotes state)
;; i: card counters/agendas become cards again
;; unimplemented
;; j: counters in discard are returned to the bank
;; unimplemented
;; 10.3.2: reaction window
(trigger-pending-abilities state eid handlers args)))))
(defn end-of-phase-checkpoint
([state _ eid event] (end-of-phase-checkpoint state nil eid event nil))
([state _ eid event context]
(when event
(queue-event state event context))
(checkpoint state nil eid {:duration event})))
;; PAYMENT
(defn- pay-next
[state side eid costs card actions msgs]
(if (empty? costs)
(complete-with-result state side eid msgs)
(wait-for (handler (first costs) state side (make-eid state eid) card actions)
(pay-next state side eid (rest costs) card actions (conj msgs async-result)))))
(defn- sentence-join
[strings]
(if (<= (count strings) 2)
(string/join " and " strings)
(str (apply str (interpose ", " (butlast strings))) ", and " (last strings))))
(defn pay
"Same as pay, but awaitable."
[state side eid card & args]
(let [args (flatten args)
raw-costs (remove map? args)
actions (filter map? args)]
(if-let [costs (can-pay? state side eid card (:title card) raw-costs)]
(wait-for (pay-next state side (make-eid state eid) costs card actions [])
(let [payment-result async-result]
(wait-for (checkpoint state nil (make-eid state eid) nil)
(complete-with-result
state side eid
{:msg (->> payment-result
(keep :msg)
sentence-join)
:cost-paid (->> payment-result
(keep #(not-empty (select-keys % [:type :targets :value])))
(reduce
(fn [acc cost]
(assoc acc (:type cost) cost))
{}))}))))
(complete-with-result state side eid nil))))
|
[
{
"context": "ay to achieve this ([doc here](https://github.com/r0man/sablono)).\nHere we use stateless functions that t",
"end": 2153,
"score": 0.9992032647132874,
"start": 2148,
"tag": "USERNAME",
"value": "r0man"
},
{
"context": "just an atom\n (dispatch! store action-init [\"John\" \"Pete\"]) ; actions are just functions\n (is ",
"end": 3260,
"score": 0.9996476769447327,
"start": 3256,
"tag": "NAME",
"value": "John"
},
{
"context": " atom\n (dispatch! store action-init [\"John\" \"Pete\"]) ; actions are just functions\n (is (= {:pe",
"end": 3267,
"score": 0.9997655749320984,
"start": 3263,
"tag": "NAME",
"value": "Pete"
},
{
"context": "tions are just functions\n (is (= {:persons [\"John\" \"Pete\"]} @store)\n \"store should be init",
"end": 3329,
"score": 0.9997121691703796,
"start": 3325,
"tag": "NAME",
"value": "John"
},
{
"context": "re just functions\n (is (= {:persons [\"John\" \"Pete\"]} @store)\n \"store should be initialised",
"end": 3336,
"score": 0.9997880458831787,
"start": 3332,
"tag": "NAME",
"value": "Pete"
},
{
"context": "nit [])\n (dispatch! store action-add-person \"François\")\n (is (= \"François\" (-> @store :persons las",
"end": 3881,
"score": 0.988207995891571,
"start": 3873,
"tag": "NAME",
"value": "François"
},
{
"context": "store action-add-person \"François\")\n (is (= \"François\" (-> @store :persons last))\n \"person sho",
"end": 3906,
"score": 0.9839677214622498,
"start": 3898,
"tag": "NAME",
"value": "François"
},
{
"context": " (dispatch! store action-add-person \"François\"))\n \"person should be unique\")\n (is",
"end": 4095,
"score": 0.9623408317565918,
"start": 4087,
"tag": "NAME",
"value": "François"
},
{
"context": " \"person should be unique\")\n (is (= [\"François\"] (-> @store :persons))\n \"store should b",
"end": 4159,
"score": 0.974663496017456,
"start": 4151,
"tag": "NAME",
"value": "François"
},
{
"context": "\n (fn [store]\n (ui-form store))\n {:persons [\"John\" \"Jim\"]})\n",
"end": 4968,
"score": 0.9974921941757202,
"start": 4964,
"tag": "NAME",
"value": "John"
},
{
"context": "[store]\n (ui-form store))\n {:persons [\"John\" \"Jim\"]})\n",
"end": 4974,
"score": 0.9997150301933289,
"start": 4971,
"tag": "NAME",
"value": "Jim"
}
] |
src/clarc/intro/card2.cljs
|
fdserr/clarc
| 2 |
(ns clarc.intro.card2
(:require
[cljs.test :as test :include-macros true :refer [testing is]]
[devcards.core :as dc :include-macros true :refer [defcard deftest]]
[sablono.core :as sab :include-macros true :refer [html]]))
(defcard
"
[ [Home](#!/clarc.index)
| [Reactive UI](#!/clarc.intro.card1)
| Basic Flux
| [Mini App](#!/clarc.mini_app.index) ]
## Flux?
Code: `src/clarc/intro/card1.cljs`
Flux is an architecture pattern.
It defines three components: `UI`, `State`, `Dispatch`,
and a model for their interaction: `State -> UI -> Dispatch -> State -> UI -> ...`
- `UI` is a pure function of `State`.
`UI` always requests changes to `State` via `Dispatch`.
- `Dispatch` changes `State`, and may trigger `side effects` (call server, launch missile, ...)
- `State` holds all of the mutable values of the system.
- The legend doesn't say how `UI` is rendered on `State` change, but a common
practice is to make `State` `observable` (or `reactive`) and fire a `render`
function whenever it changes.
### Implementation:
- State is a `cljs.core/atom`, to which we add a `watcher` function to
`render` the `UI` on change. __NOTE__: You don't need to manually attach a watcher to the
`store` of a card, Devcards takes care of this.
To avoid confusion, we will call the `atom` itself: `store`, and its
current value: `state`. To obtain `state` from `store`, `(deref store)` (or just `@store`).
- `Dispatch` is a function: `dispatch!`. We pass it the `store`, an `action` and
any number of arguments. An `action` is an arbitrary function that takes a
`state` (a value, not an `atom`), any number of arguments, and returns a new `state`.
Notice that if anything goes wrong during the execution of `dispatch!`, the `store`
is left intact. That's why it's not a good idea to chain actions, each user action
should trigger _one and only one_ `dispatch!`. To re-use small changes to the `store`,
_compose_ smaller functions into one, single `action`.
- `UI` is produced by arbitrary functions that return a `ReactJS` component.
Using `sablono/html` over `hiccup` data structures is one way to achieve this ([doc here](https://github.com/r0man/sablono)).
Here we use stateless functions that take a
`store` and fetch the data they need from it (without ever changing it!).
Other models will be studied later, but we can go a long way with keeping
things simple. UI `events` (clicks, input changes, etc.) are associated to an
anonymous function, which will always call `dispatch!`. __All changes happen
via dispatching actions to the store, do not read or manipulate the DOM directly__.
")
;;;
(defcard "### A minimalistic flux app")
(defn dispatch!
"Dispatch action to store"
[store action & args]
(apply swap! store action args)
nil)
;;; simple centralised error management:
; (defn dispatch!
; [store fun & args]
; (try
; (apply swap! store fun args)
; (catch js/Error e
; (js/alert (.-message e))
; (throw e)))
; nil)
;;;
(defn action-init ; actions take state & args and return new state
"Initial state"
[state persons]
(assoc state :persons persons))
(deftest test-init
(testing "Store initialisation"
(let [store (atom {})] ; store is just an atom
(dispatch! store action-init ["John" "Pete"]) ; actions are just functions
(is (= {:persons ["John" "Pete"]} @store)
"store should be initialised after action-init"))))
;;;
(defn action-add-person
"Person added"
[state person]
(if-not (or (= person "")
(nil? person)
(some #{person} (:persons state)))
(-> state
(update :persons conj person)
(dissoc :input))
(throw (ex-info "Invalid person" {:input person}))))
(deftest test-add-person
(testing "Add a person"
(let [store (atom {})]
(dispatch! store action-init [])
(dispatch! store action-add-person "François")
(is (= "François" (-> @store :persons last))
"person should be found in store after action-add-person")
(is (thrown? js/Error
(dispatch! store action-add-person "François"))
"person should be unique")
(is (= ["François"] (-> @store :persons))
"store should be intact after error"))))
;;;
(defn action-change-input
"Input changed"
[state input]
(assoc state :input input))
(defn ui-person
"person component"
[person]
(html [:li {:key person} person]))
(defn ui-form
"Form component"
[store]
(html [:div
[:input
{:value (or (:input @store) "")
:on-change #(dispatch! store action-change-input
(-> % .-target .-value))}]
[:button
{:on-click #(dispatch! store action-add-person (:input @store))}
"Submit"]
[:p " "]
[:ul (map ui-person (:persons @store))]]))
(defcard ui-persons
"Form to add a person. Check JS console for errors."
(fn [store]
(ui-form store))
{:persons ["John" "Jim"]})
|
84285
|
(ns clarc.intro.card2
(:require
[cljs.test :as test :include-macros true :refer [testing is]]
[devcards.core :as dc :include-macros true :refer [defcard deftest]]
[sablono.core :as sab :include-macros true :refer [html]]))
(defcard
"
[ [Home](#!/clarc.index)
| [Reactive UI](#!/clarc.intro.card1)
| Basic Flux
| [Mini App](#!/clarc.mini_app.index) ]
## Flux?
Code: `src/clarc/intro/card1.cljs`
Flux is an architecture pattern.
It defines three components: `UI`, `State`, `Dispatch`,
and a model for their interaction: `State -> UI -> Dispatch -> State -> UI -> ...`
- `UI` is a pure function of `State`.
`UI` always requests changes to `State` via `Dispatch`.
- `Dispatch` changes `State`, and may trigger `side effects` (call server, launch missile, ...)
- `State` holds all of the mutable values of the system.
- The legend doesn't say how `UI` is rendered on `State` change, but a common
practice is to make `State` `observable` (or `reactive`) and fire a `render`
function whenever it changes.
### Implementation:
- State is a `cljs.core/atom`, to which we add a `watcher` function to
`render` the `UI` on change. __NOTE__: You don't need to manually attach a watcher to the
`store` of a card, Devcards takes care of this.
To avoid confusion, we will call the `atom` itself: `store`, and its
current value: `state`. To obtain `state` from `store`, `(deref store)` (or just `@store`).
- `Dispatch` is a function: `dispatch!`. We pass it the `store`, an `action` and
any number of arguments. An `action` is an arbitrary function that takes a
`state` (a value, not an `atom`), any number of arguments, and returns a new `state`.
Notice that if anything goes wrong during the execution of `dispatch!`, the `store`
is left intact. That's why it's not a good idea to chain actions, each user action
should trigger _one and only one_ `dispatch!`. To re-use small changes to the `store`,
_compose_ smaller functions into one, single `action`.
- `UI` is produced by arbitrary functions that return a `ReactJS` component.
Using `sablono/html` over `hiccup` data structures is one way to achieve this ([doc here](https://github.com/r0man/sablono)).
Here we use stateless functions that take a
`store` and fetch the data they need from it (without ever changing it!).
Other models will be studied later, but we can go a long way with keeping
things simple. UI `events` (clicks, input changes, etc.) are associated to an
anonymous function, which will always call `dispatch!`. __All changes happen
via dispatching actions to the store, do not read or manipulate the DOM directly__.
")
;;;
(defcard "### A minimalistic flux app")
(defn dispatch!
"Dispatch action to store"
[store action & args]
(apply swap! store action args)
nil)
;;; simple centralised error management:
; (defn dispatch!
; [store fun & args]
; (try
; (apply swap! store fun args)
; (catch js/Error e
; (js/alert (.-message e))
; (throw e)))
; nil)
;;;
(defn action-init ; actions take state & args and return new state
"Initial state"
[state persons]
(assoc state :persons persons))
(deftest test-init
(testing "Store initialisation"
(let [store (atom {})] ; store is just an atom
(dispatch! store action-init ["<NAME>" "<NAME>"]) ; actions are just functions
(is (= {:persons ["<NAME>" "<NAME>"]} @store)
"store should be initialised after action-init"))))
;;;
(defn action-add-person
"Person added"
[state person]
(if-not (or (= person "")
(nil? person)
(some #{person} (:persons state)))
(-> state
(update :persons conj person)
(dissoc :input))
(throw (ex-info "Invalid person" {:input person}))))
(deftest test-add-person
(testing "Add a person"
(let [store (atom {})]
(dispatch! store action-init [])
(dispatch! store action-add-person "<NAME>")
(is (= "<NAME>" (-> @store :persons last))
"person should be found in store after action-add-person")
(is (thrown? js/Error
(dispatch! store action-add-person "<NAME>"))
"person should be unique")
(is (= ["<NAME>"] (-> @store :persons))
"store should be intact after error"))))
;;;
(defn action-change-input
"Input changed"
[state input]
(assoc state :input input))
(defn ui-person
"person component"
[person]
(html [:li {:key person} person]))
(defn ui-form
"Form component"
[store]
(html [:div
[:input
{:value (or (:input @store) "")
:on-change #(dispatch! store action-change-input
(-> % .-target .-value))}]
[:button
{:on-click #(dispatch! store action-add-person (:input @store))}
"Submit"]
[:p " "]
[:ul (map ui-person (:persons @store))]]))
(defcard ui-persons
"Form to add a person. Check JS console for errors."
(fn [store]
(ui-form store))
{:persons ["<NAME>" "<NAME>"]})
| true |
(ns clarc.intro.card2
(:require
[cljs.test :as test :include-macros true :refer [testing is]]
[devcards.core :as dc :include-macros true :refer [defcard deftest]]
[sablono.core :as sab :include-macros true :refer [html]]))
(defcard
"
[ [Home](#!/clarc.index)
| [Reactive UI](#!/clarc.intro.card1)
| Basic Flux
| [Mini App](#!/clarc.mini_app.index) ]
## Flux?
Code: `src/clarc/intro/card1.cljs`
Flux is an architecture pattern.
It defines three components: `UI`, `State`, `Dispatch`,
and a model for their interaction: `State -> UI -> Dispatch -> State -> UI -> ...`
- `UI` is a pure function of `State`.
`UI` always requests changes to `State` via `Dispatch`.
- `Dispatch` changes `State`, and may trigger `side effects` (call server, launch missile, ...)
- `State` holds all of the mutable values of the system.
- The legend doesn't say how `UI` is rendered on `State` change, but a common
practice is to make `State` `observable` (or `reactive`) and fire a `render`
function whenever it changes.
### Implementation:
- State is a `cljs.core/atom`, to which we add a `watcher` function to
`render` the `UI` on change. __NOTE__: You don't need to manually attach a watcher to the
`store` of a card, Devcards takes care of this.
To avoid confusion, we will call the `atom` itself: `store`, and its
current value: `state`. To obtain `state` from `store`, `(deref store)` (or just `@store`).
- `Dispatch` is a function: `dispatch!`. We pass it the `store`, an `action` and
any number of arguments. An `action` is an arbitrary function that takes a
`state` (a value, not an `atom`), any number of arguments, and returns a new `state`.
Notice that if anything goes wrong during the execution of `dispatch!`, the `store`
is left intact. That's why it's not a good idea to chain actions, each user action
should trigger _one and only one_ `dispatch!`. To re-use small changes to the `store`,
_compose_ smaller functions into one, single `action`.
- `UI` is produced by arbitrary functions that return a `ReactJS` component.
Using `sablono/html` over `hiccup` data structures is one way to achieve this ([doc here](https://github.com/r0man/sablono)).
Here we use stateless functions that take a
`store` and fetch the data they need from it (without ever changing it!).
Other models will be studied later, but we can go a long way with keeping
things simple. UI `events` (clicks, input changes, etc.) are associated to an
anonymous function, which will always call `dispatch!`. __All changes happen
via dispatching actions to the store, do not read or manipulate the DOM directly__.
")
;;;
(defcard "### A minimalistic flux app")
(defn dispatch!
"Dispatch action to store"
[store action & args]
(apply swap! store action args)
nil)
;;; simple centralised error management:
; (defn dispatch!
; [store fun & args]
; (try
; (apply swap! store fun args)
; (catch js/Error e
; (js/alert (.-message e))
; (throw e)))
; nil)
;;;
(defn action-init ; actions take state & args and return new state
"Initial state"
[state persons]
(assoc state :persons persons))
(deftest test-init
(testing "Store initialisation"
(let [store (atom {})] ; store is just an atom
(dispatch! store action-init ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ; actions are just functions
(is (= {:persons ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]} @store)
"store should be initialised after action-init"))))
;;;
(defn action-add-person
"Person added"
[state person]
(if-not (or (= person "")
(nil? person)
(some #{person} (:persons state)))
(-> state
(update :persons conj person)
(dissoc :input))
(throw (ex-info "Invalid person" {:input person}))))
(deftest test-add-person
(testing "Add a person"
(let [store (atom {})]
(dispatch! store action-init [])
(dispatch! store action-add-person "PI:NAME:<NAME>END_PI")
(is (= "PI:NAME:<NAME>END_PI" (-> @store :persons last))
"person should be found in store after action-add-person")
(is (thrown? js/Error
(dispatch! store action-add-person "PI:NAME:<NAME>END_PI"))
"person should be unique")
(is (= ["PI:NAME:<NAME>END_PI"] (-> @store :persons))
"store should be intact after error"))))
;;;
(defn action-change-input
"Input changed"
[state input]
(assoc state :input input))
(defn ui-person
"person component"
[person]
(html [:li {:key person} person]))
(defn ui-form
"Form component"
[store]
(html [:div
[:input
{:value (or (:input @store) "")
:on-change #(dispatch! store action-change-input
(-> % .-target .-value))}]
[:button
{:on-click #(dispatch! store action-add-person (:input @store))}
"Submit"]
[:p " "]
[:ul (map ui-person (:persons @store))]]))
(defcard ui-persons
"Form to add a person. Check JS console for errors."
(fn [store]
(ui-form store))
{:persons ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]})
|
[
{
"context": " Präsentation\n; Aussagenlogik\n; Copyright (c) 2017 Burkhardt Renz, THM. All rights reserved.\n\n(ns pres.al\n (:requi",
"end": 89,
"score": 0.9998524785041809,
"start": 75,
"tag": "NAME",
"value": "Burkhardt Renz"
}
] |
src/pres/al.clj
|
esb-lwb/lwb
| 22 |
; lwb Logic WorkBench -- Präsentation
; Aussagenlogik
; Copyright (c) 2017 Burkhardt Renz, THM. All rights reserved.
(ns pres.al
(:require [lwb.prop :refer :all])
(:require [lwb.prop.sat :refer [sat sat? valid?]]
[clojure.spec.alpha :as s])
)
; Syntax ===========================
; In Lehrbüchern wird üblicherweise Infix-Notation verwendet,
; also z.B. ¬P ∨ Q ∧ R um Aussagen zu formulieren
;
; Damit man Klammern sparen kann, gibt es Regeln für die Präzedenz
; von Operatoren, etwa ¬ bindet am stärksten, ∧ bindet stärker als ∨
;
; Die schlägt sich im Syntaxbaum nieder, der dadurch eindeutig wird
; und in unserem Beispiel so aussehen würde
;
; ∨
; / ∖
; ¬ ∧
; ⎮ / ∖
; P Q R
; Die Syntax in lwb ist lispy, d.h. wir schreiben einfach den
; abstrakten Syntaxbaum selbst hin:
; In unserem Beispiel:
;
; (or (not P) (and Q R))
(def phi '(or (not P) (and Q R)))
phi
; Warum '??
(wff? phi)
; aber
(wff? '(or not P (and Q R)))
; Operators in der Aussagenlogik
; `not`: Negation - unär
; `and`: Konjunktion -- n-är
; `or`: Disjunktion -- n-är
; `impl`: Implikation -- binär
; `equiv`: Äquivalenz -- binär
; `xor`: Exklusives or -- binär
; `ite`: If-then-else -- ternär
; Syntaxbaum kann man auch hübsch zeichnen
(texify phi "beispiel")
; Exkurs -----------------------------------
; Wie ist wff? implementiert?
; wff? verwendet clojure.spec
; Ein einfacher Ausdruck ist true/false oder atomare Aussage
(s/def ::simple-expr (s/or :bool boolean? :atom atom?))
; Ein zusammengesetzter Ausdruck ist eine Liste mit einem Operator und
; Formeln als Argumente (deren Zahl zur Arität des Operators passt)
(defn- arity-ok? [{:keys [op params]}]
(let [arity (arity op)]
(if (= arity -1) true
(= arity (count params)))))
(s/def ::compl-expr (s/and list? (s/& (s/cat :op op? :params (s/* ::fml)) arity-ok?)))
; Eine ordentliche Formel der Aussagenlogik:
(s/def ::fml (s/or :simple-expr ::simple-expr
:compl-expr ::compl-expr))
; Ende Exkurs --------------------------------
; Auswertung =================================
; Man gibt einfach Wahrheitswerte vor
(def m1 {'P true 'Q false 'R true})
(eval-phi phi m1)
; => false
(def m2 {'P false 'Q false 'R true})
(eval-phi phi m2)
; => true
; Exkurs -----------------------------------
; Implementierung
; verwendet die Funktion eval von Clojure
; Die Formel ist ein Ausdruck, der mit dem gegebenen Modell
; ausgewertet wird
; Data is Code, Code is Data = Homoikonizität
; Ende Exkurs --------------------------------
; Erfüllbarkeit =================================
; Wahrheitstafel (brute force)
(ptt phi)
; viel besser: SAT-Solver
(sat phi)
(sat phi :all)
; Exkurs -----------------------------------
; Implementierung
; Tseitin-Transformation in eine Formel in CNF, die
; erfüllbarkeits-äquvalent ist
; Umbauen ins dimac-Format
; Aufruf von SAT4J (www.sat4j.org)
; Ergebnis in unsere Sprache zurückübersetzen
; Ende Exkurs --------------------------------
; Beispiel sudoku
; lwb.prop.examples.sudoku
; Natürliches Schließen ======================
; pres.nd
|
101166
|
; lwb Logic WorkBench -- Präsentation
; Aussagenlogik
; Copyright (c) 2017 <NAME>, THM. All rights reserved.
(ns pres.al
(:require [lwb.prop :refer :all])
(:require [lwb.prop.sat :refer [sat sat? valid?]]
[clojure.spec.alpha :as s])
)
; Syntax ===========================
; In Lehrbüchern wird üblicherweise Infix-Notation verwendet,
; also z.B. ¬P ∨ Q ∧ R um Aussagen zu formulieren
;
; Damit man Klammern sparen kann, gibt es Regeln für die Präzedenz
; von Operatoren, etwa ¬ bindet am stärksten, ∧ bindet stärker als ∨
;
; Die schlägt sich im Syntaxbaum nieder, der dadurch eindeutig wird
; und in unserem Beispiel so aussehen würde
;
; ∨
; / ∖
; ¬ ∧
; ⎮ / ∖
; P Q R
; Die Syntax in lwb ist lispy, d.h. wir schreiben einfach den
; abstrakten Syntaxbaum selbst hin:
; In unserem Beispiel:
;
; (or (not P) (and Q R))
(def phi '(or (not P) (and Q R)))
phi
; Warum '??
(wff? phi)
; aber
(wff? '(or not P (and Q R)))
; Operators in der Aussagenlogik
; `not`: Negation - unär
; `and`: Konjunktion -- n-är
; `or`: Disjunktion -- n-är
; `impl`: Implikation -- binär
; `equiv`: Äquivalenz -- binär
; `xor`: Exklusives or -- binär
; `ite`: If-then-else -- ternär
; Syntaxbaum kann man auch hübsch zeichnen
(texify phi "beispiel")
; Exkurs -----------------------------------
; Wie ist wff? implementiert?
; wff? verwendet clojure.spec
; Ein einfacher Ausdruck ist true/false oder atomare Aussage
(s/def ::simple-expr (s/or :bool boolean? :atom atom?))
; Ein zusammengesetzter Ausdruck ist eine Liste mit einem Operator und
; Formeln als Argumente (deren Zahl zur Arität des Operators passt)
(defn- arity-ok? [{:keys [op params]}]
(let [arity (arity op)]
(if (= arity -1) true
(= arity (count params)))))
(s/def ::compl-expr (s/and list? (s/& (s/cat :op op? :params (s/* ::fml)) arity-ok?)))
; Eine ordentliche Formel der Aussagenlogik:
(s/def ::fml (s/or :simple-expr ::simple-expr
:compl-expr ::compl-expr))
; Ende Exkurs --------------------------------
; Auswertung =================================
; Man gibt einfach Wahrheitswerte vor
(def m1 {'P true 'Q false 'R true})
(eval-phi phi m1)
; => false
(def m2 {'P false 'Q false 'R true})
(eval-phi phi m2)
; => true
; Exkurs -----------------------------------
; Implementierung
; verwendet die Funktion eval von Clojure
; Die Formel ist ein Ausdruck, der mit dem gegebenen Modell
; ausgewertet wird
; Data is Code, Code is Data = Homoikonizität
; Ende Exkurs --------------------------------
; Erfüllbarkeit =================================
; Wahrheitstafel (brute force)
(ptt phi)
; viel besser: SAT-Solver
(sat phi)
(sat phi :all)
; Exkurs -----------------------------------
; Implementierung
; Tseitin-Transformation in eine Formel in CNF, die
; erfüllbarkeits-äquvalent ist
; Umbauen ins dimac-Format
; Aufruf von SAT4J (www.sat4j.org)
; Ergebnis in unsere Sprache zurückübersetzen
; Ende Exkurs --------------------------------
; Beispiel sudoku
; lwb.prop.examples.sudoku
; Natürliches Schließen ======================
; pres.nd
| true |
; lwb Logic WorkBench -- Präsentation
; Aussagenlogik
; Copyright (c) 2017 PI:NAME:<NAME>END_PI, THM. All rights reserved.
(ns pres.al
(:require [lwb.prop :refer :all])
(:require [lwb.prop.sat :refer [sat sat? valid?]]
[clojure.spec.alpha :as s])
)
; Syntax ===========================
; In Lehrbüchern wird üblicherweise Infix-Notation verwendet,
; also z.B. ¬P ∨ Q ∧ R um Aussagen zu formulieren
;
; Damit man Klammern sparen kann, gibt es Regeln für die Präzedenz
; von Operatoren, etwa ¬ bindet am stärksten, ∧ bindet stärker als ∨
;
; Die schlägt sich im Syntaxbaum nieder, der dadurch eindeutig wird
; und in unserem Beispiel so aussehen würde
;
; ∨
; / ∖
; ¬ ∧
; ⎮ / ∖
; P Q R
; Die Syntax in lwb ist lispy, d.h. wir schreiben einfach den
; abstrakten Syntaxbaum selbst hin:
; In unserem Beispiel:
;
; (or (not P) (and Q R))
(def phi '(or (not P) (and Q R)))
phi
; Warum '??
(wff? phi)
; aber
(wff? '(or not P (and Q R)))
; Operators in der Aussagenlogik
; `not`: Negation - unär
; `and`: Konjunktion -- n-är
; `or`: Disjunktion -- n-är
; `impl`: Implikation -- binär
; `equiv`: Äquivalenz -- binär
; `xor`: Exklusives or -- binär
; `ite`: If-then-else -- ternär
; Syntaxbaum kann man auch hübsch zeichnen
(texify phi "beispiel")
; Exkurs -----------------------------------
; Wie ist wff? implementiert?
; wff? verwendet clojure.spec
; Ein einfacher Ausdruck ist true/false oder atomare Aussage
(s/def ::simple-expr (s/or :bool boolean? :atom atom?))
; Ein zusammengesetzter Ausdruck ist eine Liste mit einem Operator und
; Formeln als Argumente (deren Zahl zur Arität des Operators passt)
(defn- arity-ok? [{:keys [op params]}]
(let [arity (arity op)]
(if (= arity -1) true
(= arity (count params)))))
(s/def ::compl-expr (s/and list? (s/& (s/cat :op op? :params (s/* ::fml)) arity-ok?)))
; Eine ordentliche Formel der Aussagenlogik:
(s/def ::fml (s/or :simple-expr ::simple-expr
:compl-expr ::compl-expr))
; Ende Exkurs --------------------------------
; Auswertung =================================
; Man gibt einfach Wahrheitswerte vor
(def m1 {'P true 'Q false 'R true})
(eval-phi phi m1)
; => false
(def m2 {'P false 'Q false 'R true})
(eval-phi phi m2)
; => true
; Exkurs -----------------------------------
; Implementierung
; verwendet die Funktion eval von Clojure
; Die Formel ist ein Ausdruck, der mit dem gegebenen Modell
; ausgewertet wird
; Data is Code, Code is Data = Homoikonizität
; Ende Exkurs --------------------------------
; Erfüllbarkeit =================================
; Wahrheitstafel (brute force)
(ptt phi)
; viel besser: SAT-Solver
(sat phi)
(sat phi :all)
; Exkurs -----------------------------------
; Implementierung
; Tseitin-Transformation in eine Formel in CNF, die
; erfüllbarkeits-äquvalent ist
; Umbauen ins dimac-Format
; Aufruf von SAT4J (www.sat4j.org)
; Ergebnis in unsere Sprache zurückübersetzen
; Ende Exkurs --------------------------------
; Beispiel sudoku
; lwb.prop.examples.sudoku
; Natürliches Schließen ======================
; pres.nd
|
[
{
"context": " (b/into [])))))\n (let [input [{:name \"Bob\" :x 2} {:name \"Jim\" :x 99} {:name \"Bob\" :x 3}]]\n ",
"end": 7252,
"score": 0.9993768334388733,
"start": 7249,
"tag": "NAME",
"value": "Bob"
},
{
"context": "[])))))\n (let [input [{:name \"Bob\" :x 2} {:name \"Jim\" :x 99} {:name \"Bob\" :x 3}]]\n (is (= [{:name \"",
"end": 7271,
"score": 0.9995583295822144,
"start": 7268,
"tag": "NAME",
"value": "Jim"
},
{
"context": "t [{:name \"Bob\" :x 2} {:name \"Jim\" :x 99} {:name \"Bob\" :x 3}]]\n (is (= [{:name \"Bob\" :x 2} {:name \"J",
"end": 7291,
"score": 0.9996073842048645,
"start": 7288,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\" :x 99} {:name \"Bob\" :x 3}]]\n (is (= [{:name \"Bob\" :x 2} {:name \"Jim\" :x 99}]\n (->> input",
"end": 7324,
"score": 0.9996032118797302,
"start": 7321,
"tag": "NAME",
"value": "Bob"
},
{
"context": "b\" :x 3}]]\n (is (= [{:name \"Bob\" :x 2} {:name \"Jim\" :x 99}]\n (->> input\n (r",
"end": 7343,
"score": 0.9996545314788818,
"start": 7340,
"tag": "NAME",
"value": "Jim"
},
{
"context": " this is implemented\n ; see https://github.com/Netflix/RxJava/commit/02ccc4d727a9297f14219549208757c6e0e",
"end": 9863,
"score": 0.9978359937667847,
"start": 9856,
"tag": "USERNAME",
"value": "Netflix"
}
] |
language-adaptors/rxjava-clojure/src/test/clojure/rx/lang/clojure/core_test.clj
|
dpsm/RxJava
| 3 |
(ns rx.lang.clojure.core-test
(:require [rx.lang.clojure.core :as rx]
[rx.lang.clojure.blocking :as b]
[rx.lang.clojure.future :as f]
[clojure.test :refer [deftest is testing are]]))
(deftest test-observable?
(is (rx/observable? (rx/return 99)))
(is (not (rx/observable? "I'm not an observable"))))
(deftest test-on-next
(testing "calls onNext"
(let [called (atom [])
o (reify rx.Observer (onNext [this value] (swap! called conj value)))]
(is (identical? o (rx/on-next o 1)))
(is (= [1] @called)))))
(deftest test-on-completed
(testing "calls onCompleted"
(let [called (atom 0)
o (reify rx.Observer (onCompleted [this] (swap! called inc)))]
(is (identical? o (rx/on-completed o)))
(is (= 1 @called)))))
(deftest test-on-error
(testing "calls onError"
(let [called (atom [])
e (java.io.FileNotFoundException. "yum")
o (reify rx.Observer (onError [this e] (swap! called conj e)))]
(is (identical? o (rx/on-error o e)))
(is (= [e] @called)))))
(deftest test-catch-error-value
(testing "if no exception, returns body"
(let [o (reify rx.Observer)]
(is (= 3 (rx/catch-error-value o 99
(+ 1 2))))))
(testing "exceptions call onError on observable and inject value in exception"
(let [called (atom [])
e (java.io.FileNotFoundException. "boo")
o (reify rx.Observer
(onError [this e]
(swap! called conj e)))
result (rx/catch-error-value o 100
(throw e))
cause (.getCause e)]
(is (identical? e result))
(is (= [e] @called))
(when (is (instance? rx.exceptions.OnErrorThrowable$OnNextValue cause))
(is (= 100 (.getValue cause)))))))
(deftest test-subscribe
(testing "subscribe overload with only onNext"
(let [o (rx/return 1)
called (atom nil)]
(rx/subscribe o (fn [v] (swap! called (fn [_] v))))
(is (= 1 @called)))))
(deftest test-fn->predicate
(are [f arg result] (= result (.call (rx/fn->predicate f) arg))
identity nil false
identity false false
identity 1 true
identity "true" true
identity true true))
(deftest test-subscription
(let [called (atom 0)
s (rx/subscription #(swap! called inc))]
(is (identical? s (rx/unsubscribe s)))
(is (= 1 @called))))
(deftest test-unsubscribed?
(let [s (rx/subscription #())]
(is (not (rx/unsubscribed? s)))
(rx/unsubscribe s)
(is (rx/unsubscribed? s))))
(deftest test-observable*
(let [o (rx/observable* (fn [s]
(rx/on-next s 0)
(rx/on-next s 1)
(when-not (rx/unsubscribed? s) (rx/on-next s 2))
(rx/on-completed s)))]
(is (= [0 1 2] (b/into [] o)))))
(deftest test-operator*
(let [o (rx/operator* #(rx/subscriber %
(fn [o v]
(if (even? v)
(rx/on-next o v)))))
result (->> (rx/seq->o [1 2 3 4 5])
(rx/lift o)
(b/into []))]
(is (= [2 4] result))))
(deftest test-serialize
; I'm going to believe serialize works and just exercise it
; here for sanity.
(is (= [1 2 3]
(->> [1 2 3]
(rx/seq->o)
(rx/serialize)
(b/into [])))))
(let [expected-result [[1 3 5] [2 4 6]]
sleepy-o #(f/future-generator*
future-call
(fn [o]
(doseq [x %]
(Thread/sleep 10)
(rx/on-next o x))))
make-inputs (fn [] (mapv sleepy-o expected-result))
make-output (fn [r] [(keep #{1 3 5} r)
(keep #{2 4 6} r)])]
(deftest test-merge*
(is (= expected-result
(->> (make-inputs)
(rx/seq->o)
(rx/merge*)
(b/into [])
(make-output)))))
(deftest test-merge
(is (= expected-result
(->> (make-inputs)
(apply rx/merge)
(b/into [])
(make-output)))))
(deftest test-merge-delay-error*
(is (= expected-result
(->> (make-inputs)
(rx/seq->o)
(rx/merge-delay-error*)
(b/into [])
(make-output)))))
(deftest test-merge-delay-error
(is (= expected-result
(->> (make-inputs)
(apply rx/merge-delay-error)
(b/into [])
(make-output))))))
(deftest test-generator
(testing "calls on-completed automatically"
(let [o (rx/generator [o])
called (atom nil)]
(rx/subscribe o (fn [v]) (fn [_]) #(reset! called "YES"))
(is (= "YES" @called))))
(testing "exceptions automatically go to on-error"
(let [expected (IllegalArgumentException. "hi")
actual (atom nil)]
(rx/subscribe (rx/generator [o] (throw expected))
#()
#(reset! actual %))
(is (identical? expected @actual)))))
(deftest test-seq->o
(is (= [] (b/into [] (rx/seq->o []))))
(is (= [] (b/into [] (rx/seq->o nil))))
(is (= [\a \b \c] (b/into [] (rx/seq->o "abc"))))
(is (= [0 1 2 3] (b/first (rx/into [] (rx/seq->o (range 4))))))
(is (= #{0 1 2 3} (b/first (rx/into #{} (rx/seq->o (range 4))))))
(is (= {:a 1 :b 2 :c 3} (b/first (rx/into {} (rx/seq->o [[:a 1] [:b 2] [:c 3]]))))))
(deftest test-return
(is (= [0] (b/into [] (rx/return 0)))))
(deftest test-cache
(let [value (atom 0)
o (->>
(rx/return 0)
(rx/map (fn [x] (swap! value inc)))
(rx/cache))]
(is (= 1 (b/single o)))
(is (= 1 @value))
(is (= 1 (b/single o)))
(is (= 1 @value))
(is (= 1 (b/single o)))))
(deftest test-cons
(is (= [1] (b/into [] (rx/cons 1 (rx/empty)))))
(is (= [1 2 3 4] (b/into [] (rx/cons 1 (rx/seq->o [2 3 4]))))))
(deftest test-concat
(is (= [:q :r]
(b/into [] (rx/concat (rx/seq->o [:q :r])))))
(is (= [:q :r 1 2 3]
(b/into [] (rx/concat (rx/seq->o [:q :r])
(rx/seq->o [1 2 3]))))))
(deftest test-concat*
(is (= [:q :r]
(b/into [] (rx/concat* (rx/return (rx/seq->o [:q :r]))))))
(is (= [:q :r 1 2 3]
(b/into [] (rx/concat* (rx/seq->o [(rx/seq->o [:q :r])
(rx/seq->o [1 2 3])]))))))
(deftest test-count
(are [xs] (= (count xs) (->> xs (rx/seq->o) (rx/count) (b/single)))
[]
[1]
[5 6 7]
(range 10000)))
(deftest test-cycle
(is (= [1 2 3 1 2 3 1 2 3 1 2]
(->> [1 2 3]
(rx/seq->o)
(rx/cycle)
(rx/take 11)
(b/into [])))))
(deftest test-distinct
(let [input [{:a 1} {:a 1} {:b 1} {"a" (int 1)} {:a (int 1)}]]
(is (= (distinct input)
(->> input
(rx/seq->o)
(rx/distinct)
(b/into [])))))
(let [input [{:name "Bob" :x 2} {:name "Jim" :x 99} {:name "Bob" :x 3}]]
(is (= [{:name "Bob" :x 2} {:name "Jim" :x 99}]
(->> input
(rx/seq->o)
(rx/distinct :name)
(b/into []))))))
(deftest test-do
(testing "calls a function with each element"
(let [collected (atom [])]
(is (= [1 2 3]
(->> (rx/seq->o [1 2 3])
(rx/do (fn [v]
(swap! collected conj (* 2 v))))
(rx/do (partial println "GOT"))
(b/into []))))
(is (= [2 4 6] @collected))))
(testing "ends sequence with onError if action code throws an exception"
(let [collected (atom [])
o (->> (rx/seq->o [1 2 3])
(rx/do (fn [v]
(if (= v 2)
(throw (IllegalStateException. (str "blah" v)))
(swap! collected conj (* 99 v))))))]
(is (thrown-with-msg? IllegalStateException #"blah2"
(b/into [] o)))
(is (= [99] @collected)))))
(deftest test-drop-while
(is (= (into [] (drop-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/drop-while even? (rx/seq->o [2 4 6 8 1 2 3])))))
(is (= (into [] (drop-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/drop-while even? (rx/seq->o [2 4 6 8 1 2 3]))))))
(deftest test-every?
(are [xs p result] (= result (->> xs (rx/seq->o) (rx/every? p) (b/single)))
[2 4 6 8] even? true
[2 4 3 8] even? false
[1 2 3 4] #{1 2 3 4} true
[1 2 3 4] #{1 3 4} false))
(deftest test-filter
(is (= (into [] (->> [:a :b :c :d :e :f :G :e]
(filter #{:b :e :G})))
(b/into [] (->> (rx/seq->o [:a :b :c :d :e :f :G :e])
(rx/filter #{:b :e :G}))))))
(deftest test-first
(is (= [3]
(b/into [] (rx/first (rx/seq->o [3 4 5])))))
(is (= []
(b/into [] (rx/first (rx/empty))))))
(deftest test-group-by
(let [xs [{:k :a :v 1} {:k :b :v 2} {:k :a :v 3} {:k :c :v 4}]]
(testing "with just a key-fn"
(is (= [[:a {:k :a :v 1}]
[:b {:k :b :v 2}]
[:a {:k :a :v 3}]
[:c {:k :c :v 4}]]
(->> xs
(rx/seq->o)
(rx/group-by :k)
(rx/mapcat (fn [[k vo :as me]]
(is (instance? clojure.lang.MapEntry me))
(rx/map #(vector k %) vo)))
(b/into [])))))
; TODO reinstate once this is implemented
; see https://github.com/Netflix/RxJava/commit/02ccc4d727a9297f14219549208757c6e0efce2a
#_(testing "with a val-fn"
(is (= [[:a 1]
[:b 2]
[:a 3]
[:c 4]]
(->> xs
(rx/seq->o)
(rx/group-by :k :v)
(rx/mapcat (fn [[k vo :as me]]
(is (instance? clojure.lang.MapEntry me))
(rx/map #(vector k %) vo)))
(b/into [])))))))
(deftest test-interleave
(are [inputs] (= (apply interleave inputs)
(->> (apply rx/interleave (map rx/seq->o inputs))
(b/into [])))
[[] []]
[[] [1]]
[(range 5) (range 10) (range 10) (range 3)]
[(range 50) (range 10)]
[(range 5) (range 10 60) (range 10) (range 50)])
; one-arg case, not supported by clojure.core/interleave
(is (= (range 10)
(->> (rx/interleave (rx/seq->o (range 10)))
(b/into [])))))
(deftest test-interleave*
(are [inputs] (= (apply interleave inputs)
(->> (rx/interleave* (->> inputs
(map rx/seq->o)
(rx/seq->o)))
(b/into [])))
[[] []]
[[] [1]]
[(range 5) (range 10) (range 10) (range 3)]
[(range 50) (range 10)]
[(range 5) (range 10 60) (range 10) (range 50)]))
(deftest test-interpose
(is (= (interpose \, [1 2 3])
(b/into [] (rx/interpose \, (rx/seq->o [1 2 3]))))))
(deftest test-into
(are [input to] (= (into to input)
(b/single (rx/into to (rx/seq->o input))))
[6 7 8] [9 10 [11]]
#{} [1 2 3 2 4 5]
{} [[1 2] [3 2] [4 5]]
{} []
'() (range 50)))
(deftest test-iterate
(are [f x n] (= (->> (iterate f x) (take n))
(->> (rx/iterate f x) (rx/take n) (b/into [])))
inc 0 10
dec 20 100
#(conj % (count %)) [] 5
#(cons (count %) % ) nil 5))
(deftest test-keep
(is (= (into [] (keep identity [true true false]))
(b/into [] (rx/keep identity (rx/seq->o [true true false])))))
(is (= (into [] (keep #(if (even? %) (* 2 %)) (range 9)))
(b/into [] (rx/keep #(if (even? %) (* 2 %)) (rx/seq->o (range 9)))))))
(deftest test-keep-indexed
(is (= (into [] (keep-indexed (fn [i v]
(if (even? i) v))
[true true false]))
(b/into [] (rx/keep-indexed (fn [i v]
(if (even? i) v))
(rx/seq->o [true true false]))))))
(deftest test-map
(is (= (into {} (map (juxt identity name)
[:q :r :s :t :u]))
(b/into {} (rx/map (juxt identity name)
(rx/seq->o [:q :r :s :t :u])))))
(is (= (into [] (map vector
[:q :r :s :t :u]
(range 10)
["a" "b" "c" "d" "e"] ))
(b/into [] (rx/map vector
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o (range 10) )
(rx/seq->o ["a" "b" "c" "d" "e"] )))))
; check > 4 arg case
(is (= (into [] (map vector
[:q :r :s :t :u]
[:q :r :s :t :u]
[:q :r :s :t :u]
(range 10)
(range 10)
(range 10)
["a" "b" "c" "d" "e"]
["a" "b" "c" "d" "e"]
["a" "b" "c" "d" "e"]))
(b/into [] (rx/map vector
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o (range 10))
(rx/seq->o (range 10))
(rx/seq->o (range 10))
(rx/seq->o ["a" "b" "c" "d" "e"])
(rx/seq->o ["a" "b" "c" "d" "e"])
(rx/seq->o ["a" "b" "c" "d" "e"]))))))
(deftest test-map*
(is (= [[1 2 3 4 5 6 7 8]]
(b/into [] (rx/map* vector
(rx/seq->o [(rx/seq->o [1])
(rx/seq->o [2])
(rx/seq->o [3])
(rx/seq->o [4])
(rx/seq->o [5])
(rx/seq->o [6])
(rx/seq->o [7])
(rx/seq->o [8])]))))))
(deftest test-map-indexed
(is (= (map-indexed vector [:a :b :c])
(b/into [] (rx/map-indexed vector (rx/seq->o [:a :b :c])))))
(testing "exceptions from fn have error value injected"
(try
(->> (rx/seq->o [:a :b :c])
(rx/map-indexed (fn [i v]
(if (= 1 i)
(throw (java.io.FileNotFoundException. "blah")))
v))
(b/into []))
(catch java.io.FileNotFoundException e
(is (= :b (-> e .getCause .getValue)))))))
(deftest test-mapcat*
(let [f (fn [a b c d e]
[(+ a b) (+ c d) e])]
(is (= (->> (range 5)
(map (fn [_] (range 5)))
(apply mapcat f))
(->> (range 5)
(map (fn [_] (rx/seq->o (range 5))))
(rx/seq->o)
(rx/mapcat* (fn [& args] (rx/seq->o (apply f args))))
(b/into []))))))
(deftest test-mapcat
(let [f (fn [v] [v (* v v)])
xs (range 10)]
(is (= (mapcat f xs)
(b/into [] (rx/mapcat (comp rx/seq->o f) (rx/seq->o xs))))))
(let [f (fn [a b] [a b (* a b)])
as (range 10)
bs (range 15)]
(is (= (mapcat f as bs)
(b/into [] (rx/mapcat (comp rx/seq->o f)
(rx/seq->o as)
(rx/seq->o bs)))))))
(deftest test-next
(let [in [:q :r :s :t :u]]
(is (= (next in) (b/into [] (rx/next (rx/seq->o in)))))))
(deftest test-nth
(is (= [:a]
(b/into [] (rx/nth (rx/seq->o [:s :b :a :c]) 2))))
(is (= [:fallback]
(b/into [] (rx/nth (rx/seq->o [:s :b :a :c]) 25 :fallback)))))
(deftest test-rest
(let [in [:q :r :s :t :u]]
(is (= (rest in) (b/into [] (rx/rest (rx/seq->o in)))))))
(deftest test-partition-all
(are [input-size part-size step] (= (->> (range input-size)
(partition-all part-size step))
(->> (range input-size)
(rx/seq->o)
(rx/partition-all part-size step)
(rx/map #(rx/into [] %))
(rx/concat*)
(b/into [])))
0 1 1
10 2 2
10 3 2
15 30 4)
(are [input-size part-size] (= (->> (range input-size)
(partition-all part-size))
(->> (range input-size)
(rx/seq->o)
(rx/partition-all part-size)
(rx/map #(rx/into [] %))
(rx/concat*)
(b/into [])))
0 1
10 2
10 3
15 30))
(deftest test-range
(are [start end step] (= (range start end step)
(->> (rx/range start end step) (b/into [])))
0 10 2
0 -100 -1
5 100 9)
(are [start end] (= (range start end)
(->> (rx/range start end) (b/into [])))
0 10
0 -100
5 100)
(are [start] (= (->> (range start) (take 100))
(->> (rx/range start) (rx/take 100) (b/into [])))
50
0
5
-20)
(is (= (->> (range) (take 500))
(->> (rx/range) (rx/take 500) (b/into [])))))
(deftest test-reduce
(is (= (reduce + 0 (range 4))
(b/first (rx/reduce + 0 (rx/seq->o (range 4)))))))
(deftest test-reductions
(is (= (into [] (reductions + 0 (range 4)))
(b/into [] (rx/reductions + 0 (rx/seq->o (range 4)))))))
(deftest test-some
(is (= [:r] (b/into [] (rx/some #{:r :s :t} (rx/seq->o [:q :v :r])))))
(is (= [] (b/into [] (rx/some #{:r :s :t} (rx/seq->o [:q :v]))))))
(deftest test-sort
(are [in cmp] (= (if cmp
(sort cmp in)
(sort in))
(->> in
(rx/seq->o)
(#(if cmp (rx/sort cmp %) (rx/sort %)))
(b/into [])))
[] nil
[] (comp - compare)
[3 1 2] nil
[1 2 3] nil
[1 2 3] (comp - compare)
[2 1 3] (comp - compare)))
(deftest test-sort-by
(are [rin cmp] (let [in (map #(hash-map :foo %) rin)]
(= (if cmp
(sort-by :foo cmp in)
(sort-by :foo in))
(->> in
(rx/seq->o)
(#(if cmp (rx/sort-by :foo cmp %) (rx/sort-by :foo %)))
(b/into []))))
[] nil
[] (comp - compare)
[3 1 2] nil
[1 2 3] nil
[1 2 3] (comp - compare)
[2 1 3] (comp - compare)))
(deftest test-split-with
(is (= (split-with (partial >= 3) (range 6))
(->> (rx/seq->o (range 6))
(rx/split-with (partial >= 3))
b/first
(map (partial b/into []))))))
(deftest test-take-while
(is (= (into [] (take-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/take-while even? (rx/seq->o [2 4 6 8 1 2 3]))))))
(deftest test-throw
(let [expected (IllegalArgumentException. "HI")
called (atom nil)]
(rx/subscribe (rx/throw expected)
(fn [_])
(fn [e] (reset! called expected))
(fn [_]))
(is (identical? expected @called))))
(deftest test-catch*
(testing "Is just a passthrough if there's no error"
(is (= [1 2 3]
(->> (rx/seq->o [1 2 3])
(rx/catch* Exception (fn [e] (throw "OH NO")))
(b/into [])))))
(testing "Can catch a particular exception type and continue with an observable"
(is (= [1 2 4 5 6 "foo"]
(->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o (IllegalStateException. "foo")))
(rx/catch* IllegalStateException
(fn [e]
(rx/seq->o [4 5 6 (.getMessage e)])))
(b/into [])))))
(testing "if exception isn't matched, it's passed to on-error"
(let [expected (IllegalArgumentException. "HI")
called (atom nil)]
(rx/subscribe (->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o expected))
(rx/catch* IllegalStateException (fn [e]
(rx/return "WAT?"))))
(fn [_])
(fn [e] (reset! called expected))
(fn [_]))
(is (identical? expected @called))))
(testing "if p returns Throwable, that's passed as e"
(let [cause (IllegalArgumentException. "HI")
wrapper (java.util.concurrent.ExecutionException. cause)]
(is (= [cause]
(->> (rx/throw wrapper)
(rx/catch #(.getCause %) e
(rx/return e))
(b/into [])))))))
(deftest test-finally
(testing "Supports a finally clause"
(testing "called on completed"
(let [completed (atom nil)
called (atom nil)]
(rx/subscribe (->> (rx/seq->o [1 2 3])
(rx/finally* (fn [] (reset! called (str "got it")))))
(fn [_])
(fn [_] (throw (IllegalStateException. "WAT")))
(fn [] (reset! completed "DONE")))
(is (= "got it" @called))
(is (= "DONE" @completed))))
(testing "called on error"
(let [expected (IllegalStateException. "expected")
completed (atom nil)
called (atom nil)]
(rx/subscribe (->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o expected))
(rx/finally
(reset! called "got it")))
(fn [_])
(fn [e] (reset! completed e))
(fn [] (throw (IllegalStateException. "WAT"))))
(is (= "got it" @called))
(is (identical? expected @completed))))))
;################################################################################
(deftest test-graph-imports
(is (= 99
(-> {:a {:deps [] :factory (fn [_] (rx/return 99))}}
rx/let-o*
:a
b/single)))
(is (= 100
(b/single (rx/let-o [?a (rx/return 100)]
?a)))))
;################################################################################
(deftest test-realized-imports
(is (= {:a 1 :b 2}
(->> (rx/let-realized [a (rx/return 1)
b (rx/return 2)]
{:a a :b b})
b/single))))
|
32821
|
(ns rx.lang.clojure.core-test
(:require [rx.lang.clojure.core :as rx]
[rx.lang.clojure.blocking :as b]
[rx.lang.clojure.future :as f]
[clojure.test :refer [deftest is testing are]]))
(deftest test-observable?
(is (rx/observable? (rx/return 99)))
(is (not (rx/observable? "I'm not an observable"))))
(deftest test-on-next
(testing "calls onNext"
(let [called (atom [])
o (reify rx.Observer (onNext [this value] (swap! called conj value)))]
(is (identical? o (rx/on-next o 1)))
(is (= [1] @called)))))
(deftest test-on-completed
(testing "calls onCompleted"
(let [called (atom 0)
o (reify rx.Observer (onCompleted [this] (swap! called inc)))]
(is (identical? o (rx/on-completed o)))
(is (= 1 @called)))))
(deftest test-on-error
(testing "calls onError"
(let [called (atom [])
e (java.io.FileNotFoundException. "yum")
o (reify rx.Observer (onError [this e] (swap! called conj e)))]
(is (identical? o (rx/on-error o e)))
(is (= [e] @called)))))
(deftest test-catch-error-value
(testing "if no exception, returns body"
(let [o (reify rx.Observer)]
(is (= 3 (rx/catch-error-value o 99
(+ 1 2))))))
(testing "exceptions call onError on observable and inject value in exception"
(let [called (atom [])
e (java.io.FileNotFoundException. "boo")
o (reify rx.Observer
(onError [this e]
(swap! called conj e)))
result (rx/catch-error-value o 100
(throw e))
cause (.getCause e)]
(is (identical? e result))
(is (= [e] @called))
(when (is (instance? rx.exceptions.OnErrorThrowable$OnNextValue cause))
(is (= 100 (.getValue cause)))))))
(deftest test-subscribe
(testing "subscribe overload with only onNext"
(let [o (rx/return 1)
called (atom nil)]
(rx/subscribe o (fn [v] (swap! called (fn [_] v))))
(is (= 1 @called)))))
(deftest test-fn->predicate
(are [f arg result] (= result (.call (rx/fn->predicate f) arg))
identity nil false
identity false false
identity 1 true
identity "true" true
identity true true))
(deftest test-subscription
(let [called (atom 0)
s (rx/subscription #(swap! called inc))]
(is (identical? s (rx/unsubscribe s)))
(is (= 1 @called))))
(deftest test-unsubscribed?
(let [s (rx/subscription #())]
(is (not (rx/unsubscribed? s)))
(rx/unsubscribe s)
(is (rx/unsubscribed? s))))
(deftest test-observable*
(let [o (rx/observable* (fn [s]
(rx/on-next s 0)
(rx/on-next s 1)
(when-not (rx/unsubscribed? s) (rx/on-next s 2))
(rx/on-completed s)))]
(is (= [0 1 2] (b/into [] o)))))
(deftest test-operator*
(let [o (rx/operator* #(rx/subscriber %
(fn [o v]
(if (even? v)
(rx/on-next o v)))))
result (->> (rx/seq->o [1 2 3 4 5])
(rx/lift o)
(b/into []))]
(is (= [2 4] result))))
(deftest test-serialize
; I'm going to believe serialize works and just exercise it
; here for sanity.
(is (= [1 2 3]
(->> [1 2 3]
(rx/seq->o)
(rx/serialize)
(b/into [])))))
(let [expected-result [[1 3 5] [2 4 6]]
sleepy-o #(f/future-generator*
future-call
(fn [o]
(doseq [x %]
(Thread/sleep 10)
(rx/on-next o x))))
make-inputs (fn [] (mapv sleepy-o expected-result))
make-output (fn [r] [(keep #{1 3 5} r)
(keep #{2 4 6} r)])]
(deftest test-merge*
(is (= expected-result
(->> (make-inputs)
(rx/seq->o)
(rx/merge*)
(b/into [])
(make-output)))))
(deftest test-merge
(is (= expected-result
(->> (make-inputs)
(apply rx/merge)
(b/into [])
(make-output)))))
(deftest test-merge-delay-error*
(is (= expected-result
(->> (make-inputs)
(rx/seq->o)
(rx/merge-delay-error*)
(b/into [])
(make-output)))))
(deftest test-merge-delay-error
(is (= expected-result
(->> (make-inputs)
(apply rx/merge-delay-error)
(b/into [])
(make-output))))))
(deftest test-generator
(testing "calls on-completed automatically"
(let [o (rx/generator [o])
called (atom nil)]
(rx/subscribe o (fn [v]) (fn [_]) #(reset! called "YES"))
(is (= "YES" @called))))
(testing "exceptions automatically go to on-error"
(let [expected (IllegalArgumentException. "hi")
actual (atom nil)]
(rx/subscribe (rx/generator [o] (throw expected))
#()
#(reset! actual %))
(is (identical? expected @actual)))))
(deftest test-seq->o
(is (= [] (b/into [] (rx/seq->o []))))
(is (= [] (b/into [] (rx/seq->o nil))))
(is (= [\a \b \c] (b/into [] (rx/seq->o "abc"))))
(is (= [0 1 2 3] (b/first (rx/into [] (rx/seq->o (range 4))))))
(is (= #{0 1 2 3} (b/first (rx/into #{} (rx/seq->o (range 4))))))
(is (= {:a 1 :b 2 :c 3} (b/first (rx/into {} (rx/seq->o [[:a 1] [:b 2] [:c 3]]))))))
(deftest test-return
(is (= [0] (b/into [] (rx/return 0)))))
(deftest test-cache
(let [value (atom 0)
o (->>
(rx/return 0)
(rx/map (fn [x] (swap! value inc)))
(rx/cache))]
(is (= 1 (b/single o)))
(is (= 1 @value))
(is (= 1 (b/single o)))
(is (= 1 @value))
(is (= 1 (b/single o)))))
(deftest test-cons
(is (= [1] (b/into [] (rx/cons 1 (rx/empty)))))
(is (= [1 2 3 4] (b/into [] (rx/cons 1 (rx/seq->o [2 3 4]))))))
(deftest test-concat
(is (= [:q :r]
(b/into [] (rx/concat (rx/seq->o [:q :r])))))
(is (= [:q :r 1 2 3]
(b/into [] (rx/concat (rx/seq->o [:q :r])
(rx/seq->o [1 2 3]))))))
(deftest test-concat*
(is (= [:q :r]
(b/into [] (rx/concat* (rx/return (rx/seq->o [:q :r]))))))
(is (= [:q :r 1 2 3]
(b/into [] (rx/concat* (rx/seq->o [(rx/seq->o [:q :r])
(rx/seq->o [1 2 3])]))))))
(deftest test-count
(are [xs] (= (count xs) (->> xs (rx/seq->o) (rx/count) (b/single)))
[]
[1]
[5 6 7]
(range 10000)))
(deftest test-cycle
(is (= [1 2 3 1 2 3 1 2 3 1 2]
(->> [1 2 3]
(rx/seq->o)
(rx/cycle)
(rx/take 11)
(b/into [])))))
(deftest test-distinct
(let [input [{:a 1} {:a 1} {:b 1} {"a" (int 1)} {:a (int 1)}]]
(is (= (distinct input)
(->> input
(rx/seq->o)
(rx/distinct)
(b/into [])))))
(let [input [{:name "<NAME>" :x 2} {:name "<NAME>" :x 99} {:name "<NAME>" :x 3}]]
(is (= [{:name "<NAME>" :x 2} {:name "<NAME>" :x 99}]
(->> input
(rx/seq->o)
(rx/distinct :name)
(b/into []))))))
(deftest test-do
(testing "calls a function with each element"
(let [collected (atom [])]
(is (= [1 2 3]
(->> (rx/seq->o [1 2 3])
(rx/do (fn [v]
(swap! collected conj (* 2 v))))
(rx/do (partial println "GOT"))
(b/into []))))
(is (= [2 4 6] @collected))))
(testing "ends sequence with onError if action code throws an exception"
(let [collected (atom [])
o (->> (rx/seq->o [1 2 3])
(rx/do (fn [v]
(if (= v 2)
(throw (IllegalStateException. (str "blah" v)))
(swap! collected conj (* 99 v))))))]
(is (thrown-with-msg? IllegalStateException #"blah2"
(b/into [] o)))
(is (= [99] @collected)))))
(deftest test-drop-while
(is (= (into [] (drop-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/drop-while even? (rx/seq->o [2 4 6 8 1 2 3])))))
(is (= (into [] (drop-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/drop-while even? (rx/seq->o [2 4 6 8 1 2 3]))))))
(deftest test-every?
(are [xs p result] (= result (->> xs (rx/seq->o) (rx/every? p) (b/single)))
[2 4 6 8] even? true
[2 4 3 8] even? false
[1 2 3 4] #{1 2 3 4} true
[1 2 3 4] #{1 3 4} false))
(deftest test-filter
(is (= (into [] (->> [:a :b :c :d :e :f :G :e]
(filter #{:b :e :G})))
(b/into [] (->> (rx/seq->o [:a :b :c :d :e :f :G :e])
(rx/filter #{:b :e :G}))))))
(deftest test-first
(is (= [3]
(b/into [] (rx/first (rx/seq->o [3 4 5])))))
(is (= []
(b/into [] (rx/first (rx/empty))))))
(deftest test-group-by
(let [xs [{:k :a :v 1} {:k :b :v 2} {:k :a :v 3} {:k :c :v 4}]]
(testing "with just a key-fn"
(is (= [[:a {:k :a :v 1}]
[:b {:k :b :v 2}]
[:a {:k :a :v 3}]
[:c {:k :c :v 4}]]
(->> xs
(rx/seq->o)
(rx/group-by :k)
(rx/mapcat (fn [[k vo :as me]]
(is (instance? clojure.lang.MapEntry me))
(rx/map #(vector k %) vo)))
(b/into [])))))
; TODO reinstate once this is implemented
; see https://github.com/Netflix/RxJava/commit/02ccc4d727a9297f14219549208757c6e0efce2a
#_(testing "with a val-fn"
(is (= [[:a 1]
[:b 2]
[:a 3]
[:c 4]]
(->> xs
(rx/seq->o)
(rx/group-by :k :v)
(rx/mapcat (fn [[k vo :as me]]
(is (instance? clojure.lang.MapEntry me))
(rx/map #(vector k %) vo)))
(b/into [])))))))
(deftest test-interleave
(are [inputs] (= (apply interleave inputs)
(->> (apply rx/interleave (map rx/seq->o inputs))
(b/into [])))
[[] []]
[[] [1]]
[(range 5) (range 10) (range 10) (range 3)]
[(range 50) (range 10)]
[(range 5) (range 10 60) (range 10) (range 50)])
; one-arg case, not supported by clojure.core/interleave
(is (= (range 10)
(->> (rx/interleave (rx/seq->o (range 10)))
(b/into [])))))
(deftest test-interleave*
(are [inputs] (= (apply interleave inputs)
(->> (rx/interleave* (->> inputs
(map rx/seq->o)
(rx/seq->o)))
(b/into [])))
[[] []]
[[] [1]]
[(range 5) (range 10) (range 10) (range 3)]
[(range 50) (range 10)]
[(range 5) (range 10 60) (range 10) (range 50)]))
(deftest test-interpose
(is (= (interpose \, [1 2 3])
(b/into [] (rx/interpose \, (rx/seq->o [1 2 3]))))))
(deftest test-into
(are [input to] (= (into to input)
(b/single (rx/into to (rx/seq->o input))))
[6 7 8] [9 10 [11]]
#{} [1 2 3 2 4 5]
{} [[1 2] [3 2] [4 5]]
{} []
'() (range 50)))
(deftest test-iterate
(are [f x n] (= (->> (iterate f x) (take n))
(->> (rx/iterate f x) (rx/take n) (b/into [])))
inc 0 10
dec 20 100
#(conj % (count %)) [] 5
#(cons (count %) % ) nil 5))
(deftest test-keep
(is (= (into [] (keep identity [true true false]))
(b/into [] (rx/keep identity (rx/seq->o [true true false])))))
(is (= (into [] (keep #(if (even? %) (* 2 %)) (range 9)))
(b/into [] (rx/keep #(if (even? %) (* 2 %)) (rx/seq->o (range 9)))))))
(deftest test-keep-indexed
(is (= (into [] (keep-indexed (fn [i v]
(if (even? i) v))
[true true false]))
(b/into [] (rx/keep-indexed (fn [i v]
(if (even? i) v))
(rx/seq->o [true true false]))))))
(deftest test-map
(is (= (into {} (map (juxt identity name)
[:q :r :s :t :u]))
(b/into {} (rx/map (juxt identity name)
(rx/seq->o [:q :r :s :t :u])))))
(is (= (into [] (map vector
[:q :r :s :t :u]
(range 10)
["a" "b" "c" "d" "e"] ))
(b/into [] (rx/map vector
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o (range 10) )
(rx/seq->o ["a" "b" "c" "d" "e"] )))))
; check > 4 arg case
(is (= (into [] (map vector
[:q :r :s :t :u]
[:q :r :s :t :u]
[:q :r :s :t :u]
(range 10)
(range 10)
(range 10)
["a" "b" "c" "d" "e"]
["a" "b" "c" "d" "e"]
["a" "b" "c" "d" "e"]))
(b/into [] (rx/map vector
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o (range 10))
(rx/seq->o (range 10))
(rx/seq->o (range 10))
(rx/seq->o ["a" "b" "c" "d" "e"])
(rx/seq->o ["a" "b" "c" "d" "e"])
(rx/seq->o ["a" "b" "c" "d" "e"]))))))
(deftest test-map*
(is (= [[1 2 3 4 5 6 7 8]]
(b/into [] (rx/map* vector
(rx/seq->o [(rx/seq->o [1])
(rx/seq->o [2])
(rx/seq->o [3])
(rx/seq->o [4])
(rx/seq->o [5])
(rx/seq->o [6])
(rx/seq->o [7])
(rx/seq->o [8])]))))))
(deftest test-map-indexed
(is (= (map-indexed vector [:a :b :c])
(b/into [] (rx/map-indexed vector (rx/seq->o [:a :b :c])))))
(testing "exceptions from fn have error value injected"
(try
(->> (rx/seq->o [:a :b :c])
(rx/map-indexed (fn [i v]
(if (= 1 i)
(throw (java.io.FileNotFoundException. "blah")))
v))
(b/into []))
(catch java.io.FileNotFoundException e
(is (= :b (-> e .getCause .getValue)))))))
(deftest test-mapcat*
(let [f (fn [a b c d e]
[(+ a b) (+ c d) e])]
(is (= (->> (range 5)
(map (fn [_] (range 5)))
(apply mapcat f))
(->> (range 5)
(map (fn [_] (rx/seq->o (range 5))))
(rx/seq->o)
(rx/mapcat* (fn [& args] (rx/seq->o (apply f args))))
(b/into []))))))
(deftest test-mapcat
(let [f (fn [v] [v (* v v)])
xs (range 10)]
(is (= (mapcat f xs)
(b/into [] (rx/mapcat (comp rx/seq->o f) (rx/seq->o xs))))))
(let [f (fn [a b] [a b (* a b)])
as (range 10)
bs (range 15)]
(is (= (mapcat f as bs)
(b/into [] (rx/mapcat (comp rx/seq->o f)
(rx/seq->o as)
(rx/seq->o bs)))))))
(deftest test-next
(let [in [:q :r :s :t :u]]
(is (= (next in) (b/into [] (rx/next (rx/seq->o in)))))))
(deftest test-nth
(is (= [:a]
(b/into [] (rx/nth (rx/seq->o [:s :b :a :c]) 2))))
(is (= [:fallback]
(b/into [] (rx/nth (rx/seq->o [:s :b :a :c]) 25 :fallback)))))
(deftest test-rest
(let [in [:q :r :s :t :u]]
(is (= (rest in) (b/into [] (rx/rest (rx/seq->o in)))))))
(deftest test-partition-all
(are [input-size part-size step] (= (->> (range input-size)
(partition-all part-size step))
(->> (range input-size)
(rx/seq->o)
(rx/partition-all part-size step)
(rx/map #(rx/into [] %))
(rx/concat*)
(b/into [])))
0 1 1
10 2 2
10 3 2
15 30 4)
(are [input-size part-size] (= (->> (range input-size)
(partition-all part-size))
(->> (range input-size)
(rx/seq->o)
(rx/partition-all part-size)
(rx/map #(rx/into [] %))
(rx/concat*)
(b/into [])))
0 1
10 2
10 3
15 30))
(deftest test-range
(are [start end step] (= (range start end step)
(->> (rx/range start end step) (b/into [])))
0 10 2
0 -100 -1
5 100 9)
(are [start end] (= (range start end)
(->> (rx/range start end) (b/into [])))
0 10
0 -100
5 100)
(are [start] (= (->> (range start) (take 100))
(->> (rx/range start) (rx/take 100) (b/into [])))
50
0
5
-20)
(is (= (->> (range) (take 500))
(->> (rx/range) (rx/take 500) (b/into [])))))
(deftest test-reduce
(is (= (reduce + 0 (range 4))
(b/first (rx/reduce + 0 (rx/seq->o (range 4)))))))
(deftest test-reductions
(is (= (into [] (reductions + 0 (range 4)))
(b/into [] (rx/reductions + 0 (rx/seq->o (range 4)))))))
(deftest test-some
(is (= [:r] (b/into [] (rx/some #{:r :s :t} (rx/seq->o [:q :v :r])))))
(is (= [] (b/into [] (rx/some #{:r :s :t} (rx/seq->o [:q :v]))))))
(deftest test-sort
(are [in cmp] (= (if cmp
(sort cmp in)
(sort in))
(->> in
(rx/seq->o)
(#(if cmp (rx/sort cmp %) (rx/sort %)))
(b/into [])))
[] nil
[] (comp - compare)
[3 1 2] nil
[1 2 3] nil
[1 2 3] (comp - compare)
[2 1 3] (comp - compare)))
(deftest test-sort-by
(are [rin cmp] (let [in (map #(hash-map :foo %) rin)]
(= (if cmp
(sort-by :foo cmp in)
(sort-by :foo in))
(->> in
(rx/seq->o)
(#(if cmp (rx/sort-by :foo cmp %) (rx/sort-by :foo %)))
(b/into []))))
[] nil
[] (comp - compare)
[3 1 2] nil
[1 2 3] nil
[1 2 3] (comp - compare)
[2 1 3] (comp - compare)))
(deftest test-split-with
(is (= (split-with (partial >= 3) (range 6))
(->> (rx/seq->o (range 6))
(rx/split-with (partial >= 3))
b/first
(map (partial b/into []))))))
(deftest test-take-while
(is (= (into [] (take-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/take-while even? (rx/seq->o [2 4 6 8 1 2 3]))))))
(deftest test-throw
(let [expected (IllegalArgumentException. "HI")
called (atom nil)]
(rx/subscribe (rx/throw expected)
(fn [_])
(fn [e] (reset! called expected))
(fn [_]))
(is (identical? expected @called))))
(deftest test-catch*
(testing "Is just a passthrough if there's no error"
(is (= [1 2 3]
(->> (rx/seq->o [1 2 3])
(rx/catch* Exception (fn [e] (throw "OH NO")))
(b/into [])))))
(testing "Can catch a particular exception type and continue with an observable"
(is (= [1 2 4 5 6 "foo"]
(->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o (IllegalStateException. "foo")))
(rx/catch* IllegalStateException
(fn [e]
(rx/seq->o [4 5 6 (.getMessage e)])))
(b/into [])))))
(testing "if exception isn't matched, it's passed to on-error"
(let [expected (IllegalArgumentException. "HI")
called (atom nil)]
(rx/subscribe (->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o expected))
(rx/catch* IllegalStateException (fn [e]
(rx/return "WAT?"))))
(fn [_])
(fn [e] (reset! called expected))
(fn [_]))
(is (identical? expected @called))))
(testing "if p returns Throwable, that's passed as e"
(let [cause (IllegalArgumentException. "HI")
wrapper (java.util.concurrent.ExecutionException. cause)]
(is (= [cause]
(->> (rx/throw wrapper)
(rx/catch #(.getCause %) e
(rx/return e))
(b/into [])))))))
(deftest test-finally
(testing "Supports a finally clause"
(testing "called on completed"
(let [completed (atom nil)
called (atom nil)]
(rx/subscribe (->> (rx/seq->o [1 2 3])
(rx/finally* (fn [] (reset! called (str "got it")))))
(fn [_])
(fn [_] (throw (IllegalStateException. "WAT")))
(fn [] (reset! completed "DONE")))
(is (= "got it" @called))
(is (= "DONE" @completed))))
(testing "called on error"
(let [expected (IllegalStateException. "expected")
completed (atom nil)
called (atom nil)]
(rx/subscribe (->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o expected))
(rx/finally
(reset! called "got it")))
(fn [_])
(fn [e] (reset! completed e))
(fn [] (throw (IllegalStateException. "WAT"))))
(is (= "got it" @called))
(is (identical? expected @completed))))))
;################################################################################
(deftest test-graph-imports
(is (= 99
(-> {:a {:deps [] :factory (fn [_] (rx/return 99))}}
rx/let-o*
:a
b/single)))
(is (= 100
(b/single (rx/let-o [?a (rx/return 100)]
?a)))))
;################################################################################
(deftest test-realized-imports
(is (= {:a 1 :b 2}
(->> (rx/let-realized [a (rx/return 1)
b (rx/return 2)]
{:a a :b b})
b/single))))
| true |
(ns rx.lang.clojure.core-test
(:require [rx.lang.clojure.core :as rx]
[rx.lang.clojure.blocking :as b]
[rx.lang.clojure.future :as f]
[clojure.test :refer [deftest is testing are]]))
(deftest test-observable?
(is (rx/observable? (rx/return 99)))
(is (not (rx/observable? "I'm not an observable"))))
(deftest test-on-next
(testing "calls onNext"
(let [called (atom [])
o (reify rx.Observer (onNext [this value] (swap! called conj value)))]
(is (identical? o (rx/on-next o 1)))
(is (= [1] @called)))))
(deftest test-on-completed
(testing "calls onCompleted"
(let [called (atom 0)
o (reify rx.Observer (onCompleted [this] (swap! called inc)))]
(is (identical? o (rx/on-completed o)))
(is (= 1 @called)))))
(deftest test-on-error
(testing "calls onError"
(let [called (atom [])
e (java.io.FileNotFoundException. "yum")
o (reify rx.Observer (onError [this e] (swap! called conj e)))]
(is (identical? o (rx/on-error o e)))
(is (= [e] @called)))))
(deftest test-catch-error-value
(testing "if no exception, returns body"
(let [o (reify rx.Observer)]
(is (= 3 (rx/catch-error-value o 99
(+ 1 2))))))
(testing "exceptions call onError on observable and inject value in exception"
(let [called (atom [])
e (java.io.FileNotFoundException. "boo")
o (reify rx.Observer
(onError [this e]
(swap! called conj e)))
result (rx/catch-error-value o 100
(throw e))
cause (.getCause e)]
(is (identical? e result))
(is (= [e] @called))
(when (is (instance? rx.exceptions.OnErrorThrowable$OnNextValue cause))
(is (= 100 (.getValue cause)))))))
(deftest test-subscribe
(testing "subscribe overload with only onNext"
(let [o (rx/return 1)
called (atom nil)]
(rx/subscribe o (fn [v] (swap! called (fn [_] v))))
(is (= 1 @called)))))
(deftest test-fn->predicate
(are [f arg result] (= result (.call (rx/fn->predicate f) arg))
identity nil false
identity false false
identity 1 true
identity "true" true
identity true true))
(deftest test-subscription
(let [called (atom 0)
s (rx/subscription #(swap! called inc))]
(is (identical? s (rx/unsubscribe s)))
(is (= 1 @called))))
(deftest test-unsubscribed?
(let [s (rx/subscription #())]
(is (not (rx/unsubscribed? s)))
(rx/unsubscribe s)
(is (rx/unsubscribed? s))))
(deftest test-observable*
(let [o (rx/observable* (fn [s]
(rx/on-next s 0)
(rx/on-next s 1)
(when-not (rx/unsubscribed? s) (rx/on-next s 2))
(rx/on-completed s)))]
(is (= [0 1 2] (b/into [] o)))))
(deftest test-operator*
(let [o (rx/operator* #(rx/subscriber %
(fn [o v]
(if (even? v)
(rx/on-next o v)))))
result (->> (rx/seq->o [1 2 3 4 5])
(rx/lift o)
(b/into []))]
(is (= [2 4] result))))
(deftest test-serialize
; I'm going to believe serialize works and just exercise it
; here for sanity.
(is (= [1 2 3]
(->> [1 2 3]
(rx/seq->o)
(rx/serialize)
(b/into [])))))
(let [expected-result [[1 3 5] [2 4 6]]
sleepy-o #(f/future-generator*
future-call
(fn [o]
(doseq [x %]
(Thread/sleep 10)
(rx/on-next o x))))
make-inputs (fn [] (mapv sleepy-o expected-result))
make-output (fn [r] [(keep #{1 3 5} r)
(keep #{2 4 6} r)])]
(deftest test-merge*
(is (= expected-result
(->> (make-inputs)
(rx/seq->o)
(rx/merge*)
(b/into [])
(make-output)))))
(deftest test-merge
(is (= expected-result
(->> (make-inputs)
(apply rx/merge)
(b/into [])
(make-output)))))
(deftest test-merge-delay-error*
(is (= expected-result
(->> (make-inputs)
(rx/seq->o)
(rx/merge-delay-error*)
(b/into [])
(make-output)))))
(deftest test-merge-delay-error
(is (= expected-result
(->> (make-inputs)
(apply rx/merge-delay-error)
(b/into [])
(make-output))))))
(deftest test-generator
(testing "calls on-completed automatically"
(let [o (rx/generator [o])
called (atom nil)]
(rx/subscribe o (fn [v]) (fn [_]) #(reset! called "YES"))
(is (= "YES" @called))))
(testing "exceptions automatically go to on-error"
(let [expected (IllegalArgumentException. "hi")
actual (atom nil)]
(rx/subscribe (rx/generator [o] (throw expected))
#()
#(reset! actual %))
(is (identical? expected @actual)))))
(deftest test-seq->o
(is (= [] (b/into [] (rx/seq->o []))))
(is (= [] (b/into [] (rx/seq->o nil))))
(is (= [\a \b \c] (b/into [] (rx/seq->o "abc"))))
(is (= [0 1 2 3] (b/first (rx/into [] (rx/seq->o (range 4))))))
(is (= #{0 1 2 3} (b/first (rx/into #{} (rx/seq->o (range 4))))))
(is (= {:a 1 :b 2 :c 3} (b/first (rx/into {} (rx/seq->o [[:a 1] [:b 2] [:c 3]]))))))
(deftest test-return
(is (= [0] (b/into [] (rx/return 0)))))
(deftest test-cache
(let [value (atom 0)
o (->>
(rx/return 0)
(rx/map (fn [x] (swap! value inc)))
(rx/cache))]
(is (= 1 (b/single o)))
(is (= 1 @value))
(is (= 1 (b/single o)))
(is (= 1 @value))
(is (= 1 (b/single o)))))
(deftest test-cons
(is (= [1] (b/into [] (rx/cons 1 (rx/empty)))))
(is (= [1 2 3 4] (b/into [] (rx/cons 1 (rx/seq->o [2 3 4]))))))
(deftest test-concat
(is (= [:q :r]
(b/into [] (rx/concat (rx/seq->o [:q :r])))))
(is (= [:q :r 1 2 3]
(b/into [] (rx/concat (rx/seq->o [:q :r])
(rx/seq->o [1 2 3]))))))
(deftest test-concat*
(is (= [:q :r]
(b/into [] (rx/concat* (rx/return (rx/seq->o [:q :r]))))))
(is (= [:q :r 1 2 3]
(b/into [] (rx/concat* (rx/seq->o [(rx/seq->o [:q :r])
(rx/seq->o [1 2 3])]))))))
(deftest test-count
(are [xs] (= (count xs) (->> xs (rx/seq->o) (rx/count) (b/single)))
[]
[1]
[5 6 7]
(range 10000)))
(deftest test-cycle
(is (= [1 2 3 1 2 3 1 2 3 1 2]
(->> [1 2 3]
(rx/seq->o)
(rx/cycle)
(rx/take 11)
(b/into [])))))
(deftest test-distinct
(let [input [{:a 1} {:a 1} {:b 1} {"a" (int 1)} {:a (int 1)}]]
(is (= (distinct input)
(->> input
(rx/seq->o)
(rx/distinct)
(b/into [])))))
(let [input [{:name "PI:NAME:<NAME>END_PI" :x 2} {:name "PI:NAME:<NAME>END_PI" :x 99} {:name "PI:NAME:<NAME>END_PI" :x 3}]]
(is (= [{:name "PI:NAME:<NAME>END_PI" :x 2} {:name "PI:NAME:<NAME>END_PI" :x 99}]
(->> input
(rx/seq->o)
(rx/distinct :name)
(b/into []))))))
(deftest test-do
(testing "calls a function with each element"
(let [collected (atom [])]
(is (= [1 2 3]
(->> (rx/seq->o [1 2 3])
(rx/do (fn [v]
(swap! collected conj (* 2 v))))
(rx/do (partial println "GOT"))
(b/into []))))
(is (= [2 4 6] @collected))))
(testing "ends sequence with onError if action code throws an exception"
(let [collected (atom [])
o (->> (rx/seq->o [1 2 3])
(rx/do (fn [v]
(if (= v 2)
(throw (IllegalStateException. (str "blah" v)))
(swap! collected conj (* 99 v))))))]
(is (thrown-with-msg? IllegalStateException #"blah2"
(b/into [] o)))
(is (= [99] @collected)))))
(deftest test-drop-while
(is (= (into [] (drop-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/drop-while even? (rx/seq->o [2 4 6 8 1 2 3])))))
(is (= (into [] (drop-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/drop-while even? (rx/seq->o [2 4 6 8 1 2 3]))))))
(deftest test-every?
(are [xs p result] (= result (->> xs (rx/seq->o) (rx/every? p) (b/single)))
[2 4 6 8] even? true
[2 4 3 8] even? false
[1 2 3 4] #{1 2 3 4} true
[1 2 3 4] #{1 3 4} false))
(deftest test-filter
(is (= (into [] (->> [:a :b :c :d :e :f :G :e]
(filter #{:b :e :G})))
(b/into [] (->> (rx/seq->o [:a :b :c :d :e :f :G :e])
(rx/filter #{:b :e :G}))))))
(deftest test-first
(is (= [3]
(b/into [] (rx/first (rx/seq->o [3 4 5])))))
(is (= []
(b/into [] (rx/first (rx/empty))))))
(deftest test-group-by
(let [xs [{:k :a :v 1} {:k :b :v 2} {:k :a :v 3} {:k :c :v 4}]]
(testing "with just a key-fn"
(is (= [[:a {:k :a :v 1}]
[:b {:k :b :v 2}]
[:a {:k :a :v 3}]
[:c {:k :c :v 4}]]
(->> xs
(rx/seq->o)
(rx/group-by :k)
(rx/mapcat (fn [[k vo :as me]]
(is (instance? clojure.lang.MapEntry me))
(rx/map #(vector k %) vo)))
(b/into [])))))
; TODO reinstate once this is implemented
; see https://github.com/Netflix/RxJava/commit/02ccc4d727a9297f14219549208757c6e0efce2a
#_(testing "with a val-fn"
(is (= [[:a 1]
[:b 2]
[:a 3]
[:c 4]]
(->> xs
(rx/seq->o)
(rx/group-by :k :v)
(rx/mapcat (fn [[k vo :as me]]
(is (instance? clojure.lang.MapEntry me))
(rx/map #(vector k %) vo)))
(b/into [])))))))
(deftest test-interleave
(are [inputs] (= (apply interleave inputs)
(->> (apply rx/interleave (map rx/seq->o inputs))
(b/into [])))
[[] []]
[[] [1]]
[(range 5) (range 10) (range 10) (range 3)]
[(range 50) (range 10)]
[(range 5) (range 10 60) (range 10) (range 50)])
; one-arg case, not supported by clojure.core/interleave
(is (= (range 10)
(->> (rx/interleave (rx/seq->o (range 10)))
(b/into [])))))
(deftest test-interleave*
(are [inputs] (= (apply interleave inputs)
(->> (rx/interleave* (->> inputs
(map rx/seq->o)
(rx/seq->o)))
(b/into [])))
[[] []]
[[] [1]]
[(range 5) (range 10) (range 10) (range 3)]
[(range 50) (range 10)]
[(range 5) (range 10 60) (range 10) (range 50)]))
(deftest test-interpose
(is (= (interpose \, [1 2 3])
(b/into [] (rx/interpose \, (rx/seq->o [1 2 3]))))))
(deftest test-into
(are [input to] (= (into to input)
(b/single (rx/into to (rx/seq->o input))))
[6 7 8] [9 10 [11]]
#{} [1 2 3 2 4 5]
{} [[1 2] [3 2] [4 5]]
{} []
'() (range 50)))
(deftest test-iterate
(are [f x n] (= (->> (iterate f x) (take n))
(->> (rx/iterate f x) (rx/take n) (b/into [])))
inc 0 10
dec 20 100
#(conj % (count %)) [] 5
#(cons (count %) % ) nil 5))
(deftest test-keep
(is (= (into [] (keep identity [true true false]))
(b/into [] (rx/keep identity (rx/seq->o [true true false])))))
(is (= (into [] (keep #(if (even? %) (* 2 %)) (range 9)))
(b/into [] (rx/keep #(if (even? %) (* 2 %)) (rx/seq->o (range 9)))))))
(deftest test-keep-indexed
(is (= (into [] (keep-indexed (fn [i v]
(if (even? i) v))
[true true false]))
(b/into [] (rx/keep-indexed (fn [i v]
(if (even? i) v))
(rx/seq->o [true true false]))))))
(deftest test-map
(is (= (into {} (map (juxt identity name)
[:q :r :s :t :u]))
(b/into {} (rx/map (juxt identity name)
(rx/seq->o [:q :r :s :t :u])))))
(is (= (into [] (map vector
[:q :r :s :t :u]
(range 10)
["a" "b" "c" "d" "e"] ))
(b/into [] (rx/map vector
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o (range 10) )
(rx/seq->o ["a" "b" "c" "d" "e"] )))))
; check > 4 arg case
(is (= (into [] (map vector
[:q :r :s :t :u]
[:q :r :s :t :u]
[:q :r :s :t :u]
(range 10)
(range 10)
(range 10)
["a" "b" "c" "d" "e"]
["a" "b" "c" "d" "e"]
["a" "b" "c" "d" "e"]))
(b/into [] (rx/map vector
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o [:q :r :s :t :u])
(rx/seq->o (range 10))
(rx/seq->o (range 10))
(rx/seq->o (range 10))
(rx/seq->o ["a" "b" "c" "d" "e"])
(rx/seq->o ["a" "b" "c" "d" "e"])
(rx/seq->o ["a" "b" "c" "d" "e"]))))))
(deftest test-map*
(is (= [[1 2 3 4 5 6 7 8]]
(b/into [] (rx/map* vector
(rx/seq->o [(rx/seq->o [1])
(rx/seq->o [2])
(rx/seq->o [3])
(rx/seq->o [4])
(rx/seq->o [5])
(rx/seq->o [6])
(rx/seq->o [7])
(rx/seq->o [8])]))))))
(deftest test-map-indexed
(is (= (map-indexed vector [:a :b :c])
(b/into [] (rx/map-indexed vector (rx/seq->o [:a :b :c])))))
(testing "exceptions from fn have error value injected"
(try
(->> (rx/seq->o [:a :b :c])
(rx/map-indexed (fn [i v]
(if (= 1 i)
(throw (java.io.FileNotFoundException. "blah")))
v))
(b/into []))
(catch java.io.FileNotFoundException e
(is (= :b (-> e .getCause .getValue)))))))
(deftest test-mapcat*
(let [f (fn [a b c d e]
[(+ a b) (+ c d) e])]
(is (= (->> (range 5)
(map (fn [_] (range 5)))
(apply mapcat f))
(->> (range 5)
(map (fn [_] (rx/seq->o (range 5))))
(rx/seq->o)
(rx/mapcat* (fn [& args] (rx/seq->o (apply f args))))
(b/into []))))))
(deftest test-mapcat
(let [f (fn [v] [v (* v v)])
xs (range 10)]
(is (= (mapcat f xs)
(b/into [] (rx/mapcat (comp rx/seq->o f) (rx/seq->o xs))))))
(let [f (fn [a b] [a b (* a b)])
as (range 10)
bs (range 15)]
(is (= (mapcat f as bs)
(b/into [] (rx/mapcat (comp rx/seq->o f)
(rx/seq->o as)
(rx/seq->o bs)))))))
(deftest test-next
(let [in [:q :r :s :t :u]]
(is (= (next in) (b/into [] (rx/next (rx/seq->o in)))))))
(deftest test-nth
(is (= [:a]
(b/into [] (rx/nth (rx/seq->o [:s :b :a :c]) 2))))
(is (= [:fallback]
(b/into [] (rx/nth (rx/seq->o [:s :b :a :c]) 25 :fallback)))))
(deftest test-rest
(let [in [:q :r :s :t :u]]
(is (= (rest in) (b/into [] (rx/rest (rx/seq->o in)))))))
(deftest test-partition-all
(are [input-size part-size step] (= (->> (range input-size)
(partition-all part-size step))
(->> (range input-size)
(rx/seq->o)
(rx/partition-all part-size step)
(rx/map #(rx/into [] %))
(rx/concat*)
(b/into [])))
0 1 1
10 2 2
10 3 2
15 30 4)
(are [input-size part-size] (= (->> (range input-size)
(partition-all part-size))
(->> (range input-size)
(rx/seq->o)
(rx/partition-all part-size)
(rx/map #(rx/into [] %))
(rx/concat*)
(b/into [])))
0 1
10 2
10 3
15 30))
(deftest test-range
(are [start end step] (= (range start end step)
(->> (rx/range start end step) (b/into [])))
0 10 2
0 -100 -1
5 100 9)
(are [start end] (= (range start end)
(->> (rx/range start end) (b/into [])))
0 10
0 -100
5 100)
(are [start] (= (->> (range start) (take 100))
(->> (rx/range start) (rx/take 100) (b/into [])))
50
0
5
-20)
(is (= (->> (range) (take 500))
(->> (rx/range) (rx/take 500) (b/into [])))))
(deftest test-reduce
(is (= (reduce + 0 (range 4))
(b/first (rx/reduce + 0 (rx/seq->o (range 4)))))))
(deftest test-reductions
(is (= (into [] (reductions + 0 (range 4)))
(b/into [] (rx/reductions + 0 (rx/seq->o (range 4)))))))
(deftest test-some
(is (= [:r] (b/into [] (rx/some #{:r :s :t} (rx/seq->o [:q :v :r])))))
(is (= [] (b/into [] (rx/some #{:r :s :t} (rx/seq->o [:q :v]))))))
(deftest test-sort
(are [in cmp] (= (if cmp
(sort cmp in)
(sort in))
(->> in
(rx/seq->o)
(#(if cmp (rx/sort cmp %) (rx/sort %)))
(b/into [])))
[] nil
[] (comp - compare)
[3 1 2] nil
[1 2 3] nil
[1 2 3] (comp - compare)
[2 1 3] (comp - compare)))
(deftest test-sort-by
(are [rin cmp] (let [in (map #(hash-map :foo %) rin)]
(= (if cmp
(sort-by :foo cmp in)
(sort-by :foo in))
(->> in
(rx/seq->o)
(#(if cmp (rx/sort-by :foo cmp %) (rx/sort-by :foo %)))
(b/into []))))
[] nil
[] (comp - compare)
[3 1 2] nil
[1 2 3] nil
[1 2 3] (comp - compare)
[2 1 3] (comp - compare)))
(deftest test-split-with
(is (= (split-with (partial >= 3) (range 6))
(->> (rx/seq->o (range 6))
(rx/split-with (partial >= 3))
b/first
(map (partial b/into []))))))
(deftest test-take-while
(is (= (into [] (take-while even? [2 4 6 8 1 2 3]))
(b/into [] (rx/take-while even? (rx/seq->o [2 4 6 8 1 2 3]))))))
(deftest test-throw
(let [expected (IllegalArgumentException. "HI")
called (atom nil)]
(rx/subscribe (rx/throw expected)
(fn [_])
(fn [e] (reset! called expected))
(fn [_]))
(is (identical? expected @called))))
(deftest test-catch*
(testing "Is just a passthrough if there's no error"
(is (= [1 2 3]
(->> (rx/seq->o [1 2 3])
(rx/catch* Exception (fn [e] (throw "OH NO")))
(b/into [])))))
(testing "Can catch a particular exception type and continue with an observable"
(is (= [1 2 4 5 6 "foo"]
(->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o (IllegalStateException. "foo")))
(rx/catch* IllegalStateException
(fn [e]
(rx/seq->o [4 5 6 (.getMessage e)])))
(b/into [])))))
(testing "if exception isn't matched, it's passed to on-error"
(let [expected (IllegalArgumentException. "HI")
called (atom nil)]
(rx/subscribe (->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o expected))
(rx/catch* IllegalStateException (fn [e]
(rx/return "WAT?"))))
(fn [_])
(fn [e] (reset! called expected))
(fn [_]))
(is (identical? expected @called))))
(testing "if p returns Throwable, that's passed as e"
(let [cause (IllegalArgumentException. "HI")
wrapper (java.util.concurrent.ExecutionException. cause)]
(is (= [cause]
(->> (rx/throw wrapper)
(rx/catch #(.getCause %) e
(rx/return e))
(b/into [])))))))
(deftest test-finally
(testing "Supports a finally clause"
(testing "called on completed"
(let [completed (atom nil)
called (atom nil)]
(rx/subscribe (->> (rx/seq->o [1 2 3])
(rx/finally* (fn [] (reset! called (str "got it")))))
(fn [_])
(fn [_] (throw (IllegalStateException. "WAT")))
(fn [] (reset! completed "DONE")))
(is (= "got it" @called))
(is (= "DONE" @completed))))
(testing "called on error"
(let [expected (IllegalStateException. "expected")
completed (atom nil)
called (atom nil)]
(rx/subscribe (->> (rx/generator [o]
(rx/on-next o 1)
(rx/on-next o 2)
(rx/on-error o expected))
(rx/finally
(reset! called "got it")))
(fn [_])
(fn [e] (reset! completed e))
(fn [] (throw (IllegalStateException. "WAT"))))
(is (= "got it" @called))
(is (identical? expected @completed))))))
;################################################################################
(deftest test-graph-imports
(is (= 99
(-> {:a {:deps [] :factory (fn [_] (rx/return 99))}}
rx/let-o*
:a
b/single)))
(is (= 100
(b/single (rx/let-o [?a (rx/return 100)]
?a)))))
;################################################################################
(deftest test-realized-imports
(is (= {:a 1 :b 2}
(->> (rx/let-realized [a (rx/return 1)
b (rx/return 2)]
{:a a :b b})
b/single))))
|
[
{
"context": "--------------------------------\n;; Copyright 2017 Greg Haskins\n;;\n;; SPDX-License-Identifier: Apache-2.0\n;;-----",
"end": 110,
"score": 0.9998193979263306,
"start": 98,
"tag": "NAME",
"value": "Greg Haskins"
}
] |
examples/example02/client/cljs/project.clj
|
simonmulser/fabric-chaintool
| 0 |
;;-----------------------------------------------------------------------------
;; Copyright 2017 Greg Haskins
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(defproject example02 "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.542"]
[org.clojure/tools.cli "0.3.5"]
[funcool/promesa "1.8.1"]]
:plugins [[lein-nodecljs "0.7.0"]]
:npm {:dependencies [[source-map-support "0.4.15"]
[protobufjs "5.0.1"]
[read-yaml "1.1.0"]
[fabric-client "1.0.0-beta"]]}
:source-paths ["src" "target/classes"]
:clean-targets ["out" "release"]
:target-path "target"
:nodecljs {:main example02.main
:files ["protos"]})
|
25761
|
;;-----------------------------------------------------------------------------
;; Copyright 2017 <NAME>
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(defproject example02 "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.542"]
[org.clojure/tools.cli "0.3.5"]
[funcool/promesa "1.8.1"]]
:plugins [[lein-nodecljs "0.7.0"]]
:npm {:dependencies [[source-map-support "0.4.15"]
[protobufjs "5.0.1"]
[read-yaml "1.1.0"]
[fabric-client "1.0.0-beta"]]}
:source-paths ["src" "target/classes"]
:clean-targets ["out" "release"]
:target-path "target"
:nodecljs {:main example02.main
:files ["protos"]})
| true |
;;-----------------------------------------------------------------------------
;; Copyright 2017 PI:NAME:<NAME>END_PI
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(defproject example02 "0.1.0-SNAPSHOT"
:description "FIXME: write this!"
:url "http://example.com/FIXME"
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/clojurescript "1.9.542"]
[org.clojure/tools.cli "0.3.5"]
[funcool/promesa "1.8.1"]]
:plugins [[lein-nodecljs "0.7.0"]]
:npm {:dependencies [[source-map-support "0.4.15"]
[protobufjs "5.0.1"]
[read-yaml "1.1.0"]
[fabric-client "1.0.0-beta"]]}
:source-paths ["src" "target/classes"]
:clean-targets ["out" "release"]
:target-path "target"
:nodecljs {:main example02.main
:files ["protos"]})
|
[
{
"context": "]\n (set (filter vowel? word)))\n\n(def name-list [\"Yourtion\", \"Sophia\"])\n\n(defn run []\n (println \"vowelsInWo",
"end": 312,
"score": 0.9982621669769287,
"start": 304,
"tag": "NAME",
"value": "Yourtion"
},
{
"context": "lter vowel? word)))\n\n(def name-list [\"Yourtion\", \"Sophia\"])\n\n(defn run []\n (println \"vowelsInWord: \" (vow",
"end": 322,
"score": 0.9998095631599426,
"start": 316,
"tag": "NAME",
"value": "Sophia"
},
{
"context": "n []\n (println \"vowelsInWord: \" (vowels-in-word \"Yourtion\"))\n (println)\n (println \"person: \" name-list)\n ",
"end": 393,
"score": 0.754496693611145,
"start": 385,
"tag": "NAME",
"value": "Yourtion"
}
] |
Clojure/src/com/yourtion/Pattern05/higher_order_functions.clj
|
yourtion/LearningFunctionalProgramming
| 14 |
(ns com.yourtion.Pattern05.higher-order-functions)
(defn sum-sequence [s]
{:pre [(not (empty? s))]}
(reduce + s))
(defn prepend-hello [names]
(map (fn [name] (str "Hello, " name)) names))
(def vowel? #{\a \e \i \o \u})
(defn vowels-in-word [word]
(set (filter vowel? word)))
(def name-list ["Yourtion", "Sophia"])
(defn run []
(println "vowelsInWord: " (vowels-in-word "Yourtion"))
(println)
(println "person: " name-list)
(println "prependHello: " (prepend-hello name-list))
(println)
(println "sumSequence: " (sum-sequence [1 2 3 4 5])))
|
48062
|
(ns com.yourtion.Pattern05.higher-order-functions)
(defn sum-sequence [s]
{:pre [(not (empty? s))]}
(reduce + s))
(defn prepend-hello [names]
(map (fn [name] (str "Hello, " name)) names))
(def vowel? #{\a \e \i \o \u})
(defn vowels-in-word [word]
(set (filter vowel? word)))
(def name-list ["<NAME>", "<NAME>"])
(defn run []
(println "vowelsInWord: " (vowels-in-word "<NAME>"))
(println)
(println "person: " name-list)
(println "prependHello: " (prepend-hello name-list))
(println)
(println "sumSequence: " (sum-sequence [1 2 3 4 5])))
| true |
(ns com.yourtion.Pattern05.higher-order-functions)
(defn sum-sequence [s]
{:pre [(not (empty? s))]}
(reduce + s))
(defn prepend-hello [names]
(map (fn [name] (str "Hello, " name)) names))
(def vowel? #{\a \e \i \o \u})
(defn vowels-in-word [word]
(set (filter vowel? word)))
(def name-list ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"])
(defn run []
(println "vowelsInWord: " (vowels-in-word "PI:NAME:<NAME>END_PI"))
(println)
(println "person: " name-list)
(println "prependHello: " (prepend-hello name-list))
(println)
(println "sumSequence: " (sum-sequence [1 2 3 4 5])))
|
[
{
"context": "est :user {:_id \"5515a24e78309661a4aa7e0d\" :name \"Don Draper\"}))))\n\n;; Standardize error response\n(defn error-",
"end": 412,
"score": 0.9944684505462646,
"start": 402,
"tag": "NAME",
"value": "Don Draper"
}
] |
src/outfolio/api.clj
|
nicolashery/outfolio-clj
| 0 |
(ns outfolio.api
(:require [compojure.core :refer [defroutes GET POST PUT DELETE ANY]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.util.response :refer [response status]]
[outfolio.db :as db]))
;; Fake auth middleware
(defn wrap-auth [handler]
(fn [request]
(handler (assoc request :user {:_id "5515a24e78309661a4aa7e0d" :name "Don Draper"}))))
;; Standardize error response
(defn error-response [status-code error-name error-description]
(status (response {:error {:name error-name
:description error-description}})
status-code))
(defn get-cards [request]
(let [user-id (get-in request [:user :_id])]
(response (db/get-cards-owned-by user-id))))
(defn post-card [request]
(let [owner (:user request)
;; TODO: some validation of request body
card (-> (:body request)
(assoc :owner owner)
(db/create-card))]
(status (response card) 201)))
;; Middleware to get card from card-id in request params
;; and check ownership with current user
(defn wrap-card [handler]
(fn [request]
(let [user-id (get-in request [:user :_id])
card-id (get-in request [:params :card-id])
card (db/get-card card-id)
card-owned-by-user? (= user-id (get-in card [:owner :_id]))
card (if card-owned-by-user? card)]
(if (nil? card)
(error-response 404 "CardNotFound" "No matching card for that id")
(handler (assoc request :card card))))))
(defn get-card [request]
(response (:card request)))
(defn put-card [request]
(let [card-id (get-in request [:card :_id])
card-updates (:body request)]
(response (db/update-card card-id card-updates))))
(defn delete-card [request]
(let [card-id (get-in request [:card :_id])]
(do
(db/remove-card card-id)
(status (response "") 204))))
(defn not-found [request]
(error-response 404 "RouteNotFound" "The API route requested does not exist"))
(defroutes api-routes*
(GET "/cards" [] get-cards)
(POST "/cards" [] post-card)
(GET "/cards/:card-id" [] (wrap-card get-card))
(PUT "/cards/:card-id" [] (wrap-card put-card))
(DELETE "/cards/:card-id" [] (wrap-card delete-card))
(ANY "*" [] not-found))
(def api-routes
(-> api-routes*
(wrap-auth)
(wrap-json-body)
(wrap-json-response)))
|
122395
|
(ns outfolio.api
(:require [compojure.core :refer [defroutes GET POST PUT DELETE ANY]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.util.response :refer [response status]]
[outfolio.db :as db]))
;; Fake auth middleware
(defn wrap-auth [handler]
(fn [request]
(handler (assoc request :user {:_id "5515a24e78309661a4aa7e0d" :name "<NAME>"}))))
;; Standardize error response
(defn error-response [status-code error-name error-description]
(status (response {:error {:name error-name
:description error-description}})
status-code))
(defn get-cards [request]
(let [user-id (get-in request [:user :_id])]
(response (db/get-cards-owned-by user-id))))
(defn post-card [request]
(let [owner (:user request)
;; TODO: some validation of request body
card (-> (:body request)
(assoc :owner owner)
(db/create-card))]
(status (response card) 201)))
;; Middleware to get card from card-id in request params
;; and check ownership with current user
(defn wrap-card [handler]
(fn [request]
(let [user-id (get-in request [:user :_id])
card-id (get-in request [:params :card-id])
card (db/get-card card-id)
card-owned-by-user? (= user-id (get-in card [:owner :_id]))
card (if card-owned-by-user? card)]
(if (nil? card)
(error-response 404 "CardNotFound" "No matching card for that id")
(handler (assoc request :card card))))))
(defn get-card [request]
(response (:card request)))
(defn put-card [request]
(let [card-id (get-in request [:card :_id])
card-updates (:body request)]
(response (db/update-card card-id card-updates))))
(defn delete-card [request]
(let [card-id (get-in request [:card :_id])]
(do
(db/remove-card card-id)
(status (response "") 204))))
(defn not-found [request]
(error-response 404 "RouteNotFound" "The API route requested does not exist"))
(defroutes api-routes*
(GET "/cards" [] get-cards)
(POST "/cards" [] post-card)
(GET "/cards/:card-id" [] (wrap-card get-card))
(PUT "/cards/:card-id" [] (wrap-card put-card))
(DELETE "/cards/:card-id" [] (wrap-card delete-card))
(ANY "*" [] not-found))
(def api-routes
(-> api-routes*
(wrap-auth)
(wrap-json-body)
(wrap-json-response)))
| true |
(ns outfolio.api
(:require [compojure.core :refer [defroutes GET POST PUT DELETE ANY]]
[ring.middleware.json :refer [wrap-json-response wrap-json-body]]
[ring.util.response :refer [response status]]
[outfolio.db :as db]))
;; Fake auth middleware
(defn wrap-auth [handler]
(fn [request]
(handler (assoc request :user {:_id "5515a24e78309661a4aa7e0d" :name "PI:NAME:<NAME>END_PI"}))))
;; Standardize error response
(defn error-response [status-code error-name error-description]
(status (response {:error {:name error-name
:description error-description}})
status-code))
(defn get-cards [request]
(let [user-id (get-in request [:user :_id])]
(response (db/get-cards-owned-by user-id))))
(defn post-card [request]
(let [owner (:user request)
;; TODO: some validation of request body
card (-> (:body request)
(assoc :owner owner)
(db/create-card))]
(status (response card) 201)))
;; Middleware to get card from card-id in request params
;; and check ownership with current user
(defn wrap-card [handler]
(fn [request]
(let [user-id (get-in request [:user :_id])
card-id (get-in request [:params :card-id])
card (db/get-card card-id)
card-owned-by-user? (= user-id (get-in card [:owner :_id]))
card (if card-owned-by-user? card)]
(if (nil? card)
(error-response 404 "CardNotFound" "No matching card for that id")
(handler (assoc request :card card))))))
(defn get-card [request]
(response (:card request)))
(defn put-card [request]
(let [card-id (get-in request [:card :_id])
card-updates (:body request)]
(response (db/update-card card-id card-updates))))
(defn delete-card [request]
(let [card-id (get-in request [:card :_id])]
(do
(db/remove-card card-id)
(status (response "") 204))))
(defn not-found [request]
(error-response 404 "RouteNotFound" "The API route requested does not exist"))
(defroutes api-routes*
(GET "/cards" [] get-cards)
(POST "/cards" [] post-card)
(GET "/cards/:card-id" [] (wrap-card get-card))
(PUT "/cards/:card-id" [] (wrap-card put-card))
(DELETE "/cards/:card-id" [] (wrap-card delete-card))
(ANY "*" [] not-found))
(def api-routes
(-> api-routes*
(wrap-auth)
(wrap-json-body)
(wrap-json-response)))
|
[
{
"context": "gits\n; Date: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------",
"end": 144,
"score": 0.9947770237922668,
"start": 135,
"tag": "USERNAME",
"value": "A01371743"
},
{
"context": "e: March 17, 2016.\n; Authors:\n; A01371743 Luis Eduardo Ballinas Aguilar\n;------------------------------------------------",
"end": 174,
"score": 0.9998666048049927,
"start": 145,
"tag": "NAME",
"value": "Luis Eduardo Ballinas Aguilar"
}
] |
4clojure/problem_99.clj
|
lu15v/TC2006
| 0 |
;----------------------------------------------------------
; Problem 99: Product Digits
; Date: March 17, 2016.
; Authors:
; A01371743 Luis Eduardo Ballinas Aguilar
;----------------------------------------------------------
(use 'clojure.test)
(def problem99
(fn [a b]
(vec(map #(Character/digit % 10) (seq(str (* a b)))))))
(deftest test-problem99
(is (= (problem99 1 1) [1]))
(is (= (problem99 99 9) [8 9 1]))
(is (= (problem99 999 99) [9 8 9 0 1])))
(run-tests)
|
19705
|
;----------------------------------------------------------
; Problem 99: Product Digits
; Date: March 17, 2016.
; Authors:
; A01371743 <NAME>
;----------------------------------------------------------
(use 'clojure.test)
(def problem99
(fn [a b]
(vec(map #(Character/digit % 10) (seq(str (* a b)))))))
(deftest test-problem99
(is (= (problem99 1 1) [1]))
(is (= (problem99 99 9) [8 9 1]))
(is (= (problem99 999 99) [9 8 9 0 1])))
(run-tests)
| true |
;----------------------------------------------------------
; Problem 99: Product Digits
; Date: March 17, 2016.
; Authors:
; A01371743 PI:NAME:<NAME>END_PI
;----------------------------------------------------------
(use 'clojure.test)
(def problem99
(fn [a b]
(vec(map #(Character/digit % 10) (seq(str (* a b)))))))
(deftest test-problem99
(is (= (problem99 1 1) [1]))
(is (= (problem99 99 9) [8 9 1]))
(is (= (problem99 999 99) [9 8 9 0 1])))
(run-tests)
|
[
{
"context": "ew-space\"] [])))\n (is (= {:login {:cf-token \"TOKEN\"\n :endpoint \"URL\"}\n ",
"end": 2018,
"score": 0.6204729676246643,
"start": 2013,
"tag": "KEY",
"value": "TOKEN"
},
{
"context": "\n(def service-key\n (c/service-key-entity \"GUID\" \"retrieve_and_rank\"))\n\n(deftest create-service-with-existing-plan\n ",
"end": 3961,
"score": 0.8279365301132202,
"start": 3944,
"tag": "KEY",
"value": "retrieve_and_rank"
},
{
"context": " :cluster {:service-key \"rnr\"\n :solr_",
"end": 10935,
"score": 0.8943168520927429,
"start": 10932,
"tag": "KEY",
"value": "rnr"
},
{
"context": " :cluster {:service-key \"rnr\"\n :solr_clus",
"end": 15868,
"score": 0.961611270904541,
"start": 15865,
"tag": "KEY",
"value": "rnr"
},
{
"context": " :config {:service-key \"rnr\"\n :cluste",
"end": 16315,
"score": 0.9002067446708679,
"start": 16313,
"tag": "KEY",
"value": "nr"
},
{
"context": " :cluster {:service-key \"rnr\"\n :solr_",
"end": 16499,
"score": 0.5839217305183411,
"start": 16497,
"tag": "KEY",
"value": "nr"
},
{
"context": " :cluster {:service-key \"rnr\"\n :solr_clus",
"end": 17587,
"score": 0.7700784206390381,
"start": 17585,
"tag": "KEY",
"value": "nr"
},
{
"context": " :config {:service-key \"rnr\"\n :cluste",
"end": 18052,
"score": 0.529667317867279,
"start": 18050,
"tag": "KEY",
"value": "nr"
},
{
"context": "(def sample-cluster\n {:cluster\n {:service-key \"rnr-service\"\n :solr_cluster_id \"CLUSTER-ID\"\n :cluster_n",
"end": 18528,
"score": 0.96181720495224,
"start": 18517,
"tag": "KEY",
"value": "rnr-service"
},
{
"context": "\n\n(def sample-config\n {:config\n {:service-key \"rnr-service\"\n :cluster-id \"CLUSTER-ID\"\n :cluster-name \"",
"end": 18675,
"score": 0.9982398748397827,
"start": 18664,
"tag": "KEY",
"value": "rnr-service"
},
{
"context": ":collection\n {:service-key \"rnr-service\"\n :cluster-id \"CLUSTER-ID\"\n",
"end": 20786,
"score": 0.8941648006439209,
"start": 20776,
"tag": "KEY",
"value": "nr-service"
},
{
"context": " {:collection\n {:service-key \"rnr-service\"\n :cluster-id \"CLUSTER-ID\"\n ",
"end": 21585,
"score": 0.8610095977783203,
"start": 21574,
"tag": "KEY",
"value": "rnr-service"
},
{
"context": ":collection\n {:service-key \"rnr-service\"\n :cluster-id \"CLUSTER-ID\"",
"end": 22432,
"score": 0.9241302013397217,
"start": 22421,
"tag": "KEY",
"value": "rnr-service"
},
{
"context": " null,\" new-line\n \" \\\"password\\\" : null\" new-line\n \" },\" new-line\n ",
"end": 23037,
"score": 0.9909517168998718,
"start": 23033,
"tag": "PASSWORD",
"value": "null"
}
] |
test/kale/create_test.clj
|
IBM-Watson/kale
| 13 |
;;
;; (C) Copyright IBM Corp. 2016 All Rights Reserved.
;;
(ns kale.create-test
(:require [kale.create :as sut]
[kale.persistence :as persist]
[kale.cloud-foundry :as cf]
[kale.cloud-foundry-constants :as c]
[cheshire.core :as json]
[clj-time.core :refer [in-minutes]]
[org.httpkit.fake :refer [with-fake-http]]
[kale.common :refer [new-line] :as common]
[clojure.test :refer [deftest is]]
[slingshot.test :refer :all]
[kale.getter :as my]
[kale.retrieve-and-rank :as rnr]))
(common/set-language :en)
(def default-state {:login {:cf-token "TOKEN"
:endpoint "URL"}
:services c/entry1
:org-space {:org "org-name"
:space "space-name"
:guid {:org "ORG_GUID",
:space "SPACE_GUID"}}})
(deftest unknown-create-target
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Don't know how to 'create junk'"
(sut/create {} ["create" "junk"] []))))
(deftest create-space-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify a name for the space."
(sut/create {} ["create" "space"] []))))
(deftest create-space-indeed
(let [output-state (atom {})]
(with-redefs [cf/get-spaces (fn [_ _] (c/spaces-response :resources))
cf/get-user-data (fn [_] {"user_id" "USER_GUID"})
cf/create-space
(fn [_ _ _ _] (c/space-entity "NEW_GUID" "new-space"))
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str new-line "Space 'new-space' has been created"
" and selected for future actions." new-line)
(sut/create default-state
["create" "space" "new-space"] [])))
(is (= {:login {:cf-token "TOKEN"
:endpoint "URL"}
:services {}
:org-space
{:org "org-name"
:space "new-space"
:guid
{:org "ORG_GUID"
:space "NEW_GUID"}}}
@output-state)))))
(deftest create-dc-service
(with-redefs [sut/create-service-with-key
(fn [_ service-type service-name _]
(is (= "document_conversion" service-type))
(is (= "dc-name" service-name)))]
(sut/create default-state ["create" "dc" "dc-name"] [])))
(deftest create-rnr-service
(with-redefs [sut/create-service-with-key
(fn [_ service-type service-name _]
(is (= "retrieve_and_rank" service-type))
(is (= "rnr-name" service-name)))]
(sut/create default-state ["create" "rnr" "rnr-name"] [])))
(deftest create-service-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify a name for the service."
(sut/create-service-with-key default-state "service-type" nil false))))
(deftest wait-for-service-success
(let [counter (atom 0)]
(with-redefs [cf/get-service-status
(fn [_ _]
(swap! counter inc)
(if (= @counter 3) "create succeeded"
"create in progress"))]
(is (= (str "..." new-line)
(with-out-str
(sut/wait-for-service c/cf-auth "GUID")))))))
(deftest wait-for-service-fail
(with-redefs [cf/get-service-status (fn [_ _] "create failed")]
(with-out-str
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Service creation failed."
(sut/wait-for-service c/cf-auth "GUID"))))))
(def service-instance
(c/service-instance-entity "GUID" "service-name"))
(def service-key
(c/service-key-entity "GUID" "retrieve_and_rank"))
(deftest create-service-with-existing-plan
(with-fake-http
[(c/cf-url "/v2/service_instances?accepts_incomplete=true")
(c/respond {:body (json/encode service-instance)})]
(with-redefs [cf/get-service-plan-guid (fn [_ _ _ _] "PLAN_GUID")]
(is (= (str "Creating retrieve_and_rank service 'new-service' "
"using the 'standard' plan." new-line)
(with-out-str
(is (= service-instance
(sut/create-service-with-plan
c/cf-auth "SPACE_GUID" "retrieve_and_rank"
"new-service" "standard")))))))))
(deftest create-service-with-unknown-plan
(with-redefs [cf/get-service-plan-guid (fn [_ _ _ _] nil)]
(is (thrown+-with-msg?
[:type :kale.common/fail]
(re-pattern (str "Plan 'premium' is not available "
"for service type 'retrieve_and_rank' "
"in this organization."))
(sut/create-service-with-plan
c/cf-auth "SPACE_GUID" "retrieve_and_rank"
"new-service" "premium")))))
(deftest create-key-for-service
(with-fake-http
[(c/cf-url "/v2/service_keys")
(c/respond {:body (json/encode service-key)})]
(is (= (str "Creating key for service 'some-service'." new-line)
(with-out-str
(is (= service-key
(sut/create-key-for-service
c/cf-auth "some-service" "GUID"))))))))
(deftest create-service-instance
(let [output-state (atom {})]
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ _] service-instance)
sut/create-key-for-service (fn [_ _ service-guid]
(if (= service-guid "GUID")
service-key nil))
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str new-line "Service 'new-service' has been created"
" and selected for future actions." new-line)
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
false)))
(is (= (merge (update-in
default-state [:services] merge
{:new-service {:guid "GUID"
:type "retrieve_and_rank"
:plan "standard"
:key-guid "KEY_GUID"
:credentials
(-> service-key :entity :credentials)}})
{:user-selections {:retrieve_and_rank "new-service"}})
@output-state)))))
(deftest create-service-instance-standard
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ service-plan]
(is (= service-plan
"standard"))
service-instance)
sut/create-key-for-service (fn [_ _ _] service-key)
persist/write-state (fn [_])]
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
false)))
(deftest create-service-instance-premium
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ service-plan]
(is (= service-plan
"premium"))
service-instance)
sut/create-key-for-service (fn [_ _ _] service-key)
sut/wait-for-service (fn [_ _])
persist/write-state (fn [_])]
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
true)))
(deftest create-cluster-missing-name
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the cluster to create."
(sut/create {} ["create" "cluster"] []))))
(deftest create-cluster-bad-size
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {}
["create" "cluster" "cluster-name" "not-an-integer"]
[]))))
(deftest create-cluster-too-small
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {} ["create" "cluster" "cluster-name" "0"] []))))
(deftest create-cluster-too-large
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {} ["create" "cluster" "cluster-name" "100"] []))))
(deftest create-cluster-no-service
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which service to create the cluster in."
(sut/create {} ["create" "cluster" "cluster-name" nil] []))))
(deftest create-cluster-duplicate-name
(with-redefs [rnr/list-clusters (fn [_] [{:cluster_name "cluster-name"}])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"A cluster named 'cluster-name' already exists."
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" nil]
[])))))
(deftest create-cluster-indeed
(let [output-state (atom {})]
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/create-cluster (fn [_ n s] {:solr_cluster_id "id"
:cluster_name n
:cluster_size s})
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating cluster 'cluster-name' in 'rnr'." new-line)
(with-out-str
(is (= (str new-line "Cluster 'cluster-name' has been created"
" and selected for future actions." new-line
"It will take a few minutes to become available."
new-line)
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" 1]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(deftest wait-for-cluster
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (> @counter 3)
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))]
(is (= (str "........" new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-restart-availability-count
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (or (> @counter 3)
(= @counter 6))
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))]
(is (= (str "........" new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-long
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (> @counter 3)
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))
in-minutes (fn [_] (if (= @counter 3) 5 0))]
(is (= (str "..." new-line
"Still waiting on cluster to become ready." new-line
"....."
new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-timeout
(with-redefs [in-minutes (fn [_] 30)
rnr/get-cluster (fn [_ _]
{:solr_cluster_status "NOT_AVAILABLE"})]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Timed out waiting for cluster to become available."
(with-out-str (sut/wait-for-cluster {} "CLUSTER-ID"))))))
(deftest create-cluster-wait
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/create-cluster (fn [_ n s] {:solr_cluster_id "id"
:cluster_name n
:cluster_size s})
sut/wait-for-cluster (fn [_ _])
persist/write-state (fn [_])]
(is (= (str "Creating cluster 'cluster-name' in 'rnr'." new-line
"Waiting for cluster to become ready." new-line)
(with-out-str
(is (= (str new-line "Cluster 'cluster-name' has been created"
" and selected for future actions." new-line)
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" 1]
["--wait"]))))))))
(deftest create-config-missing-name
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the Solr configuration to create."
(sut/create {} ["create" "config"] []))))
(deftest create-config-no-zip-file-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"'my-conf' is not a prepackaged Solr configuration."
(sut/create {} ["create" "config" "my-conf"] []))))
(deftest create-config-missing-zip-file
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cannot read the file named 'no-such-config.zip'."
(sut/create {} ["create" "config" "my-conf" "no-such-config.zip"] []))))
(deftest create-config-no-cluster
(with-redefs [common/readable-files? (fn [_] true)]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which cluster to create the configuration in."
(sut/create {} ["create" "config" "my-conf" "test-config.zip"] [])))))
(deftest create-config-from-prepackaged
(let [output-state (atom {})]
(with-redefs [rnr/upload-config (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating configuration 'english' in 'rnr/cluster-name'."
new-line)
(with-out-str
(is (= (str new-line
"Solr configuration named 'english' has been"
" created and selected for future actions."
new-line)
(sut/create
{:services {:rnr {:type "retrieve_and_rank"}}
:user-selections
{:retrieve_and_rank "rnr"
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
["create" "config" "english"]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:config {:service-key "rnr"
:cluster-id "id"
:config-name "english"}
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(deftest create-config-from-file
(let [output-state (atom {})]
(with-redefs [common/readable-files? (fn [_] true)
rnr/upload-config (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating configuration 'my-conf' in 'rnr/cluster-name'."
new-line)
(with-out-str
(is (= (str new-line
"Solr configuration named 'my-conf' has been"
" created and selected for future actions."
new-line)
(sut/create
{:services {:rnr {:type "retrieve_and_rank"}}
:user-selections
{:retrieve_and_rank "rnr"
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
["create" "config" "my-conf" "test-config.zip"]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:config {:service-key "rnr"
:cluster-id "id"
:config-name "my-conf"}
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(def sample-cluster
{:cluster
{:service-key "rnr-service"
:solr_cluster_id "CLUSTER-ID"
:cluster_name "cluster"
:cluster_size 1}})
(def sample-config
{:config
{:service-key "rnr-service"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:config-name "default-config"}})
(deftest create-collection-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the collection to create."
(sut/create {} ["create" "collection"] []))))
(deftest create-collection-no-cluster
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/list-configs (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which cluster to create the collection in."
(sut/create {} ["create" "collection" "new-collection"] [])))))
(deftest create-collection-no-config
(with-redefs [rnr/list-configs (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which Solr configuration to use."
(sut/create {:services {:rnr-service {:type "retrieve_and_rank"}}
:user-selections sample-cluster}
["create" "collection" "new-collection"]
[])))))
(deftest create-collection-indeed
(let [output-state (atom {})]
(with-redefs [rnr/create-collection (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating collection 'new-collection' in"
" 'rnr-service/cluster' using config 'default-config'."
new-line)
(with-out-str
(is (= (str new-line "Collection 'new-collection' has been "
"created and selected for future actions." new-line)
(sut/create {:user-selections
(merge sample-cluster
sample-config)}
["create" "collection" "new-collection"]
[]))))))
(is (= {:user-selections
(merge sample-cluster
sample-config
{:collection
{:service-key "rnr-service"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}})}
@output-state)))))
(deftest create-crawler-no-collection
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/list-collections (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which collection to tell the crawler to use."
(sut/create {} ["create" "cc"] [])))))
(deftest create-crawler-no-dc-service
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which document_conversion service to tell "
(sut/create {:user-selections
{:collection
{:service-key "rnr-service"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}}}
["create" "cc"]
[]))))
(deftest create-crawler-indeed
(is (= (str new-line
"Created two files for setting up the Data Crawler:"
new-line
" 'orchestration_service.conf' contains document_conversion"
" service connection information."
new-line
" 'orchestration_service_config.json' contains"
" configurations sent to the 'index_document' API call."
new-line)
(sut/create {:user-selections
{:document_conversion "test-dc"
:collection
{:service-key "rnr-service"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}}}
["create" "cc"]
[])))
(is (= (str "{" new-line
" \"base_url\" : null," new-line
" \"concurrent_upload_connection_limit\" : 14," new-line
" \"config_file\" : \"orchestration_service_config.json\","
new-line
" \"credentials\" : {" new-line
" \"username\" : null," new-line
" \"password\" : null" new-line
" }," new-line
" \"endpoint\" : \"/v1/index_document?version=2016-03-18\","
new-line
" \"http_timeout\" : 600," new-line
" \"send_stats\" : {" new-line
" \"jvm\" : true," new-line
" \"os\" : true" new-line
" }" new-line
"}")
(slurp "orchestration_service.conf")))
(is (= (str "{" new-line
" \"retrieve_and_rank\" : {" new-line
" \"cluster_id\" : \"CLUSTER-ID\"," new-line
" \"search_collection\" : \"new-collection\"," new-line
" \"service_instance_id\" : null," new-line
" \"fields\" : {" new-line
" \"include\" : [ \"body\", \"contentHtml\","
" \"contentText\", \"id\", \"indexedTimestamp\","
" \"searchText\", \"sourceUrl\", \"title\" ]" new-line
" }" new-line
" }" new-line
"}")
(slurp "orchestration_service_config.json"))))
|
119524
|
;;
;; (C) Copyright IBM Corp. 2016 All Rights Reserved.
;;
(ns kale.create-test
(:require [kale.create :as sut]
[kale.persistence :as persist]
[kale.cloud-foundry :as cf]
[kale.cloud-foundry-constants :as c]
[cheshire.core :as json]
[clj-time.core :refer [in-minutes]]
[org.httpkit.fake :refer [with-fake-http]]
[kale.common :refer [new-line] :as common]
[clojure.test :refer [deftest is]]
[slingshot.test :refer :all]
[kale.getter :as my]
[kale.retrieve-and-rank :as rnr]))
(common/set-language :en)
(def default-state {:login {:cf-token "TOKEN"
:endpoint "URL"}
:services c/entry1
:org-space {:org "org-name"
:space "space-name"
:guid {:org "ORG_GUID",
:space "SPACE_GUID"}}})
(deftest unknown-create-target
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Don't know how to 'create junk'"
(sut/create {} ["create" "junk"] []))))
(deftest create-space-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify a name for the space."
(sut/create {} ["create" "space"] []))))
(deftest create-space-indeed
(let [output-state (atom {})]
(with-redefs [cf/get-spaces (fn [_ _] (c/spaces-response :resources))
cf/get-user-data (fn [_] {"user_id" "USER_GUID"})
cf/create-space
(fn [_ _ _ _] (c/space-entity "NEW_GUID" "new-space"))
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str new-line "Space 'new-space' has been created"
" and selected for future actions." new-line)
(sut/create default-state
["create" "space" "new-space"] [])))
(is (= {:login {:cf-token "<KEY>"
:endpoint "URL"}
:services {}
:org-space
{:org "org-name"
:space "new-space"
:guid
{:org "ORG_GUID"
:space "NEW_GUID"}}}
@output-state)))))
(deftest create-dc-service
(with-redefs [sut/create-service-with-key
(fn [_ service-type service-name _]
(is (= "document_conversion" service-type))
(is (= "dc-name" service-name)))]
(sut/create default-state ["create" "dc" "dc-name"] [])))
(deftest create-rnr-service
(with-redefs [sut/create-service-with-key
(fn [_ service-type service-name _]
(is (= "retrieve_and_rank" service-type))
(is (= "rnr-name" service-name)))]
(sut/create default-state ["create" "rnr" "rnr-name"] [])))
(deftest create-service-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify a name for the service."
(sut/create-service-with-key default-state "service-type" nil false))))
(deftest wait-for-service-success
(let [counter (atom 0)]
(with-redefs [cf/get-service-status
(fn [_ _]
(swap! counter inc)
(if (= @counter 3) "create succeeded"
"create in progress"))]
(is (= (str "..." new-line)
(with-out-str
(sut/wait-for-service c/cf-auth "GUID")))))))
(deftest wait-for-service-fail
(with-redefs [cf/get-service-status (fn [_ _] "create failed")]
(with-out-str
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Service creation failed."
(sut/wait-for-service c/cf-auth "GUID"))))))
(def service-instance
(c/service-instance-entity "GUID" "service-name"))
(def service-key
(c/service-key-entity "GUID" "<KEY>"))
(deftest create-service-with-existing-plan
(with-fake-http
[(c/cf-url "/v2/service_instances?accepts_incomplete=true")
(c/respond {:body (json/encode service-instance)})]
(with-redefs [cf/get-service-plan-guid (fn [_ _ _ _] "PLAN_GUID")]
(is (= (str "Creating retrieve_and_rank service 'new-service' "
"using the 'standard' plan." new-line)
(with-out-str
(is (= service-instance
(sut/create-service-with-plan
c/cf-auth "SPACE_GUID" "retrieve_and_rank"
"new-service" "standard")))))))))
(deftest create-service-with-unknown-plan
(with-redefs [cf/get-service-plan-guid (fn [_ _ _ _] nil)]
(is (thrown+-with-msg?
[:type :kale.common/fail]
(re-pattern (str "Plan 'premium' is not available "
"for service type 'retrieve_and_rank' "
"in this organization."))
(sut/create-service-with-plan
c/cf-auth "SPACE_GUID" "retrieve_and_rank"
"new-service" "premium")))))
(deftest create-key-for-service
(with-fake-http
[(c/cf-url "/v2/service_keys")
(c/respond {:body (json/encode service-key)})]
(is (= (str "Creating key for service 'some-service'." new-line)
(with-out-str
(is (= service-key
(sut/create-key-for-service
c/cf-auth "some-service" "GUID"))))))))
(deftest create-service-instance
(let [output-state (atom {})]
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ _] service-instance)
sut/create-key-for-service (fn [_ _ service-guid]
(if (= service-guid "GUID")
service-key nil))
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str new-line "Service 'new-service' has been created"
" and selected for future actions." new-line)
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
false)))
(is (= (merge (update-in
default-state [:services] merge
{:new-service {:guid "GUID"
:type "retrieve_and_rank"
:plan "standard"
:key-guid "KEY_GUID"
:credentials
(-> service-key :entity :credentials)}})
{:user-selections {:retrieve_and_rank "new-service"}})
@output-state)))))
(deftest create-service-instance-standard
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ service-plan]
(is (= service-plan
"standard"))
service-instance)
sut/create-key-for-service (fn [_ _ _] service-key)
persist/write-state (fn [_])]
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
false)))
(deftest create-service-instance-premium
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ service-plan]
(is (= service-plan
"premium"))
service-instance)
sut/create-key-for-service (fn [_ _ _] service-key)
sut/wait-for-service (fn [_ _])
persist/write-state (fn [_])]
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
true)))
(deftest create-cluster-missing-name
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the cluster to create."
(sut/create {} ["create" "cluster"] []))))
(deftest create-cluster-bad-size
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {}
["create" "cluster" "cluster-name" "not-an-integer"]
[]))))
(deftest create-cluster-too-small
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {} ["create" "cluster" "cluster-name" "0"] []))))
(deftest create-cluster-too-large
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {} ["create" "cluster" "cluster-name" "100"] []))))
(deftest create-cluster-no-service
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which service to create the cluster in."
(sut/create {} ["create" "cluster" "cluster-name" nil] []))))
(deftest create-cluster-duplicate-name
(with-redefs [rnr/list-clusters (fn [_] [{:cluster_name "cluster-name"}])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"A cluster named 'cluster-name' already exists."
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" nil]
[])))))
(deftest create-cluster-indeed
(let [output-state (atom {})]
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/create-cluster (fn [_ n s] {:solr_cluster_id "id"
:cluster_name n
:cluster_size s})
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating cluster 'cluster-name' in 'rnr'." new-line)
(with-out-str
(is (= (str new-line "Cluster 'cluster-name' has been created"
" and selected for future actions." new-line
"It will take a few minutes to become available."
new-line)
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" 1]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:cluster {:service-key "<KEY>"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(deftest wait-for-cluster
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (> @counter 3)
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))]
(is (= (str "........" new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-restart-availability-count
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (or (> @counter 3)
(= @counter 6))
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))]
(is (= (str "........" new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-long
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (> @counter 3)
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))
in-minutes (fn [_] (if (= @counter 3) 5 0))]
(is (= (str "..." new-line
"Still waiting on cluster to become ready." new-line
"....."
new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-timeout
(with-redefs [in-minutes (fn [_] 30)
rnr/get-cluster (fn [_ _]
{:solr_cluster_status "NOT_AVAILABLE"})]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Timed out waiting for cluster to become available."
(with-out-str (sut/wait-for-cluster {} "CLUSTER-ID"))))))
(deftest create-cluster-wait
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/create-cluster (fn [_ n s] {:solr_cluster_id "id"
:cluster_name n
:cluster_size s})
sut/wait-for-cluster (fn [_ _])
persist/write-state (fn [_])]
(is (= (str "Creating cluster 'cluster-name' in 'rnr'." new-line
"Waiting for cluster to become ready." new-line)
(with-out-str
(is (= (str new-line "Cluster 'cluster-name' has been created"
" and selected for future actions." new-line)
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" 1]
["--wait"]))))))))
(deftest create-config-missing-name
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the Solr configuration to create."
(sut/create {} ["create" "config"] []))))
(deftest create-config-no-zip-file-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"'my-conf' is not a prepackaged Solr configuration."
(sut/create {} ["create" "config" "my-conf"] []))))
(deftest create-config-missing-zip-file
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cannot read the file named 'no-such-config.zip'."
(sut/create {} ["create" "config" "my-conf" "no-such-config.zip"] []))))
(deftest create-config-no-cluster
(with-redefs [common/readable-files? (fn [_] true)]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which cluster to create the configuration in."
(sut/create {} ["create" "config" "my-conf" "test-config.zip"] [])))))
(deftest create-config-from-prepackaged
(let [output-state (atom {})]
(with-redefs [rnr/upload-config (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating configuration 'english' in 'rnr/cluster-name'."
new-line)
(with-out-str
(is (= (str new-line
"Solr configuration named 'english' has been"
" created and selected for future actions."
new-line)
(sut/create
{:services {:rnr {:type "retrieve_and_rank"}}
:user-selections
{:retrieve_and_rank "rnr"
:cluster {:service-key "<KEY>"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
["create" "config" "english"]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:config {:service-key "r<KEY>"
:cluster-id "id"
:config-name "english"}
:cluster {:service-key "r<KEY>"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(deftest create-config-from-file
(let [output-state (atom {})]
(with-redefs [common/readable-files? (fn [_] true)
rnr/upload-config (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating configuration 'my-conf' in 'rnr/cluster-name'."
new-line)
(with-out-str
(is (= (str new-line
"Solr configuration named 'my-conf' has been"
" created and selected for future actions."
new-line)
(sut/create
{:services {:rnr {:type "retrieve_and_rank"}}
:user-selections
{:retrieve_and_rank "rnr"
:cluster {:service-key "r<KEY>"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
["create" "config" "my-conf" "test-config.zip"]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:config {:service-key "r<KEY>"
:cluster-id "id"
:config-name "my-conf"}
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(def sample-cluster
{:cluster
{:service-key "<KEY>"
:solr_cluster_id "CLUSTER-ID"
:cluster_name "cluster"
:cluster_size 1}})
(def sample-config
{:config
{:service-key "<KEY>"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:config-name "default-config"}})
(deftest create-collection-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the collection to create."
(sut/create {} ["create" "collection"] []))))
(deftest create-collection-no-cluster
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/list-configs (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which cluster to create the collection in."
(sut/create {} ["create" "collection" "new-collection"] [])))))
(deftest create-collection-no-config
(with-redefs [rnr/list-configs (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which Solr configuration to use."
(sut/create {:services {:rnr-service {:type "retrieve_and_rank"}}
:user-selections sample-cluster}
["create" "collection" "new-collection"]
[])))))
(deftest create-collection-indeed
(let [output-state (atom {})]
(with-redefs [rnr/create-collection (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating collection 'new-collection' in"
" 'rnr-service/cluster' using config 'default-config'."
new-line)
(with-out-str
(is (= (str new-line "Collection 'new-collection' has been "
"created and selected for future actions." new-line)
(sut/create {:user-selections
(merge sample-cluster
sample-config)}
["create" "collection" "new-collection"]
[]))))))
(is (= {:user-selections
(merge sample-cluster
sample-config
{:collection
{:service-key "r<KEY>"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}})}
@output-state)))))
(deftest create-crawler-no-collection
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/list-collections (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which collection to tell the crawler to use."
(sut/create {} ["create" "cc"] [])))))
(deftest create-crawler-no-dc-service
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which document_conversion service to tell "
(sut/create {:user-selections
{:collection
{:service-key "<KEY>"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}}}
["create" "cc"]
[]))))
(deftest create-crawler-indeed
(is (= (str new-line
"Created two files for setting up the Data Crawler:"
new-line
" 'orchestration_service.conf' contains document_conversion"
" service connection information."
new-line
" 'orchestration_service_config.json' contains"
" configurations sent to the 'index_document' API call."
new-line)
(sut/create {:user-selections
{:document_conversion "test-dc"
:collection
{:service-key "<KEY>"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}}}
["create" "cc"]
[])))
(is (= (str "{" new-line
" \"base_url\" : null," new-line
" \"concurrent_upload_connection_limit\" : 14," new-line
" \"config_file\" : \"orchestration_service_config.json\","
new-line
" \"credentials\" : {" new-line
" \"username\" : null," new-line
" \"password\" : <PASSWORD>" new-line
" }," new-line
" \"endpoint\" : \"/v1/index_document?version=2016-03-18\","
new-line
" \"http_timeout\" : 600," new-line
" \"send_stats\" : {" new-line
" \"jvm\" : true," new-line
" \"os\" : true" new-line
" }" new-line
"}")
(slurp "orchestration_service.conf")))
(is (= (str "{" new-line
" \"retrieve_and_rank\" : {" new-line
" \"cluster_id\" : \"CLUSTER-ID\"," new-line
" \"search_collection\" : \"new-collection\"," new-line
" \"service_instance_id\" : null," new-line
" \"fields\" : {" new-line
" \"include\" : [ \"body\", \"contentHtml\","
" \"contentText\", \"id\", \"indexedTimestamp\","
" \"searchText\", \"sourceUrl\", \"title\" ]" new-line
" }" new-line
" }" new-line
"}")
(slurp "orchestration_service_config.json"))))
| true |
;;
;; (C) Copyright IBM Corp. 2016 All Rights Reserved.
;;
(ns kale.create-test
(:require [kale.create :as sut]
[kale.persistence :as persist]
[kale.cloud-foundry :as cf]
[kale.cloud-foundry-constants :as c]
[cheshire.core :as json]
[clj-time.core :refer [in-minutes]]
[org.httpkit.fake :refer [with-fake-http]]
[kale.common :refer [new-line] :as common]
[clojure.test :refer [deftest is]]
[slingshot.test :refer :all]
[kale.getter :as my]
[kale.retrieve-and-rank :as rnr]))
(common/set-language :en)
(def default-state {:login {:cf-token "TOKEN"
:endpoint "URL"}
:services c/entry1
:org-space {:org "org-name"
:space "space-name"
:guid {:org "ORG_GUID",
:space "SPACE_GUID"}}})
(deftest unknown-create-target
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Don't know how to 'create junk'"
(sut/create {} ["create" "junk"] []))))
(deftest create-space-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify a name for the space."
(sut/create {} ["create" "space"] []))))
(deftest create-space-indeed
(let [output-state (atom {})]
(with-redefs [cf/get-spaces (fn [_ _] (c/spaces-response :resources))
cf/get-user-data (fn [_] {"user_id" "USER_GUID"})
cf/create-space
(fn [_ _ _ _] (c/space-entity "NEW_GUID" "new-space"))
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str new-line "Space 'new-space' has been created"
" and selected for future actions." new-line)
(sut/create default-state
["create" "space" "new-space"] [])))
(is (= {:login {:cf-token "PI:KEY:<KEY>END_PI"
:endpoint "URL"}
:services {}
:org-space
{:org "org-name"
:space "new-space"
:guid
{:org "ORG_GUID"
:space "NEW_GUID"}}}
@output-state)))))
(deftest create-dc-service
(with-redefs [sut/create-service-with-key
(fn [_ service-type service-name _]
(is (= "document_conversion" service-type))
(is (= "dc-name" service-name)))]
(sut/create default-state ["create" "dc" "dc-name"] [])))
(deftest create-rnr-service
(with-redefs [sut/create-service-with-key
(fn [_ service-type service-name _]
(is (= "retrieve_and_rank" service-type))
(is (= "rnr-name" service-name)))]
(sut/create default-state ["create" "rnr" "rnr-name"] [])))
(deftest create-service-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify a name for the service."
(sut/create-service-with-key default-state "service-type" nil false))))
(deftest wait-for-service-success
(let [counter (atom 0)]
(with-redefs [cf/get-service-status
(fn [_ _]
(swap! counter inc)
(if (= @counter 3) "create succeeded"
"create in progress"))]
(is (= (str "..." new-line)
(with-out-str
(sut/wait-for-service c/cf-auth "GUID")))))))
(deftest wait-for-service-fail
(with-redefs [cf/get-service-status (fn [_ _] "create failed")]
(with-out-str
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Service creation failed."
(sut/wait-for-service c/cf-auth "GUID"))))))
(def service-instance
(c/service-instance-entity "GUID" "service-name"))
(def service-key
(c/service-key-entity "GUID" "PI:KEY:<KEY>END_PI"))
(deftest create-service-with-existing-plan
(with-fake-http
[(c/cf-url "/v2/service_instances?accepts_incomplete=true")
(c/respond {:body (json/encode service-instance)})]
(with-redefs [cf/get-service-plan-guid (fn [_ _ _ _] "PLAN_GUID")]
(is (= (str "Creating retrieve_and_rank service 'new-service' "
"using the 'standard' plan." new-line)
(with-out-str
(is (= service-instance
(sut/create-service-with-plan
c/cf-auth "SPACE_GUID" "retrieve_and_rank"
"new-service" "standard")))))))))
(deftest create-service-with-unknown-plan
(with-redefs [cf/get-service-plan-guid (fn [_ _ _ _] nil)]
(is (thrown+-with-msg?
[:type :kale.common/fail]
(re-pattern (str "Plan 'premium' is not available "
"for service type 'retrieve_and_rank' "
"in this organization."))
(sut/create-service-with-plan
c/cf-auth "SPACE_GUID" "retrieve_and_rank"
"new-service" "premium")))))
(deftest create-key-for-service
(with-fake-http
[(c/cf-url "/v2/service_keys")
(c/respond {:body (json/encode service-key)})]
(is (= (str "Creating key for service 'some-service'." new-line)
(with-out-str
(is (= service-key
(sut/create-key-for-service
c/cf-auth "some-service" "GUID"))))))))
(deftest create-service-instance
(let [output-state (atom {})]
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ _] service-instance)
sut/create-key-for-service (fn [_ _ service-guid]
(if (= service-guid "GUID")
service-key nil))
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str new-line "Service 'new-service' has been created"
" and selected for future actions." new-line)
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
false)))
(is (= (merge (update-in
default-state [:services] merge
{:new-service {:guid "GUID"
:type "retrieve_and_rank"
:plan "standard"
:key-guid "KEY_GUID"
:credentials
(-> service-key :entity :credentials)}})
{:user-selections {:retrieve_and_rank "new-service"}})
@output-state)))))
(deftest create-service-instance-standard
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ service-plan]
(is (= service-plan
"standard"))
service-instance)
sut/create-key-for-service (fn [_ _ _] service-key)
persist/write-state (fn [_])]
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
false)))
(deftest create-service-instance-premium
(with-redefs [sut/create-service-with-plan (fn [_ _ _ _ service-plan]
(is (= service-plan
"premium"))
service-instance)
sut/create-key-for-service (fn [_ _ _] service-key)
sut/wait-for-service (fn [_ _])
persist/write-state (fn [_])]
(sut/create-service-with-key default-state
"retrieve_and_rank"
"new-service"
true)))
(deftest create-cluster-missing-name
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the cluster to create."
(sut/create {} ["create" "cluster"] []))))
(deftest create-cluster-bad-size
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {}
["create" "cluster" "cluster-name" "not-an-integer"]
[]))))
(deftest create-cluster-too-small
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {} ["create" "cluster" "cluster-name" "0"] []))))
(deftest create-cluster-too-large
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cluster size must be an integer in the range of 1 to 99."
(sut/create {} ["create" "cluster" "cluster-name" "100"] []))))
(deftest create-cluster-no-service
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which service to create the cluster in."
(sut/create {} ["create" "cluster" "cluster-name" nil] []))))
(deftest create-cluster-duplicate-name
(with-redefs [rnr/list-clusters (fn [_] [{:cluster_name "cluster-name"}])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"A cluster named 'cluster-name' already exists."
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" nil]
[])))))
(deftest create-cluster-indeed
(let [output-state (atom {})]
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/create-cluster (fn [_ n s] {:solr_cluster_id "id"
:cluster_name n
:cluster_size s})
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating cluster 'cluster-name' in 'rnr'." new-line)
(with-out-str
(is (= (str new-line "Cluster 'cluster-name' has been created"
" and selected for future actions." new-line
"It will take a few minutes to become available."
new-line)
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" 1]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:cluster {:service-key "PI:KEY:<KEY>END_PI"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(deftest wait-for-cluster
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (> @counter 3)
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))]
(is (= (str "........" new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-restart-availability-count
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (or (> @counter 3)
(= @counter 6))
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))]
(is (= (str "........" new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-long
(let [counter (atom 0)]
(with-redefs [rnr/get-cluster
(fn [_ _]
(swap! counter inc)
(if (> @counter 3)
{:solr_cluster_status "READY"}
{:solr_cluster_status "NOT_AVAILABLE"}))
in-minutes (fn [_] (if (= @counter 3) 5 0))]
(is (= (str "..." new-line
"Still waiting on cluster to become ready." new-line
"....."
new-line)
(with-out-str
(sut/wait-for-cluster {} "CLUSTER-ID")))))))
(deftest wait-for-cluster-timeout
(with-redefs [in-minutes (fn [_] 30)
rnr/get-cluster (fn [_ _]
{:solr_cluster_status "NOT_AVAILABLE"})]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Timed out waiting for cluster to become available."
(with-out-str (sut/wait-for-cluster {} "CLUSTER-ID"))))))
(deftest create-cluster-wait
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/create-cluster (fn [_ n s] {:solr_cluster_id "id"
:cluster_name n
:cluster_size s})
sut/wait-for-cluster (fn [_ _])
persist/write-state (fn [_])]
(is (= (str "Creating cluster 'cluster-name' in 'rnr'." new-line
"Waiting for cluster to become ready." new-line)
(with-out-str
(is (= (str new-line "Cluster 'cluster-name' has been created"
" and selected for future actions." new-line)
(sut/create {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"}}
["create" "cluster" "cluster-name" 1]
["--wait"]))))))))
(deftest create-config-missing-name
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the Solr configuration to create."
(sut/create {} ["create" "config"] []))))
(deftest create-config-no-zip-file-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"'my-conf' is not a prepackaged Solr configuration."
(sut/create {} ["create" "config" "my-conf"] []))))
(deftest create-config-missing-zip-file
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Cannot read the file named 'no-such-config.zip'."
(sut/create {} ["create" "config" "my-conf" "no-such-config.zip"] []))))
(deftest create-config-no-cluster
(with-redefs [common/readable-files? (fn [_] true)]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which cluster to create the configuration in."
(sut/create {} ["create" "config" "my-conf" "test-config.zip"] [])))))
(deftest create-config-from-prepackaged
(let [output-state (atom {})]
(with-redefs [rnr/upload-config (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating configuration 'english' in 'rnr/cluster-name'."
new-line)
(with-out-str
(is (= (str new-line
"Solr configuration named 'english' has been"
" created and selected for future actions."
new-line)
(sut/create
{:services {:rnr {:type "retrieve_and_rank"}}
:user-selections
{:retrieve_and_rank "rnr"
:cluster {:service-key "PI:KEY:<KEY>END_PI"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
["create" "config" "english"]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:config {:service-key "rPI:KEY:<KEY>END_PI"
:cluster-id "id"
:config-name "english"}
:cluster {:service-key "rPI:KEY:<KEY>END_PI"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(deftest create-config-from-file
(let [output-state (atom {})]
(with-redefs [common/readable-files? (fn [_] true)
rnr/upload-config (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating configuration 'my-conf' in 'rnr/cluster-name'."
new-line)
(with-out-str
(is (= (str new-line
"Solr configuration named 'my-conf' has been"
" created and selected for future actions."
new-line)
(sut/create
{:services {:rnr {:type "retrieve_and_rank"}}
:user-selections
{:retrieve_and_rank "rnr"
:cluster {:service-key "rPI:KEY:<KEY>END_PI"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
["create" "config" "my-conf" "test-config.zip"]
[]))))))
(is (= {:services {:rnr {:type "retrieve_and_rank"}}
:user-selections {:retrieve_and_rank "rnr"
:config {:service-key "rPI:KEY:<KEY>END_PI"
:cluster-id "id"
:config-name "my-conf"}
:cluster {:service-key "rnr"
:solr_cluster_id "id"
:cluster_name "cluster-name"
:cluster_size 1}}}
@output-state)))))
(def sample-cluster
{:cluster
{:service-key "PI:KEY:<KEY>END_PI"
:solr_cluster_id "CLUSTER-ID"
:cluster_name "cluster"
:cluster_size 1}})
(def sample-config
{:config
{:service-key "PI:KEY:<KEY>END_PI"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:config-name "default-config"}})
(deftest create-collection-no-name-specified
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Please specify the name of the collection to create."
(sut/create {} ["create" "collection"] []))))
(deftest create-collection-no-cluster
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/list-configs (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which cluster to create the collection in."
(sut/create {} ["create" "collection" "new-collection"] [])))))
(deftest create-collection-no-config
(with-redefs [rnr/list-configs (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which Solr configuration to use."
(sut/create {:services {:rnr-service {:type "retrieve_and_rank"}}
:user-selections sample-cluster}
["create" "collection" "new-collection"]
[])))))
(deftest create-collection-indeed
(let [output-state (atom {})]
(with-redefs [rnr/create-collection (fn [_ _ _ _] nil)
persist/write-state (fn [state] (reset! output-state state))]
(is (= (str "Creating collection 'new-collection' in"
" 'rnr-service/cluster' using config 'default-config'."
new-line)
(with-out-str
(is (= (str new-line "Collection 'new-collection' has been "
"created and selected for future actions." new-line)
(sut/create {:user-selections
(merge sample-cluster
sample-config)}
["create" "collection" "new-collection"]
[]))))))
(is (= {:user-selections
(merge sample-cluster
sample-config
{:collection
{:service-key "rPI:KEY:<KEY>END_PI"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}})}
@output-state)))))
(deftest create-crawler-no-collection
(with-redefs [rnr/list-clusters (fn [_] [])
rnr/list-collections (fn [_ _] [])]
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which collection to tell the crawler to use."
(sut/create {} ["create" "cc"] [])))))
(deftest create-crawler-no-dc-service
(is (thrown+-with-msg?
[:type :kale.common/fail]
#"Couldn't determine which document_conversion service to tell "
(sut/create {:user-selections
{:collection
{:service-key "PI:KEY:<KEY>END_PI"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}}}
["create" "cc"]
[]))))
(deftest create-crawler-indeed
(is (= (str new-line
"Created two files for setting up the Data Crawler:"
new-line
" 'orchestration_service.conf' contains document_conversion"
" service connection information."
new-line
" 'orchestration_service_config.json' contains"
" configurations sent to the 'index_document' API call."
new-line)
(sut/create {:user-selections
{:document_conversion "test-dc"
:collection
{:service-key "PI:KEY:<KEY>END_PI"
:cluster-id "CLUSTER-ID"
:cluster-name "cluster"
:collection-name "new-collection"}}}
["create" "cc"]
[])))
(is (= (str "{" new-line
" \"base_url\" : null," new-line
" \"concurrent_upload_connection_limit\" : 14," new-line
" \"config_file\" : \"orchestration_service_config.json\","
new-line
" \"credentials\" : {" new-line
" \"username\" : null," new-line
" \"password\" : PI:PASSWORD:<PASSWORD>END_PI" new-line
" }," new-line
" \"endpoint\" : \"/v1/index_document?version=2016-03-18\","
new-line
" \"http_timeout\" : 600," new-line
" \"send_stats\" : {" new-line
" \"jvm\" : true," new-line
" \"os\" : true" new-line
" }" new-line
"}")
(slurp "orchestration_service.conf")))
(is (= (str "{" new-line
" \"retrieve_and_rank\" : {" new-line
" \"cluster_id\" : \"CLUSTER-ID\"," new-line
" \"search_collection\" : \"new-collection\"," new-line
" \"service_instance_id\" : null," new-line
" \"fields\" : {" new-line
" \"include\" : [ \"body\", \"contentHtml\","
" \"contentText\", \"id\", \"indexedTimestamp\","
" \"searchText\", \"sourceUrl\", \"title\" ]" new-line
" }" new-line
" }" new-line
"}")
(slurp "orchestration_service_config.json"))))
|
[
{
"context": "L\n :user mailUsername\n :pass mailPassword\n :t-and-c-url termsAndConditions}))\n\n",
"end": 2860,
"score": 0.5674434304237366,
"start": 2856,
"tag": "PASSWORD",
"value": "mail"
}
] |
cimi/src/com/sixsq/slipstream/ssclj/resources/email/utils.clj
|
slipstream/SlipStreamServer
| 6 |
(ns com.sixsq.slipstream.ssclj.resources.email.utils
(:require
[clojure.string :as str]
[com.sixsq.slipstream.ssclj.resources.callback :as callback]
[com.sixsq.slipstream.ssclj.resources.callback-email-validation :as email-callback]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.util.response :as r]
[postal.core :as postal]))
(def validation-email-body
(partial format
(str/join "\n"
["To validate your email address, visit:"
"\n %s\n"
"If you did not initiate this request, do NOT click on the link and report"
"this to the service administrator."])))
(def t-and-c-acceptance
(partial format
(str/join "\n"
["By clicking the link and validating your email address you accept the Terms"
"and Conditions:"
"\n %s\n"])))
;; FIXME: Fix ugliness around needing to create ring requests with authentication!
(defn create-callback [email-id baseURI]
(let [callback-request {:params {:resource-name callback/resource-url}
:body {:action email-callback/action-name
:targetResource {:href email-id}}
:identity {:current "INTERNAL"
:authentications {"INTERNAL" {:identity "INTERNAL"
:roles ["ADMIN"]}}}}
{{:keys [resource-id]} :body status :status} (crud/add callback-request)]
(if (= 201 status)
(if-let [callback-resource (crud/set-operations (crud/retrieve-by-id-as-admin resource-id) {})]
(if-let [validate-op (u/get-op callback-resource "execute")]
(str baseURI validate-op)
(let [msg "callback does not have execute operation"]
(throw (ex-info msg (r/map-response msg 500 resource-id)))))
(let [msg "cannot retrieve email validation callback"]
(throw (ex-info msg (r/map-response msg 500 resource-id)))))
(let [msg "cannot create email validation callback"]
(throw (ex-info msg (r/map-response msg 500 email-id)))))))
(defn smtp-cfg
"Extracts the SMTP configuration from the server's configuration resource.
Note that this assumes a standard URL for the configuration resource."
[]
(when-let [{:keys [mailHost mailPort
mailSSL
mailUsername mailPassword
termsAndConditions]} (crud/retrieve-by-id-as-admin "configuration/slipstream")]
{:host mailHost
:port mailPort
:ssl mailSSL
:user mailUsername
:pass mailPassword
:t-and-c-url termsAndConditions}))
(defn send-validation-email [callback-url address]
(try
(let [{:keys [user t-and-c-url] :as smtp} (smtp-cfg)]
(let [sender (or user "administrator")
body (cond-> (validation-email-body callback-url)
t-and-c-url (str (t-and-c-acceptance t-and-c-url)))
msg {:from sender
:to [address]
:subject "email validation"
:body body}
resp (postal/send-message smtp msg)]
(if-not (= :SUCCESS (:error resp))
(let [msg (str "cannot send verification email: " (:message resp))]
(throw (r/ex-bad-request msg))))))
(catch Exception e
(let [error-msg "server configuration for SMTP is missing"]
(throw (ex-info error-msg (r/map-response error-msg 500)))))))
(defn send-email
[subject body addresses]
(try
(let [{:keys [user t-and-c-url] :as smtp} (smtp-cfg)]
(let [msg {:from user
:to addresses
:subject subject
:body body}
resp (postal/send-message smtp msg)]
(if-not (= :SUCCESS (:error resp))
(let [msg (str "cannot send email: " (:message resp))]
(throw (r/ex-bad-request msg))))))
(catch Exception e
(let [error-msg "server configuration for SMTP is missing"]
(throw (ex-info error-msg (r/map-response error-msg 500)))))))
|
38911
|
(ns com.sixsq.slipstream.ssclj.resources.email.utils
(:require
[clojure.string :as str]
[com.sixsq.slipstream.ssclj.resources.callback :as callback]
[com.sixsq.slipstream.ssclj.resources.callback-email-validation :as email-callback]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.util.response :as r]
[postal.core :as postal]))
(def validation-email-body
(partial format
(str/join "\n"
["To validate your email address, visit:"
"\n %s\n"
"If you did not initiate this request, do NOT click on the link and report"
"this to the service administrator."])))
(def t-and-c-acceptance
(partial format
(str/join "\n"
["By clicking the link and validating your email address you accept the Terms"
"and Conditions:"
"\n %s\n"])))
;; FIXME: Fix ugliness around needing to create ring requests with authentication!
(defn create-callback [email-id baseURI]
(let [callback-request {:params {:resource-name callback/resource-url}
:body {:action email-callback/action-name
:targetResource {:href email-id}}
:identity {:current "INTERNAL"
:authentications {"INTERNAL" {:identity "INTERNAL"
:roles ["ADMIN"]}}}}
{{:keys [resource-id]} :body status :status} (crud/add callback-request)]
(if (= 201 status)
(if-let [callback-resource (crud/set-operations (crud/retrieve-by-id-as-admin resource-id) {})]
(if-let [validate-op (u/get-op callback-resource "execute")]
(str baseURI validate-op)
(let [msg "callback does not have execute operation"]
(throw (ex-info msg (r/map-response msg 500 resource-id)))))
(let [msg "cannot retrieve email validation callback"]
(throw (ex-info msg (r/map-response msg 500 resource-id)))))
(let [msg "cannot create email validation callback"]
(throw (ex-info msg (r/map-response msg 500 email-id)))))))
(defn smtp-cfg
"Extracts the SMTP configuration from the server's configuration resource.
Note that this assumes a standard URL for the configuration resource."
[]
(when-let [{:keys [mailHost mailPort
mailSSL
mailUsername mailPassword
termsAndConditions]} (crud/retrieve-by-id-as-admin "configuration/slipstream")]
{:host mailHost
:port mailPort
:ssl mailSSL
:user mailUsername
:pass <PASSWORD>Password
:t-and-c-url termsAndConditions}))
(defn send-validation-email [callback-url address]
(try
(let [{:keys [user t-and-c-url] :as smtp} (smtp-cfg)]
(let [sender (or user "administrator")
body (cond-> (validation-email-body callback-url)
t-and-c-url (str (t-and-c-acceptance t-and-c-url)))
msg {:from sender
:to [address]
:subject "email validation"
:body body}
resp (postal/send-message smtp msg)]
(if-not (= :SUCCESS (:error resp))
(let [msg (str "cannot send verification email: " (:message resp))]
(throw (r/ex-bad-request msg))))))
(catch Exception e
(let [error-msg "server configuration for SMTP is missing"]
(throw (ex-info error-msg (r/map-response error-msg 500)))))))
(defn send-email
[subject body addresses]
(try
(let [{:keys [user t-and-c-url] :as smtp} (smtp-cfg)]
(let [msg {:from user
:to addresses
:subject subject
:body body}
resp (postal/send-message smtp msg)]
(if-not (= :SUCCESS (:error resp))
(let [msg (str "cannot send email: " (:message resp))]
(throw (r/ex-bad-request msg))))))
(catch Exception e
(let [error-msg "server configuration for SMTP is missing"]
(throw (ex-info error-msg (r/map-response error-msg 500)))))))
| true |
(ns com.sixsq.slipstream.ssclj.resources.email.utils
(:require
[clojure.string :as str]
[com.sixsq.slipstream.ssclj.resources.callback :as callback]
[com.sixsq.slipstream.ssclj.resources.callback-email-validation :as email-callback]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.util.response :as r]
[postal.core :as postal]))
(def validation-email-body
(partial format
(str/join "\n"
["To validate your email address, visit:"
"\n %s\n"
"If you did not initiate this request, do NOT click on the link and report"
"this to the service administrator."])))
(def t-and-c-acceptance
(partial format
(str/join "\n"
["By clicking the link and validating your email address you accept the Terms"
"and Conditions:"
"\n %s\n"])))
;; FIXME: Fix ugliness around needing to create ring requests with authentication!
(defn create-callback [email-id baseURI]
(let [callback-request {:params {:resource-name callback/resource-url}
:body {:action email-callback/action-name
:targetResource {:href email-id}}
:identity {:current "INTERNAL"
:authentications {"INTERNAL" {:identity "INTERNAL"
:roles ["ADMIN"]}}}}
{{:keys [resource-id]} :body status :status} (crud/add callback-request)]
(if (= 201 status)
(if-let [callback-resource (crud/set-operations (crud/retrieve-by-id-as-admin resource-id) {})]
(if-let [validate-op (u/get-op callback-resource "execute")]
(str baseURI validate-op)
(let [msg "callback does not have execute operation"]
(throw (ex-info msg (r/map-response msg 500 resource-id)))))
(let [msg "cannot retrieve email validation callback"]
(throw (ex-info msg (r/map-response msg 500 resource-id)))))
(let [msg "cannot create email validation callback"]
(throw (ex-info msg (r/map-response msg 500 email-id)))))))
(defn smtp-cfg
"Extracts the SMTP configuration from the server's configuration resource.
Note that this assumes a standard URL for the configuration resource."
[]
(when-let [{:keys [mailHost mailPort
mailSSL
mailUsername mailPassword
termsAndConditions]} (crud/retrieve-by-id-as-admin "configuration/slipstream")]
{:host mailHost
:port mailPort
:ssl mailSSL
:user mailUsername
:pass PI:PASSWORD:<PASSWORD>END_PIPassword
:t-and-c-url termsAndConditions}))
(defn send-validation-email [callback-url address]
(try
(let [{:keys [user t-and-c-url] :as smtp} (smtp-cfg)]
(let [sender (or user "administrator")
body (cond-> (validation-email-body callback-url)
t-and-c-url (str (t-and-c-acceptance t-and-c-url)))
msg {:from sender
:to [address]
:subject "email validation"
:body body}
resp (postal/send-message smtp msg)]
(if-not (= :SUCCESS (:error resp))
(let [msg (str "cannot send verification email: " (:message resp))]
(throw (r/ex-bad-request msg))))))
(catch Exception e
(let [error-msg "server configuration for SMTP is missing"]
(throw (ex-info error-msg (r/map-response error-msg 500)))))))
(defn send-email
[subject body addresses]
(try
(let [{:keys [user t-and-c-url] :as smtp} (smtp-cfg)]
(let [msg {:from user
:to addresses
:subject subject
:body body}
resp (postal/send-message smtp msg)]
(if-not (= :SUCCESS (:error resp))
(let [msg (str "cannot send email: " (:message resp))]
(throw (r/ex-bad-request msg))))))
(catch Exception e
(let [error-msg "server configuration for SMTP is missing"]
(throw (ex-info error-msg (r/map-response error-msg 500)))))))
|
[
{
"context": "e the variant\n;;; 'app-exp has two fields)\n;;;\n;;; Eli Bendersky [http://eli.thegreenplace.net]\n;;; This code is i",
"end": 1685,
"score": 0.9974662661552429,
"start": 1672,
"tag": "NAME",
"value": "Eli Bendersky"
}
] |
2016/define-datatype/src/define_datatype/define_datatype.clj
|
mikiec84/code-for-blog
| 1,199 |
;;; Clojure implementation of the 'define-datatypes' and 'cases' macros from
;;; the "Elements of Programming Languages" (EOPL) book - third edition.
;;;
;;; Given:
;;;
;;; (define-datatype lc-exp lc-exp?
;;; (var-exp
;;; (var symbol?))
;;; (lambda-exp
;;; (bound-var symbol?)
;;; (body lc-exp?))
;;; (app-exp
;;; (rator lc-exp?)
;;; (rand lc-exp?)))
;;;
;;; We createa a "type" named 'lc-exp, with 3 variants: 'var-exp, 'lambda-exp
;;; and 'app-exp. The following functions are defined automatically:
;;;
;;; Predicate -- is arg an lc-exp?:
;;; lc-exp?: fn [arg] ; predicate: is arg an lc-exp?
;;;
;;; Constructors that verify that their arguments comply to the predicates
;;; provided in the define-datatype specification, and predicates that check
;;; that the given object is a variant:
;;; var-exp: fn [var]
;;; var-exp?: fn [arg]
;;; lambda-exp: fn [bound-var body]
;;; lambda-exp?: fn [arg?]
;;; app-exp: fn [rator rand]
;;; app-exp?: fn [arg]
;;;
;;; Accessors for fields:
;;; var-exp->var: fn [arg]
;;; lambda-exp->bound-var: fn [arg]
;;; lambda-exp->body: fn [arg]
;;; app-exp->rator: fn [arg]
;;; app-exp->rand: fn [arg]
;;;
;;; Also, the macro 'cases' permits compact actions on objects created with
;;; define-datatypes. See tests below.
;;;
;;; This system creates "objects" as follows:
;;;
;;; (typename variant-name field1 field2 ... fieldN)
;;;
;;; typename is the name of the encompassing type (such as 'lc-exp);
;;; variant-name is the name of the specific variant of the type (such as
;;; 'app-exp); field1...N are the fields of the variant (for example the variant
;;; 'app-exp has two fields)
;;;
;;; Eli Bendersky [http://eli.thegreenplace.net]
;;; This code is in the public domain.
(ns define-datatype.define-datatype
(:use clojure.test))
(defn internfunc
"Helper for interning a function with the given name (as a string) in the
current namespace."
[strname func]
(intern *ns* (symbol strname) func))
(defn make-accessor
"Creates an accessor for field 'fielname' in variant 'variant-name'.
The accessor is positional using 'nth'."
[variant-name fieldname fieldpos]
(letfn [(func [obj]
(nth obj fieldpos))]
(internfunc (str variant-name "->" fieldname) func)))
(defn make-predicate
"Creates a predicate function to test whether a given object belongs to a type
variant. numfields is the number of fields the variant object is expected to
have."
[typename variant-name numfields]
(letfn [(func [obj]
(and (= (count obj) (+ 2 numfields))
(= (first obj) typename)
(= (second obj) variant-name)))]
(internfunc (str variant-name "?") func)))
(defn make-ctor
"Creates a constructor function for the given variant of a type. predicates is
a list of predicates for the fields passed to the constructor."
[typename variant-name predicates]
(letfn [(func [& field-initializers]
(do
(assert (= (count field-initializers) (count predicates)))
(assert (every? true? (map (fn [pred field]
((resolve pred) field))
predicates
field-initializers)))
(cons typename (cons variant-name field-initializers))))]
(internfunc (str variant-name) func)))
(defn make-type-variant
"Creates a type variant with a constructor, predicate and accessors.
The typename and variant-name are symbols; field-descriptors is a list of
pairs, each consisting of two symbols: field name and a predicate to test for
the validity of this field when creating a type variant. The predicate is a
symbol, not an actual Clojure function."
[typename variant-name field-descriptors]
(let [numfields (count field-descriptors)
predicates (map second field-descriptors)]
(do
;; Create the constructor for this type.
(make-ctor typename variant-name predicates)
;; Create the predicate for this type.
(make-predicate typename variant-name numfields)
;; Create field accessors.
(doseq [[field-index [fieldname field-predicate]]
(map-indexed vector field-descriptors)]
(make-accessor variant-name fieldname (+ 2 field-index))))))
(defn define-datatype-aux
"Creates a datatype from the specification. This is a function, so all its
arguments are symbols or quoted lists. In particular, variant-descriptors is a
quoted list of all the descriptors."
[typename predicate-name variant-descriptors]
(do
(letfn [(pred-func [obj]
(= (first obj) typename))]
(internfunc (str predicate-name) pred-func))
(doseq [[variant-name & field-descriptors] variant-descriptors]
(make-type-variant typename variant-name field-descriptors))))
(defmacro define-datatype
"Simple macro wrapper around define-datatype-aux, so that the type name,
predicate name and variant descriptors don't have to be quoted but rather can
be regular Clojure symbols."
[typename predicate-name & variant-descriptors]
(define-datatype-aux typename predicate-name variant-descriptors))
(defn make-cond-case
"Helper function for cases that generates a single case for the variant cond.
variant-case is one variant case as given to the cases macro.
obj-variant is the actual object variant (a symbol) as taken from the object.
obj-fields is the list of the actual object's fields.
Produces the code for '(cond-case cond-action)."
[variant-case obj-variant obj-fields]
`((= (quote ~(first variant-case)) ~obj-variant)
(apply (fn [~@(second variant-case)] ~(last variant-case)) ~obj-fields)))
(defmacro cases
[typename obj & variant-cases]
(let [obj-type-sym (gensym 'type)
obj-variant-sym (gensym 'variant)
obj-fields-sym (gensym 'fields)]
`(let [[~obj-type-sym ~obj-variant-sym & ~obj-fields-sym] ~obj]
(assert (= ~obj-type-sym (quote ~typename)) "Unexpected type")
(cond
~@(mapcat (fn [vc] (make-cond-case vc obj-variant-sym obj-fields-sym))
variant-cases)
:else (assert false "Unsupported variant")))))
;;; ------------------ Testing ------------------
;;; A silly tuple is either a single symbol, or a pair of integers.
(define-datatype sillytuple sillytuple?
(single (s symbol?))
(pair (i integer?) (j integer?)))
(deftest test-sillytuple-single
(let [s (single 'k)]
(is (sillytuple? s))
(is (single? s))
(is (not (pair? s)))
(is (= 'k (single->s s)))))
(deftest test-sillytuple-bad-single
(is (thrown? AssertionError (single '(k))))
(is (thrown? AssertionError (single 20))))
(deftest test-sillytuple-pair
(let [p (pair 10 20)]
(is (sillytuple? p))
(is (pair? p))
(is (not (single? p)))
(is (= 10 (pair->i p)))
(is (= 20 (pair->j p)))))
(deftest test-sillytuple-bad-pair
(is (thrown? AssertionError (pair 'foo 10)))
(is (thrown? AssertionError (pair 20 21.5))))
(deftest test-sillytuple-simple-cases
;; Test that a simple cases definition works well
(letfn [(good? [st]
(cases sillytuple st
(single (s) (= s 'good))
(pair (i j) (> i j))))]
(is (not (good? (single 'food))))
(is (good? (single 'good)))
(is (good? (pair 10 9)))
(is (not (good? (pair 10 19))))
(is (thrown-with-msg?
AssertionError #"Unexpected" (good? '(kuku da))))
;; Force-create a bad silly tuple (inexistent variant) and good? should
;; throw as expected.
(is (thrown-with-msg?
AssertionError #"Unsupported variant"
(good? '(sillytuple foobar 20))))))
(define-datatype lc-exp lc-exp?
(var-exp
(var symbol?))
(lambda-exp
(bound-var symbol?)
(body lc-exp?))
(app-exp
(rator lc-exp?)
(rand lc-exp?)))
;;; Trivial 'cases' for testing
(defn lc-exp-numargs
[exp]
(cases lc-exp exp
(var-exp (variable) 1)
(lambda-exp (bound-var body) 2)
(app-exp (rator rand) 3)))
(deftest test-lc-exp-simple
(let [ve (var-exp 't)]
(is (lc-exp? ve))
(is (var-exp? ve))
(is (not (app-exp? ve)))
(is (= 1 (lc-exp-numargs ve))))
(let [v (lambda-exp 'v (app-exp (var-exp 'v) (var-exp 't)))]
(is (lc-exp? v))
(is (lambda-exp? v))
(is (= 'v (lambda-exp->bound-var v)))
(is (app-exp? (lambda-exp->body v)))
(is (= 2 (lc-exp-numargs v)))
(is (= 3 (lc-exp-numargs (lambda-exp->body v))))
(is (= 1 (lc-exp-numargs (app-exp->rator (lambda-exp->body v)))))
(is (= 1 (lc-exp-numargs (app-exp->rand (lambda-exp->body v)))))))
(defn occurs-free?
"Does search-var occur as a free variable in exp?"
[search-var exp]
(cases lc-exp exp
(var-exp (variable) (= variable search-var))
(lambda-exp (bound-var body)
(and (not (= search-var bound-var))
(occurs-free? search-var body)))
(app-exp (rator rand)
(or
(occurs-free? search-var rator)
(occurs-free? search-var rand)))))
(deftest test-lc-exp-occurs-free
(let [ve (var-exp 't)]
(is (occurs-free? 't ve))
(is (not (occurs-free? 'r ve)))
(let [ae (app-exp (var-exp 't) (app-exp (var-exp 'd) (var-exp 'e)))]
(is (occurs-free? 't ae))
(is (occurs-free? 'd ae))
(is (occurs-free? 'e ae))
(is (not (occurs-free? 'p ae))))
(let [le (lambda-exp 'v (app-exp (var-exp 'v) (var-exp 't)))]
(is (occurs-free? 't le))
(is (not (occurs-free? 'v le))))
(let [ne (app-exp
(var-exp 't)
(app-exp
(var-exp 'd)
(lambda-exp 'v (app-exp (var-exp 'c) (var-exp 'v)))))]
(is (occurs-free? 't ne))
(is (occurs-free? 'd ne))
(is (occurs-free? 'c ne))
(is (not (occurs-free? 'v ne))))))
;;; Exercise 2.21: the environment data structure, from section 2.2.2
(defn symbol-or-number? [v] (or (symbol? v) (number? v)))
(define-datatype env env?
(empty-env)
(extend-env
(var symbol?)
(val symbol-or-number?)
(env env?)))
(defn apply-env
[e search-var]
(cases env e
(empty-env () (assert false "apply-env on empty env"))
(extend-env (var val saved-env)
(if (= search-var var)
val
(apply-env saved-env search-var)))))
(defn has-binding?
[e search-var]
(cases env e
(empty-env () false)
(extend-env (var val saved-env)
(or (= search-var var)
(has-binding? saved-env search-var)))))
(deftest test-env
(let [emp (empty-env)]
(is (env? emp)))
(let [ext1 (extend-env 'v 20 (empty-env))]
(is (env? ext1))
(is (= (extend-env->var ext1) 'v))
(is (= (apply-env ext1 'v) 20))
(is (has-binding? ext1 'v))
(is (thrown? AssertionError (apply-env ext1 'jk)))
(is (not (has-binding? ext1 'jf)))
(is (= (extend-env->val ext1) 20)))
(let [ext3 (extend-env
'a 1 (extend-env 'b 2 (extend-env 'c 3 (empty-env))))]
(is (= (apply-env ext3 'a) 1))
(is (has-binding? ext3 'a))
(is (= (apply-env ext3 'b) 2))
(is (has-binding? ext3 'b))
(is (= (apply-env ext3 'c) 3))
(is (has-binding? ext3 'c))
(is (not (has-binding? ext3 'd)))
(is (thrown? AssertionError (apply-env ext3 'd)))))
;;; Exercise 2.24: binary tree
(define-datatype bintree bintree?
(leaf-node
(num integer?))
(interior-node
(key symbol?)
(left bintree?)
(right bintree?)))
(defn bintree-to-list
[bt]
(cases bintree bt
(leaf-node (num) (list 'leaf-node num))
(interior-node (key left right)
(list 'interior-node
key
(bintree-to-list left)
(bintree-to-list right)))))
(defn max-interior
[bt]
;; exercise 2.25
(cases bintree bt
(leaf-node (num) [num nil])
(interior-node (key left right)
(let [[leftsum leftsym] (max-interior left)
[rightsum rightsym] (max-interior right)
mysum (+ leftsum rightsum)]
(cond
(and (> mysum rightsum) (> mysum leftsum))
[mysum key]
(and (> leftsum rightsum) (> leftsum mysum))
[leftsum leftsym]
:else
[rightsum rightsym])))))
(deftest test-bintree
(let [bt1 (interior-node 'k
(interior-node 'p (leaf-node 20) (leaf-node 30))
(leaf-node 40))]
(is (bintree? bt1))
(is (= (bintree-to-list bt1)
'(interior-node k
(interior-node p (leaf-node 20) (leaf-node 30))
(leaf-node 40)))))
(let [tree-1 (interior-node 'foo (leaf-node 2) (leaf-node 3))
tree-2 (interior-node 'bar (leaf-node -1) tree-1)
tree-3 (interior-node 'baz tree-2 (leaf-node 1))]
(is (= [5 'foo] (max-interior tree-2)))
(is (= [6 'baz] (max-interior tree-3)))))
(run-tests)
|
33963
|
;;; Clojure implementation of the 'define-datatypes' and 'cases' macros from
;;; the "Elements of Programming Languages" (EOPL) book - third edition.
;;;
;;; Given:
;;;
;;; (define-datatype lc-exp lc-exp?
;;; (var-exp
;;; (var symbol?))
;;; (lambda-exp
;;; (bound-var symbol?)
;;; (body lc-exp?))
;;; (app-exp
;;; (rator lc-exp?)
;;; (rand lc-exp?)))
;;;
;;; We createa a "type" named 'lc-exp, with 3 variants: 'var-exp, 'lambda-exp
;;; and 'app-exp. The following functions are defined automatically:
;;;
;;; Predicate -- is arg an lc-exp?:
;;; lc-exp?: fn [arg] ; predicate: is arg an lc-exp?
;;;
;;; Constructors that verify that their arguments comply to the predicates
;;; provided in the define-datatype specification, and predicates that check
;;; that the given object is a variant:
;;; var-exp: fn [var]
;;; var-exp?: fn [arg]
;;; lambda-exp: fn [bound-var body]
;;; lambda-exp?: fn [arg?]
;;; app-exp: fn [rator rand]
;;; app-exp?: fn [arg]
;;;
;;; Accessors for fields:
;;; var-exp->var: fn [arg]
;;; lambda-exp->bound-var: fn [arg]
;;; lambda-exp->body: fn [arg]
;;; app-exp->rator: fn [arg]
;;; app-exp->rand: fn [arg]
;;;
;;; Also, the macro 'cases' permits compact actions on objects created with
;;; define-datatypes. See tests below.
;;;
;;; This system creates "objects" as follows:
;;;
;;; (typename variant-name field1 field2 ... fieldN)
;;;
;;; typename is the name of the encompassing type (such as 'lc-exp);
;;; variant-name is the name of the specific variant of the type (such as
;;; 'app-exp); field1...N are the fields of the variant (for example the variant
;;; 'app-exp has two fields)
;;;
;;; <NAME> [http://eli.thegreenplace.net]
;;; This code is in the public domain.
(ns define-datatype.define-datatype
(:use clojure.test))
(defn internfunc
"Helper for interning a function with the given name (as a string) in the
current namespace."
[strname func]
(intern *ns* (symbol strname) func))
(defn make-accessor
"Creates an accessor for field 'fielname' in variant 'variant-name'.
The accessor is positional using 'nth'."
[variant-name fieldname fieldpos]
(letfn [(func [obj]
(nth obj fieldpos))]
(internfunc (str variant-name "->" fieldname) func)))
(defn make-predicate
"Creates a predicate function to test whether a given object belongs to a type
variant. numfields is the number of fields the variant object is expected to
have."
[typename variant-name numfields]
(letfn [(func [obj]
(and (= (count obj) (+ 2 numfields))
(= (first obj) typename)
(= (second obj) variant-name)))]
(internfunc (str variant-name "?") func)))
(defn make-ctor
"Creates a constructor function for the given variant of a type. predicates is
a list of predicates for the fields passed to the constructor."
[typename variant-name predicates]
(letfn [(func [& field-initializers]
(do
(assert (= (count field-initializers) (count predicates)))
(assert (every? true? (map (fn [pred field]
((resolve pred) field))
predicates
field-initializers)))
(cons typename (cons variant-name field-initializers))))]
(internfunc (str variant-name) func)))
(defn make-type-variant
"Creates a type variant with a constructor, predicate and accessors.
The typename and variant-name are symbols; field-descriptors is a list of
pairs, each consisting of two symbols: field name and a predicate to test for
the validity of this field when creating a type variant. The predicate is a
symbol, not an actual Clojure function."
[typename variant-name field-descriptors]
(let [numfields (count field-descriptors)
predicates (map second field-descriptors)]
(do
;; Create the constructor for this type.
(make-ctor typename variant-name predicates)
;; Create the predicate for this type.
(make-predicate typename variant-name numfields)
;; Create field accessors.
(doseq [[field-index [fieldname field-predicate]]
(map-indexed vector field-descriptors)]
(make-accessor variant-name fieldname (+ 2 field-index))))))
(defn define-datatype-aux
"Creates a datatype from the specification. This is a function, so all its
arguments are symbols or quoted lists. In particular, variant-descriptors is a
quoted list of all the descriptors."
[typename predicate-name variant-descriptors]
(do
(letfn [(pred-func [obj]
(= (first obj) typename))]
(internfunc (str predicate-name) pred-func))
(doseq [[variant-name & field-descriptors] variant-descriptors]
(make-type-variant typename variant-name field-descriptors))))
(defmacro define-datatype
"Simple macro wrapper around define-datatype-aux, so that the type name,
predicate name and variant descriptors don't have to be quoted but rather can
be regular Clojure symbols."
[typename predicate-name & variant-descriptors]
(define-datatype-aux typename predicate-name variant-descriptors))
(defn make-cond-case
"Helper function for cases that generates a single case for the variant cond.
variant-case is one variant case as given to the cases macro.
obj-variant is the actual object variant (a symbol) as taken from the object.
obj-fields is the list of the actual object's fields.
Produces the code for '(cond-case cond-action)."
[variant-case obj-variant obj-fields]
`((= (quote ~(first variant-case)) ~obj-variant)
(apply (fn [~@(second variant-case)] ~(last variant-case)) ~obj-fields)))
(defmacro cases
[typename obj & variant-cases]
(let [obj-type-sym (gensym 'type)
obj-variant-sym (gensym 'variant)
obj-fields-sym (gensym 'fields)]
`(let [[~obj-type-sym ~obj-variant-sym & ~obj-fields-sym] ~obj]
(assert (= ~obj-type-sym (quote ~typename)) "Unexpected type")
(cond
~@(mapcat (fn [vc] (make-cond-case vc obj-variant-sym obj-fields-sym))
variant-cases)
:else (assert false "Unsupported variant")))))
;;; ------------------ Testing ------------------
;;; A silly tuple is either a single symbol, or a pair of integers.
(define-datatype sillytuple sillytuple?
(single (s symbol?))
(pair (i integer?) (j integer?)))
(deftest test-sillytuple-single
(let [s (single 'k)]
(is (sillytuple? s))
(is (single? s))
(is (not (pair? s)))
(is (= 'k (single->s s)))))
(deftest test-sillytuple-bad-single
(is (thrown? AssertionError (single '(k))))
(is (thrown? AssertionError (single 20))))
(deftest test-sillytuple-pair
(let [p (pair 10 20)]
(is (sillytuple? p))
(is (pair? p))
(is (not (single? p)))
(is (= 10 (pair->i p)))
(is (= 20 (pair->j p)))))
(deftest test-sillytuple-bad-pair
(is (thrown? AssertionError (pair 'foo 10)))
(is (thrown? AssertionError (pair 20 21.5))))
(deftest test-sillytuple-simple-cases
;; Test that a simple cases definition works well
(letfn [(good? [st]
(cases sillytuple st
(single (s) (= s 'good))
(pair (i j) (> i j))))]
(is (not (good? (single 'food))))
(is (good? (single 'good)))
(is (good? (pair 10 9)))
(is (not (good? (pair 10 19))))
(is (thrown-with-msg?
AssertionError #"Unexpected" (good? '(kuku da))))
;; Force-create a bad silly tuple (inexistent variant) and good? should
;; throw as expected.
(is (thrown-with-msg?
AssertionError #"Unsupported variant"
(good? '(sillytuple foobar 20))))))
(define-datatype lc-exp lc-exp?
(var-exp
(var symbol?))
(lambda-exp
(bound-var symbol?)
(body lc-exp?))
(app-exp
(rator lc-exp?)
(rand lc-exp?)))
;;; Trivial 'cases' for testing
(defn lc-exp-numargs
[exp]
(cases lc-exp exp
(var-exp (variable) 1)
(lambda-exp (bound-var body) 2)
(app-exp (rator rand) 3)))
(deftest test-lc-exp-simple
(let [ve (var-exp 't)]
(is (lc-exp? ve))
(is (var-exp? ve))
(is (not (app-exp? ve)))
(is (= 1 (lc-exp-numargs ve))))
(let [v (lambda-exp 'v (app-exp (var-exp 'v) (var-exp 't)))]
(is (lc-exp? v))
(is (lambda-exp? v))
(is (= 'v (lambda-exp->bound-var v)))
(is (app-exp? (lambda-exp->body v)))
(is (= 2 (lc-exp-numargs v)))
(is (= 3 (lc-exp-numargs (lambda-exp->body v))))
(is (= 1 (lc-exp-numargs (app-exp->rator (lambda-exp->body v)))))
(is (= 1 (lc-exp-numargs (app-exp->rand (lambda-exp->body v)))))))
(defn occurs-free?
"Does search-var occur as a free variable in exp?"
[search-var exp]
(cases lc-exp exp
(var-exp (variable) (= variable search-var))
(lambda-exp (bound-var body)
(and (not (= search-var bound-var))
(occurs-free? search-var body)))
(app-exp (rator rand)
(or
(occurs-free? search-var rator)
(occurs-free? search-var rand)))))
(deftest test-lc-exp-occurs-free
(let [ve (var-exp 't)]
(is (occurs-free? 't ve))
(is (not (occurs-free? 'r ve)))
(let [ae (app-exp (var-exp 't) (app-exp (var-exp 'd) (var-exp 'e)))]
(is (occurs-free? 't ae))
(is (occurs-free? 'd ae))
(is (occurs-free? 'e ae))
(is (not (occurs-free? 'p ae))))
(let [le (lambda-exp 'v (app-exp (var-exp 'v) (var-exp 't)))]
(is (occurs-free? 't le))
(is (not (occurs-free? 'v le))))
(let [ne (app-exp
(var-exp 't)
(app-exp
(var-exp 'd)
(lambda-exp 'v (app-exp (var-exp 'c) (var-exp 'v)))))]
(is (occurs-free? 't ne))
(is (occurs-free? 'd ne))
(is (occurs-free? 'c ne))
(is (not (occurs-free? 'v ne))))))
;;; Exercise 2.21: the environment data structure, from section 2.2.2
(defn symbol-or-number? [v] (or (symbol? v) (number? v)))
(define-datatype env env?
(empty-env)
(extend-env
(var symbol?)
(val symbol-or-number?)
(env env?)))
(defn apply-env
[e search-var]
(cases env e
(empty-env () (assert false "apply-env on empty env"))
(extend-env (var val saved-env)
(if (= search-var var)
val
(apply-env saved-env search-var)))))
(defn has-binding?
[e search-var]
(cases env e
(empty-env () false)
(extend-env (var val saved-env)
(or (= search-var var)
(has-binding? saved-env search-var)))))
(deftest test-env
(let [emp (empty-env)]
(is (env? emp)))
(let [ext1 (extend-env 'v 20 (empty-env))]
(is (env? ext1))
(is (= (extend-env->var ext1) 'v))
(is (= (apply-env ext1 'v) 20))
(is (has-binding? ext1 'v))
(is (thrown? AssertionError (apply-env ext1 'jk)))
(is (not (has-binding? ext1 'jf)))
(is (= (extend-env->val ext1) 20)))
(let [ext3 (extend-env
'a 1 (extend-env 'b 2 (extend-env 'c 3 (empty-env))))]
(is (= (apply-env ext3 'a) 1))
(is (has-binding? ext3 'a))
(is (= (apply-env ext3 'b) 2))
(is (has-binding? ext3 'b))
(is (= (apply-env ext3 'c) 3))
(is (has-binding? ext3 'c))
(is (not (has-binding? ext3 'd)))
(is (thrown? AssertionError (apply-env ext3 'd)))))
;;; Exercise 2.24: binary tree
(define-datatype bintree bintree?
(leaf-node
(num integer?))
(interior-node
(key symbol?)
(left bintree?)
(right bintree?)))
(defn bintree-to-list
[bt]
(cases bintree bt
(leaf-node (num) (list 'leaf-node num))
(interior-node (key left right)
(list 'interior-node
key
(bintree-to-list left)
(bintree-to-list right)))))
(defn max-interior
[bt]
;; exercise 2.25
(cases bintree bt
(leaf-node (num) [num nil])
(interior-node (key left right)
(let [[leftsum leftsym] (max-interior left)
[rightsum rightsym] (max-interior right)
mysum (+ leftsum rightsum)]
(cond
(and (> mysum rightsum) (> mysum leftsum))
[mysum key]
(and (> leftsum rightsum) (> leftsum mysum))
[leftsum leftsym]
:else
[rightsum rightsym])))))
(deftest test-bintree
(let [bt1 (interior-node 'k
(interior-node 'p (leaf-node 20) (leaf-node 30))
(leaf-node 40))]
(is (bintree? bt1))
(is (= (bintree-to-list bt1)
'(interior-node k
(interior-node p (leaf-node 20) (leaf-node 30))
(leaf-node 40)))))
(let [tree-1 (interior-node 'foo (leaf-node 2) (leaf-node 3))
tree-2 (interior-node 'bar (leaf-node -1) tree-1)
tree-3 (interior-node 'baz tree-2 (leaf-node 1))]
(is (= [5 'foo] (max-interior tree-2)))
(is (= [6 'baz] (max-interior tree-3)))))
(run-tests)
| true |
;;; Clojure implementation of the 'define-datatypes' and 'cases' macros from
;;; the "Elements of Programming Languages" (EOPL) book - third edition.
;;;
;;; Given:
;;;
;;; (define-datatype lc-exp lc-exp?
;;; (var-exp
;;; (var symbol?))
;;; (lambda-exp
;;; (bound-var symbol?)
;;; (body lc-exp?))
;;; (app-exp
;;; (rator lc-exp?)
;;; (rand lc-exp?)))
;;;
;;; We createa a "type" named 'lc-exp, with 3 variants: 'var-exp, 'lambda-exp
;;; and 'app-exp. The following functions are defined automatically:
;;;
;;; Predicate -- is arg an lc-exp?:
;;; lc-exp?: fn [arg] ; predicate: is arg an lc-exp?
;;;
;;; Constructors that verify that their arguments comply to the predicates
;;; provided in the define-datatype specification, and predicates that check
;;; that the given object is a variant:
;;; var-exp: fn [var]
;;; var-exp?: fn [arg]
;;; lambda-exp: fn [bound-var body]
;;; lambda-exp?: fn [arg?]
;;; app-exp: fn [rator rand]
;;; app-exp?: fn [arg]
;;;
;;; Accessors for fields:
;;; var-exp->var: fn [arg]
;;; lambda-exp->bound-var: fn [arg]
;;; lambda-exp->body: fn [arg]
;;; app-exp->rator: fn [arg]
;;; app-exp->rand: fn [arg]
;;;
;;; Also, the macro 'cases' permits compact actions on objects created with
;;; define-datatypes. See tests below.
;;;
;;; This system creates "objects" as follows:
;;;
;;; (typename variant-name field1 field2 ... fieldN)
;;;
;;; typename is the name of the encompassing type (such as 'lc-exp);
;;; variant-name is the name of the specific variant of the type (such as
;;; 'app-exp); field1...N are the fields of the variant (for example the variant
;;; 'app-exp has two fields)
;;;
;;; PI:NAME:<NAME>END_PI [http://eli.thegreenplace.net]
;;; This code is in the public domain.
(ns define-datatype.define-datatype
(:use clojure.test))
(defn internfunc
"Helper for interning a function with the given name (as a string) in the
current namespace."
[strname func]
(intern *ns* (symbol strname) func))
(defn make-accessor
"Creates an accessor for field 'fielname' in variant 'variant-name'.
The accessor is positional using 'nth'."
[variant-name fieldname fieldpos]
(letfn [(func [obj]
(nth obj fieldpos))]
(internfunc (str variant-name "->" fieldname) func)))
(defn make-predicate
"Creates a predicate function to test whether a given object belongs to a type
variant. numfields is the number of fields the variant object is expected to
have."
[typename variant-name numfields]
(letfn [(func [obj]
(and (= (count obj) (+ 2 numfields))
(= (first obj) typename)
(= (second obj) variant-name)))]
(internfunc (str variant-name "?") func)))
(defn make-ctor
"Creates a constructor function for the given variant of a type. predicates is
a list of predicates for the fields passed to the constructor."
[typename variant-name predicates]
(letfn [(func [& field-initializers]
(do
(assert (= (count field-initializers) (count predicates)))
(assert (every? true? (map (fn [pred field]
((resolve pred) field))
predicates
field-initializers)))
(cons typename (cons variant-name field-initializers))))]
(internfunc (str variant-name) func)))
(defn make-type-variant
"Creates a type variant with a constructor, predicate and accessors.
The typename and variant-name are symbols; field-descriptors is a list of
pairs, each consisting of two symbols: field name and a predicate to test for
the validity of this field when creating a type variant. The predicate is a
symbol, not an actual Clojure function."
[typename variant-name field-descriptors]
(let [numfields (count field-descriptors)
predicates (map second field-descriptors)]
(do
;; Create the constructor for this type.
(make-ctor typename variant-name predicates)
;; Create the predicate for this type.
(make-predicate typename variant-name numfields)
;; Create field accessors.
(doseq [[field-index [fieldname field-predicate]]
(map-indexed vector field-descriptors)]
(make-accessor variant-name fieldname (+ 2 field-index))))))
(defn define-datatype-aux
"Creates a datatype from the specification. This is a function, so all its
arguments are symbols or quoted lists. In particular, variant-descriptors is a
quoted list of all the descriptors."
[typename predicate-name variant-descriptors]
(do
(letfn [(pred-func [obj]
(= (first obj) typename))]
(internfunc (str predicate-name) pred-func))
(doseq [[variant-name & field-descriptors] variant-descriptors]
(make-type-variant typename variant-name field-descriptors))))
(defmacro define-datatype
"Simple macro wrapper around define-datatype-aux, so that the type name,
predicate name and variant descriptors don't have to be quoted but rather can
be regular Clojure symbols."
[typename predicate-name & variant-descriptors]
(define-datatype-aux typename predicate-name variant-descriptors))
(defn make-cond-case
"Helper function for cases that generates a single case for the variant cond.
variant-case is one variant case as given to the cases macro.
obj-variant is the actual object variant (a symbol) as taken from the object.
obj-fields is the list of the actual object's fields.
Produces the code for '(cond-case cond-action)."
[variant-case obj-variant obj-fields]
`((= (quote ~(first variant-case)) ~obj-variant)
(apply (fn [~@(second variant-case)] ~(last variant-case)) ~obj-fields)))
(defmacro cases
[typename obj & variant-cases]
(let [obj-type-sym (gensym 'type)
obj-variant-sym (gensym 'variant)
obj-fields-sym (gensym 'fields)]
`(let [[~obj-type-sym ~obj-variant-sym & ~obj-fields-sym] ~obj]
(assert (= ~obj-type-sym (quote ~typename)) "Unexpected type")
(cond
~@(mapcat (fn [vc] (make-cond-case vc obj-variant-sym obj-fields-sym))
variant-cases)
:else (assert false "Unsupported variant")))))
;;; ------------------ Testing ------------------
;;; A silly tuple is either a single symbol, or a pair of integers.
(define-datatype sillytuple sillytuple?
(single (s symbol?))
(pair (i integer?) (j integer?)))
(deftest test-sillytuple-single
(let [s (single 'k)]
(is (sillytuple? s))
(is (single? s))
(is (not (pair? s)))
(is (= 'k (single->s s)))))
(deftest test-sillytuple-bad-single
(is (thrown? AssertionError (single '(k))))
(is (thrown? AssertionError (single 20))))
(deftest test-sillytuple-pair
(let [p (pair 10 20)]
(is (sillytuple? p))
(is (pair? p))
(is (not (single? p)))
(is (= 10 (pair->i p)))
(is (= 20 (pair->j p)))))
(deftest test-sillytuple-bad-pair
(is (thrown? AssertionError (pair 'foo 10)))
(is (thrown? AssertionError (pair 20 21.5))))
(deftest test-sillytuple-simple-cases
;; Test that a simple cases definition works well
(letfn [(good? [st]
(cases sillytuple st
(single (s) (= s 'good))
(pair (i j) (> i j))))]
(is (not (good? (single 'food))))
(is (good? (single 'good)))
(is (good? (pair 10 9)))
(is (not (good? (pair 10 19))))
(is (thrown-with-msg?
AssertionError #"Unexpected" (good? '(kuku da))))
;; Force-create a bad silly tuple (inexistent variant) and good? should
;; throw as expected.
(is (thrown-with-msg?
AssertionError #"Unsupported variant"
(good? '(sillytuple foobar 20))))))
(define-datatype lc-exp lc-exp?
(var-exp
(var symbol?))
(lambda-exp
(bound-var symbol?)
(body lc-exp?))
(app-exp
(rator lc-exp?)
(rand lc-exp?)))
;;; Trivial 'cases' for testing
(defn lc-exp-numargs
[exp]
(cases lc-exp exp
(var-exp (variable) 1)
(lambda-exp (bound-var body) 2)
(app-exp (rator rand) 3)))
(deftest test-lc-exp-simple
(let [ve (var-exp 't)]
(is (lc-exp? ve))
(is (var-exp? ve))
(is (not (app-exp? ve)))
(is (= 1 (lc-exp-numargs ve))))
(let [v (lambda-exp 'v (app-exp (var-exp 'v) (var-exp 't)))]
(is (lc-exp? v))
(is (lambda-exp? v))
(is (= 'v (lambda-exp->bound-var v)))
(is (app-exp? (lambda-exp->body v)))
(is (= 2 (lc-exp-numargs v)))
(is (= 3 (lc-exp-numargs (lambda-exp->body v))))
(is (= 1 (lc-exp-numargs (app-exp->rator (lambda-exp->body v)))))
(is (= 1 (lc-exp-numargs (app-exp->rand (lambda-exp->body v)))))))
(defn occurs-free?
"Does search-var occur as a free variable in exp?"
[search-var exp]
(cases lc-exp exp
(var-exp (variable) (= variable search-var))
(lambda-exp (bound-var body)
(and (not (= search-var bound-var))
(occurs-free? search-var body)))
(app-exp (rator rand)
(or
(occurs-free? search-var rator)
(occurs-free? search-var rand)))))
(deftest test-lc-exp-occurs-free
(let [ve (var-exp 't)]
(is (occurs-free? 't ve))
(is (not (occurs-free? 'r ve)))
(let [ae (app-exp (var-exp 't) (app-exp (var-exp 'd) (var-exp 'e)))]
(is (occurs-free? 't ae))
(is (occurs-free? 'd ae))
(is (occurs-free? 'e ae))
(is (not (occurs-free? 'p ae))))
(let [le (lambda-exp 'v (app-exp (var-exp 'v) (var-exp 't)))]
(is (occurs-free? 't le))
(is (not (occurs-free? 'v le))))
(let [ne (app-exp
(var-exp 't)
(app-exp
(var-exp 'd)
(lambda-exp 'v (app-exp (var-exp 'c) (var-exp 'v)))))]
(is (occurs-free? 't ne))
(is (occurs-free? 'd ne))
(is (occurs-free? 'c ne))
(is (not (occurs-free? 'v ne))))))
;;; Exercise 2.21: the environment data structure, from section 2.2.2
(defn symbol-or-number? [v] (or (symbol? v) (number? v)))
(define-datatype env env?
(empty-env)
(extend-env
(var symbol?)
(val symbol-or-number?)
(env env?)))
(defn apply-env
[e search-var]
(cases env e
(empty-env () (assert false "apply-env on empty env"))
(extend-env (var val saved-env)
(if (= search-var var)
val
(apply-env saved-env search-var)))))
(defn has-binding?
[e search-var]
(cases env e
(empty-env () false)
(extend-env (var val saved-env)
(or (= search-var var)
(has-binding? saved-env search-var)))))
(deftest test-env
(let [emp (empty-env)]
(is (env? emp)))
(let [ext1 (extend-env 'v 20 (empty-env))]
(is (env? ext1))
(is (= (extend-env->var ext1) 'v))
(is (= (apply-env ext1 'v) 20))
(is (has-binding? ext1 'v))
(is (thrown? AssertionError (apply-env ext1 'jk)))
(is (not (has-binding? ext1 'jf)))
(is (= (extend-env->val ext1) 20)))
(let [ext3 (extend-env
'a 1 (extend-env 'b 2 (extend-env 'c 3 (empty-env))))]
(is (= (apply-env ext3 'a) 1))
(is (has-binding? ext3 'a))
(is (= (apply-env ext3 'b) 2))
(is (has-binding? ext3 'b))
(is (= (apply-env ext3 'c) 3))
(is (has-binding? ext3 'c))
(is (not (has-binding? ext3 'd)))
(is (thrown? AssertionError (apply-env ext3 'd)))))
;;; Exercise 2.24: binary tree
(define-datatype bintree bintree?
(leaf-node
(num integer?))
(interior-node
(key symbol?)
(left bintree?)
(right bintree?)))
(defn bintree-to-list
[bt]
(cases bintree bt
(leaf-node (num) (list 'leaf-node num))
(interior-node (key left right)
(list 'interior-node
key
(bintree-to-list left)
(bintree-to-list right)))))
(defn max-interior
[bt]
;; exercise 2.25
(cases bintree bt
(leaf-node (num) [num nil])
(interior-node (key left right)
(let [[leftsum leftsym] (max-interior left)
[rightsum rightsym] (max-interior right)
mysum (+ leftsum rightsum)]
(cond
(and (> mysum rightsum) (> mysum leftsum))
[mysum key]
(and (> leftsum rightsum) (> leftsum mysum))
[leftsum leftsym]
:else
[rightsum rightsym])))))
(deftest test-bintree
(let [bt1 (interior-node 'k
(interior-node 'p (leaf-node 20) (leaf-node 30))
(leaf-node 40))]
(is (bintree? bt1))
(is (= (bintree-to-list bt1)
'(interior-node k
(interior-node p (leaf-node 20) (leaf-node 30))
(leaf-node 40)))))
(let [tree-1 (interior-node 'foo (leaf-node 2) (leaf-node 3))
tree-2 (interior-node 'bar (leaf-node -1) tree-1)
tree-3 (interior-node 'baz tree-2 (leaf-node 1))]
(is (= [5 'foo] (max-interior tree-2)))
(is (= [6 'baz] (max-interior tree-3)))))
(run-tests)
|
[
{
"context": "(deftest raw-execute\n (people/add* @conn {:name \"yest\"\n :email \"[email protected]\"\n ",
"end": 872,
"score": 0.9855780601501465,
"start": 868,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "@conn {:name \"yest\"\n :email \"[email protected]\"\n :entity-id #uuid \"9273175",
"end": 917,
"score": 0.9999198913574219,
"start": 904,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "rce/to-date-time \"2019-02-03\")\n :email \"[email protected]\"\n :name \"yest\"}]\n (map\n ",
"end": 1360,
"score": 0.9999216198921204,
"start": 1347,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :email \"[email protected]\"\n :name \"yest\"}]\n (map\n #(dissoc %\n ",
"end": 1384,
"score": 0.9726669788360596,
"start": 1380,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "nsaction [tx @conn]\n (people/add* tx {:name \"yest\"\n :email \"[email protected]\"\n ",
"end": 2032,
"score": 0.8084775805473328,
"start": 2028,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "* tx {:name \"yest\"\n :email \"[email protected]\"\n :entity-id #uuid \"927317",
"end": 2078,
"score": 0.9999229311943054,
"start": 2065,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "inst \"2019-02-03\"})\n (people/add* tx {:name \"who\"\n :email \"[email protected]\"\n ",
"end": 2347,
"score": 0.8452842831611633,
"start": 2344,
"tag": "USERNAME",
"value": "who"
},
{
"context": "d* tx {:name \"who\"\n :email \"[email protected]\"\n :entity-id #uuid \"927317",
"end": 2392,
"score": 0.9999192357063293,
"start": 2380,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "ollback-only true}]\n (people/add* tx {:name \"yest\"\n :email \"[email protected]\"",
"end": 3198,
"score": 0.5915173292160034,
"start": 3197,
"tag": "NAME",
"value": "y"
},
{
"context": "llback-only true}]\n (people/add* tx {:name \"yest\"\n :email \"[email protected]\"\n ",
"end": 3201,
"score": 0.5610173940658569,
"start": 3198,
"tag": "USERNAME",
"value": "est"
},
{
"context": "* tx {:name \"yest\"\n :email \"[email protected]\"\n :entity-id #uuid \"927317",
"end": 3247,
"score": 0.9999231100082397,
"start": 3234,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "d* tx {:name nil\n :email \"[email protected]\"\n :attributes {:bar 1\n ",
"end": 3574,
"score": 0.9999240040779114,
"start": 3562,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "\n(deftest modes-test\n (people/add* @conn {:name \"yest\"\n :email \"[email protected]\"\n ",
"end": 3975,
"score": 0.9996521472930908,
"start": 3971,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "@conn {:name \"yest\"\n :email \"[email protected]\"\n :entity-id #uuid \"9273175",
"end": 4020,
"score": 0.9999254941940308,
"start": 4007,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :foo [:a :b :c]}})\n (people/add* @conn {:name \"yest2\"\n :email \"[email protected]\"\n ",
"end": 4286,
"score": 0.9996967315673828,
"start": 4281,
"tag": "USERNAME",
"value": "yest2"
},
{
"context": "conn {:name \"yest2\"\n :email \"[email protected]\"\n :entity-id #uuid \"9273175",
"end": 4332,
"score": 0.9999256134033203,
"start": 4318,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "time \"2019-02-03T00:00:00\"),\n :email \"[email protected]\",\n :name \"yest\"}\n {:attrib",
"end": 4759,
"score": 0.9999253153800964,
"start": 4746,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :email \"[email protected]\",\n :name \"yest\"}\n {:attributes {:bar 1, :foo [\"a\" \"b\"",
"end": 4786,
"score": 0.9996548295021057,
"start": 4782,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "time \"2019-02-03T00:00:00\"),\n :email \"[email protected]\",\n :name \"yest2\"}]\n (helper",
"end": 4951,
"score": 0.9999268651008606,
"start": 4937,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :email \"[email protected]\",\n :name \"yest2\"}]\n (helpers/execute @conn [\"select att",
"end": 4979,
"score": 0.9996652603149414,
"start": 4974,
"tag": "USERNAME",
"value": "yest2"
},
{
"context": "019-02-03T00:00:00\"),\n :people/email \"[email protected]\",\n :people/name \"yest\"}\n {",
"end": 5288,
"score": 0.9999246597290039,
"start": 5275,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "email \"[email protected]\",\n :people/name \"yest\"}\n {:people/attributes {:bar 1, :foo [",
"end": 5322,
"score": 0.9987285137176514,
"start": 5318,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "019-02-03T00:00:00\"),\n :people/email \"[email protected]\",\n :people/name \"yest2\"}]\n ",
"end": 5508,
"score": 0.9999244809150696,
"start": 5494,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "mail \"[email protected]\",\n :people/name \"yest2\"}]\n (helpers/execute @conn [\"select att",
"end": 5543,
"score": 0.9992983937263489,
"start": 5538,
"tag": "USERNAME",
"value": "yest2"
},
{
"context": "time \"2019-02-03T00:00:00\"),\n :email \"[email protected]\",\n :name \"yest\"}\n {:attrib",
"end": 5858,
"score": 0.9999231100082397,
"start": 5845,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :email \"[email protected]\",\n :name \"yest\"}\n {:attributes {:bar 1, :foo [\"a\" \"b\"",
"end": 5885,
"score": 0.9987584352493286,
"start": 5881,
"tag": "USERNAME",
"value": "yest"
},
{
"context": "time \"2019-02-03T00:00:00\"),\n :email \"[email protected]\",\n :name \"yest2\"}]\n (helper",
"end": 6050,
"score": 0.9999262690544128,
"start": 6036,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :email \"[email protected]\",\n :name \"yest2\"}]\n (helpers/execute @conn [\"select att",
"end": 6078,
"score": 0.9992724061012268,
"start": 6073,
"tag": "USERNAME",
"value": "yest2"
}
] |
test/utility_belt/sql/helpers_test.clj
|
nomnom-insights/nomnom.utility-belt.sql
| 2 |
(ns utility-belt.sql.helpers-test
(:require
[clj-time.coerce :as coerce]
[clojure.test :refer [deftest testing is use-fixtures]]
;; -- test helpers
[utility-belt.sql.connection :as connection]
;; -- actual things under test
[utility-belt.sql.conv]
[utility-belt.sql.helpers :as helpers]
[utility-belt.sql.people :as people]))
(def conn (atom nil))
(use-fixtures :each (fn [test-fn]
(connection/start! conn)
(try
(people/setup* @conn)
(people/setup-squad* @conn)
(people/setup-users* @conn)
(people/delete-all* @conn)
(test-fn)
(finally
(connection/stop! conn)))))
(deftest raw-execute
(people/add* @conn {:name "yest"
:email "[email protected]"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c]}
:confirmed-at #inst "2019-02-03"})
(is (= [{:attributes {:bar 1 :foo ["a" "b" "c"]}
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at (coerce/to-date-time "2019-02-03")
:email "[email protected]"
:name "yest"}]
(map
#(dissoc %
:id
:created-at
:updated-at)
(helpers/execute @conn ["select * from people"])))))
(deftest transaction-operation
(testing "detecting transactions"
(helpers/with-transaction [tx @conn {:read-only true}]
(is (true? (helpers/transaction? tx)))
;; need to run something to avoid "connection closed" error
(helpers/execute tx ["select * from now()"]))
(is (false? (helpers/transaction? @conn))))
(testing "operations in a transaction"
(helpers/with-transaction [tx @conn]
(people/add* tx {:name "yest"
:email "[email protected]"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c]}
:confirmed-at #inst "2019-02-03"})
(people/add* tx {:name "who"
:email "[email protected]"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo {:ok :dawg}}
:confirmed-at #inst "2019-02-03"})
(testing "tx not finished yet so using db-pool no results should be reutnred"
(is (= 0 (count (people/get-all* @conn)))))
(testing "when reading via transaction, we get the correct result"
(is (= 2 (count (people/get-all* tx))))))
(testing "tx is done, we can read via normal conn:"
(is (= 2 (count (people/get-all* @conn))))))
(testing "failing within transaction - should not add rows if an exception is thrown during transaction"
(helpers/with-transaction [tx @conn {:rollback-only true}]
(people/add* tx {:name "yest"
:email "[email protected]"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(try
(people/add* tx {:name nil
:email "[email protected]"
:attributes {:bar 1
:foo {:ok :dawg}}})
(catch Exception e
(is (= "Parameter Mismatch: :confirmed-at parameter data not found."
(ex-message e))))))
(testing "No new data should be inserted"
(is (= 2 (count (people/get-all* @conn)))))))
(deftest modes-test
(people/add* @conn {:name "yest"
:email "[email protected]"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(people/add* @conn {:name "yest2"
:email "[email protected]"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(testing "default - kebab-maps"
(is (= [{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed-at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "[email protected]",
:name "yest"}
{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed-at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "[email protected]",
:name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"]))))
(testing "next.jdbc"
(is (= [{:people/attributes {:bar 1, :foo ["a" "b" "c"]},
:people/confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:people/email "[email protected]",
:people/name "yest"}
{:people/attributes {:bar 1, :foo ["a" "b" "c"]},
:people/confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:people/email "[email protected]",
:people/name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"] {:mode :next.jdbc}))))
(testing "clojure.java.jdbc"
(is (= [{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "[email protected]",
:name "yest"}
{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "[email protected]",
:name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"] {:mode :java.jdbc})))))
|
115260
|
(ns utility-belt.sql.helpers-test
(:require
[clj-time.coerce :as coerce]
[clojure.test :refer [deftest testing is use-fixtures]]
;; -- test helpers
[utility-belt.sql.connection :as connection]
;; -- actual things under test
[utility-belt.sql.conv]
[utility-belt.sql.helpers :as helpers]
[utility-belt.sql.people :as people]))
(def conn (atom nil))
(use-fixtures :each (fn [test-fn]
(connection/start! conn)
(try
(people/setup* @conn)
(people/setup-squad* @conn)
(people/setup-users* @conn)
(people/delete-all* @conn)
(test-fn)
(finally
(connection/stop! conn)))))
(deftest raw-execute
(people/add* @conn {:name "yest"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c]}
:confirmed-at #inst "2019-02-03"})
(is (= [{:attributes {:bar 1 :foo ["a" "b" "c"]}
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at (coerce/to-date-time "2019-02-03")
:email "<EMAIL>"
:name "yest"}]
(map
#(dissoc %
:id
:created-at
:updated-at)
(helpers/execute @conn ["select * from people"])))))
(deftest transaction-operation
(testing "detecting transactions"
(helpers/with-transaction [tx @conn {:read-only true}]
(is (true? (helpers/transaction? tx)))
;; need to run something to avoid "connection closed" error
(helpers/execute tx ["select * from now()"]))
(is (false? (helpers/transaction? @conn))))
(testing "operations in a transaction"
(helpers/with-transaction [tx @conn]
(people/add* tx {:name "yest"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c]}
:confirmed-at #inst "2019-02-03"})
(people/add* tx {:name "who"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo {:ok :dawg}}
:confirmed-at #inst "2019-02-03"})
(testing "tx not finished yet so using db-pool no results should be reutnred"
(is (= 0 (count (people/get-all* @conn)))))
(testing "when reading via transaction, we get the correct result"
(is (= 2 (count (people/get-all* tx))))))
(testing "tx is done, we can read via normal conn:"
(is (= 2 (count (people/get-all* @conn))))))
(testing "failing within transaction - should not add rows if an exception is thrown during transaction"
(helpers/with-transaction [tx @conn {:rollback-only true}]
(people/add* tx {:name "<NAME>est"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(try
(people/add* tx {:name nil
:email "<EMAIL>"
:attributes {:bar 1
:foo {:ok :dawg}}})
(catch Exception e
(is (= "Parameter Mismatch: :confirmed-at parameter data not found."
(ex-message e))))))
(testing "No new data should be inserted"
(is (= 2 (count (people/get-all* @conn)))))))
(deftest modes-test
(people/add* @conn {:name "yest"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(people/add* @conn {:name "yest2"
:email "<EMAIL>"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(testing "default - kebab-maps"
(is (= [{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed-at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "<EMAIL>",
:name "yest"}
{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed-at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "<EMAIL>",
:name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"]))))
(testing "next.jdbc"
(is (= [{:people/attributes {:bar 1, :foo ["a" "b" "c"]},
:people/confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:people/email "<EMAIL>",
:people/name "yest"}
{:people/attributes {:bar 1, :foo ["a" "b" "c"]},
:people/confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:people/email "<EMAIL>",
:people/name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"] {:mode :next.jdbc}))))
(testing "clojure.java.jdbc"
(is (= [{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "<EMAIL>",
:name "yest"}
{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "<EMAIL>",
:name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"] {:mode :java.jdbc})))))
| true |
(ns utility-belt.sql.helpers-test
(:require
[clj-time.coerce :as coerce]
[clojure.test :refer [deftest testing is use-fixtures]]
;; -- test helpers
[utility-belt.sql.connection :as connection]
;; -- actual things under test
[utility-belt.sql.conv]
[utility-belt.sql.helpers :as helpers]
[utility-belt.sql.people :as people]))
(def conn (atom nil))
(use-fixtures :each (fn [test-fn]
(connection/start! conn)
(try
(people/setup* @conn)
(people/setup-squad* @conn)
(people/setup-users* @conn)
(people/delete-all* @conn)
(test-fn)
(finally
(connection/stop! conn)))))
(deftest raw-execute
(people/add* @conn {:name "yest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c]}
:confirmed-at #inst "2019-02-03"})
(is (= [{:attributes {:bar 1 :foo ["a" "b" "c"]}
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at (coerce/to-date-time "2019-02-03")
:email "PI:EMAIL:<EMAIL>END_PI"
:name "yest"}]
(map
#(dissoc %
:id
:created-at
:updated-at)
(helpers/execute @conn ["select * from people"])))))
(deftest transaction-operation
(testing "detecting transactions"
(helpers/with-transaction [tx @conn {:read-only true}]
(is (true? (helpers/transaction? tx)))
;; need to run something to avoid "connection closed" error
(helpers/execute tx ["select * from now()"]))
(is (false? (helpers/transaction? @conn))))
(testing "operations in a transaction"
(helpers/with-transaction [tx @conn]
(people/add* tx {:name "yest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo [:a :b :c]}
:confirmed-at #inst "2019-02-03"})
(people/add* tx {:name "who"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:attributes {:bar 1
:foo {:ok :dawg}}
:confirmed-at #inst "2019-02-03"})
(testing "tx not finished yet so using db-pool no results should be reutnred"
(is (= 0 (count (people/get-all* @conn)))))
(testing "when reading via transaction, we get the correct result"
(is (= 2 (count (people/get-all* tx))))))
(testing "tx is done, we can read via normal conn:"
(is (= 2 (count (people/get-all* @conn))))))
(testing "failing within transaction - should not add rows if an exception is thrown during transaction"
(helpers/with-transaction [tx @conn {:rollback-only true}]
(people/add* tx {:name "PI:NAME:<NAME>END_PIest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(try
(people/add* tx {:name nil
:email "PI:EMAIL:<EMAIL>END_PI"
:attributes {:bar 1
:foo {:ok :dawg}}})
(catch Exception e
(is (= "Parameter Mismatch: :confirmed-at parameter data not found."
(ex-message e))))))
(testing "No new data should be inserted"
(is (= 2 (count (people/get-all* @conn)))))))
(deftest modes-test
(people/add* @conn {:name "yest"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(people/add* @conn {:name "yest2"
:email "PI:EMAIL:<EMAIL>END_PI"
:entity-id #uuid "92731758-98f9-4358-974b-b15c74c917d9"
:confirmed-at #inst "2019-02-03"
:attributes {:bar 1
:foo [:a :b :c]}})
(testing "default - kebab-maps"
(is (= [{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed-at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "PI:EMAIL:<EMAIL>END_PI",
:name "yest"}
{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed-at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "PI:EMAIL:<EMAIL>END_PI",
:name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"]))))
(testing "next.jdbc"
(is (= [{:people/attributes {:bar 1, :foo ["a" "b" "c"]},
:people/confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:people/email "PI:EMAIL:<EMAIL>END_PI",
:people/name "yest"}
{:people/attributes {:bar 1, :foo ["a" "b" "c"]},
:people/confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:people/email "PI:EMAIL:<EMAIL>END_PI",
:people/name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"] {:mode :next.jdbc}))))
(testing "clojure.java.jdbc"
(is (= [{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "PI:EMAIL:<EMAIL>END_PI",
:name "yest"}
{:attributes {:bar 1, :foo ["a" "b" "c"]},
:confirmed_at (coerce/to-date-time "2019-02-03T00:00:00"),
:email "PI:EMAIL:<EMAIL>END_PI",
:name "yest2"}]
(helpers/execute @conn ["select attributes, confirmed_at, email, name from people"] {:mode :java.jdbc})))))
|
[
{
"context": "tem\n {:body (let [home \"https://github.com/milelo/yetipad-app\"\n app \"https://ye",
"end": 1109,
"score": 0.9530647397041321,
"start": 1103,
"tag": "USERNAME",
"value": "milelo"
},
{
"context": " {:title \"Author\" :content \"Mike Longworth\"}\n ]])\n :buttons [up",
"end": 1434,
"score": 0.9998744130134583,
"start": 1420,
"tag": "NAME",
"value": "Mike Longworth"
}
] |
src/app/ui/about_pane.cljs
|
milelo/yetipad-app
| 2 |
(ns app.ui.about-pane
(:require
[app.ui.registry :as reg]
[app.ui.ui :as ui]
[lib.utils :as utils :refer-macros [for-all]]
["@material-ui/core" :refer [Tooltip Typography
TableContainer TableBody Table TableHead TableRow TableCell
]]
["@material-ui/icons/Info" :default about-icon]
["@material-ui/icons/SystemUpdateTwoTone" :default update-icon]))
(defn table [data]
[:<>
[:> Typography {:variant :h6} "Yetipad - Development release"]
[:> TableContainer
[:> Table {:size :small}
[:> TableBody
(for-all [{:keys [title content]} data]
^{:key title} [:> TableRow [:> TableCell title] [:> TableCell content]]
)]]]])
(defn update-app-button []
;todo this doesn't work on mobile
[ui/item-button update-icon "update-app" #(js/window.location.reload true)])
(defn about-pane [_context]
(let [item {:id :about
:kind :about
:title "About app"
}
]
[ui/viewer-pane item
{:body (let [home "https://github.com/milelo/yetipad-app"
app "https://yetipad.mikelongworth.uk"
]
[table [{:title "Home-page" :content [:a {:href home} home]}
{:title "App: new document" :content [:a {:href app} app]}
{:title "Author" :content "Mike Longworth"}
]])
:buttons [update-app-button ui/fullscreen-button]
}]))
(reg/register {:id :about
:title "About"
:icon about-icon
:pane about-pane
})
|
97818
|
(ns app.ui.about-pane
(:require
[app.ui.registry :as reg]
[app.ui.ui :as ui]
[lib.utils :as utils :refer-macros [for-all]]
["@material-ui/core" :refer [Tooltip Typography
TableContainer TableBody Table TableHead TableRow TableCell
]]
["@material-ui/icons/Info" :default about-icon]
["@material-ui/icons/SystemUpdateTwoTone" :default update-icon]))
(defn table [data]
[:<>
[:> Typography {:variant :h6} "Yetipad - Development release"]
[:> TableContainer
[:> Table {:size :small}
[:> TableBody
(for-all [{:keys [title content]} data]
^{:key title} [:> TableRow [:> TableCell title] [:> TableCell content]]
)]]]])
(defn update-app-button []
;todo this doesn't work on mobile
[ui/item-button update-icon "update-app" #(js/window.location.reload true)])
(defn about-pane [_context]
(let [item {:id :about
:kind :about
:title "About app"
}
]
[ui/viewer-pane item
{:body (let [home "https://github.com/milelo/yetipad-app"
app "https://yetipad.mikelongworth.uk"
]
[table [{:title "Home-page" :content [:a {:href home} home]}
{:title "App: new document" :content [:a {:href app} app]}
{:title "Author" :content "<NAME>"}
]])
:buttons [update-app-button ui/fullscreen-button]
}]))
(reg/register {:id :about
:title "About"
:icon about-icon
:pane about-pane
})
| true |
(ns app.ui.about-pane
(:require
[app.ui.registry :as reg]
[app.ui.ui :as ui]
[lib.utils :as utils :refer-macros [for-all]]
["@material-ui/core" :refer [Tooltip Typography
TableContainer TableBody Table TableHead TableRow TableCell
]]
["@material-ui/icons/Info" :default about-icon]
["@material-ui/icons/SystemUpdateTwoTone" :default update-icon]))
(defn table [data]
[:<>
[:> Typography {:variant :h6} "Yetipad - Development release"]
[:> TableContainer
[:> Table {:size :small}
[:> TableBody
(for-all [{:keys [title content]} data]
^{:key title} [:> TableRow [:> TableCell title] [:> TableCell content]]
)]]]])
(defn update-app-button []
;todo this doesn't work on mobile
[ui/item-button update-icon "update-app" #(js/window.location.reload true)])
(defn about-pane [_context]
(let [item {:id :about
:kind :about
:title "About app"
}
]
[ui/viewer-pane item
{:body (let [home "https://github.com/milelo/yetipad-app"
app "https://yetipad.mikelongworth.uk"
]
[table [{:title "Home-page" :content [:a {:href home} home]}
{:title "App: new document" :content [:a {:href app} app]}
{:title "Author" :content "PI:NAME:<NAME>END_PI"}
]])
:buttons [update-app-button ui/fullscreen-button]
}]))
(reg/register {:id :about
:title "About"
:icon about-icon
:pane about-pane
})
|
[
{
"context": " :password (System/getenv \"CLOJARS_PASS\")}]))\n\n(task-options!\n pom {:project 'edna/lein-",
"end": 352,
"score": 0.974825382232666,
"start": 340,
"tag": "PASSWORD",
"value": "CLOJARS_PASS"
},
{
"context": "ng edna projects\"\n :url \"https://github.com/oakes/edna\"\n :license {\"Public Domain\" \"http://un",
"end": 530,
"score": 0.7152340412139893,
"start": 525,
"tag": "USERNAME",
"value": "oakes"
}
] |
template/build.boot
|
based2/edna
| 0 |
(set-env!
:resource-paths #{"src"}
:dependencies '[[org.clojure/clojure "1.9.0" :scope "provided"]]
:repositories (conj (get-env :repositories)
["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "CLOJARS_PASS")}]))
(task-options!
pom {:project 'edna/lein-template
:version "1.5.3"
:description "A template for making edna projects"
:url "https://github.com/oakes/edna"
:license {"Public Domain" "http://unlicense.org/UNLICENSE"}}
push {:repo "clojars"})
(deftask local []
(comp (pom) (jar) (install)))
(deftask deploy []
(comp (pom) (jar) (push)))
|
8764
|
(set-env!
:resource-paths #{"src"}
:dependencies '[[org.clojure/clojure "1.9.0" :scope "provided"]]
:repositories (conj (get-env :repositories)
["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "<PASSWORD>")}]))
(task-options!
pom {:project 'edna/lein-template
:version "1.5.3"
:description "A template for making edna projects"
:url "https://github.com/oakes/edna"
:license {"Public Domain" "http://unlicense.org/UNLICENSE"}}
push {:repo "clojars"})
(deftask local []
(comp (pom) (jar) (install)))
(deftask deploy []
(comp (pom) (jar) (push)))
| true |
(set-env!
:resource-paths #{"src"}
:dependencies '[[org.clojure/clojure "1.9.0" :scope "provided"]]
:repositories (conj (get-env :repositories)
["clojars" {:url "https://clojars.org/repo/"
:username (System/getenv "CLOJARS_USER")
:password (System/getenv "PI:PASSWORD:<PASSWORD>END_PI")}]))
(task-options!
pom {:project 'edna/lein-template
:version "1.5.3"
:description "A template for making edna projects"
:url "https://github.com/oakes/edna"
:license {"Public Domain" "http://unlicense.org/UNLICENSE"}}
push {:repo "clojars"})
(deftask local []
(comp (pom) (jar) (install)))
(deftask deploy []
(comp (pom) (jar) (push)))
|
[
{
"context": "ogs minus credentials\"\n [e]\n (assoc e :db-pass \"xxxxxxx\"))\n\n(defn alia\n \"alia shaped configuration\"\n [e",
"end": 3008,
"score": 0.997026264667511,
"start": 3001,
"tag": "PASSWORD",
"value": "xxxxxxx"
}
] |
src/lcmap/nemo/config.clj
|
USGS-EROS/lcmap-nemo
| 0 |
(ns lcmap.nemo.config
"Configuration related functions.
Values are obtained from ENV variables and/or profiles.clj. These are:
| ENV | Description |
| --------------------------- | ----------------------------------------|
| `DB_HOST` | Cassandra node |
| `DB_USER` | Cassandra username |
| `DB_PASS` | Cassandra password |
| `DB_PORT` | Cassandra cluster port |
| `DB_KEYSPACE` | Cassandra keyspace name |
| `DB_TABLES` | Cassandra tables to expose as resources |
| `DB_CONNECT_TIMEOUT_MILLIS` | Cassandra connection timeout |
| `DB_READ_TIMEOUT_MILLIS` | Cassandra read timeout |
| `HTTP_PORT` | HTTP listener port |
"
(:require [clojure.tools.logging :as log]
[environ.core :refer [env]]
[lcmap.nemo.util :as util]
[qbits.alia.policy.load-balancing :as lb]))
(defn string->vector
"Split string on comma into vector"
[s]
(if (nil? s)
nil
(->> (clojure.string/split s #"[,]+")
(map clojure.string/trim)
(vec))))
(defn nil-kv?
"presents a sequence of [:key value] in terms of {:key (nil? value)}"
[kv]
(reduce-kv (fn [m k v] (assoc m k (nil? v))) {} kv))
(defn environment
"return the environment map for nemo"
[]
{:db-host (-> env :db-host)
:db-user (-> env :db-user)
:db-pass (-> env :db-pass)
:db-port (-> env :db-port util/numberize)
:db-keyspace (-> env :db-keyspace)
:db-tables (-> env :db-tables string->vector)
:db-connect-timeout-millis (util/numberize
(or (-> env :db-connect-timeout-millis) 30000))
:db-read-timeout-millis (util/numberize
(or (-> env :db-read-timeout-millis) 600000))
:http-port (-> env :http-port)
:load-balancing-policy lb/round-robin-policy
:consistency :quorum})
(defn ok?
"checks environment for nil values"
[e]
(let [missing (keys (filter #(true? (second %)) (nil-kv? e)))
message (format "Missing environment variables: %s" missing)]
(if (empty? missing)
(merge e {:ok true})
(merge e {:ok false :message message}))))
(defn with-except
"checks state of environment and raises an exception if not ok"
[e]
(if (:ok e)
e
(do (log/fatal (:message e))
(-> e :message str Exception. throw))))
(defn checked-environment
"returns environment map or raises exception if there are missing values"
[]
(-> (environment) ok? with-except))
(defn sanitize
"returns environment map safe to print in logs minus credentials"
[e]
(assoc e :db-pass "xxxxxxx"))
(defn alia
"alia shaped configuration"
[e]
{:contact-points (-> e :db-host string->vector)
:port (:db-port e)
:credentials {:user (:db-user e) :password (:db-pass e)}
:query-options {:consistency (:consistency e)}
:load-balancing-policy (:load-balancing-policy e)
:socket-options {:read-timeout-millis (:db-read-timeout-millis e)
:connect-timeout-millis (:db-connect-timeout-millis e)}})
|
71297
|
(ns lcmap.nemo.config
"Configuration related functions.
Values are obtained from ENV variables and/or profiles.clj. These are:
| ENV | Description |
| --------------------------- | ----------------------------------------|
| `DB_HOST` | Cassandra node |
| `DB_USER` | Cassandra username |
| `DB_PASS` | Cassandra password |
| `DB_PORT` | Cassandra cluster port |
| `DB_KEYSPACE` | Cassandra keyspace name |
| `DB_TABLES` | Cassandra tables to expose as resources |
| `DB_CONNECT_TIMEOUT_MILLIS` | Cassandra connection timeout |
| `DB_READ_TIMEOUT_MILLIS` | Cassandra read timeout |
| `HTTP_PORT` | HTTP listener port |
"
(:require [clojure.tools.logging :as log]
[environ.core :refer [env]]
[lcmap.nemo.util :as util]
[qbits.alia.policy.load-balancing :as lb]))
(defn string->vector
"Split string on comma into vector"
[s]
(if (nil? s)
nil
(->> (clojure.string/split s #"[,]+")
(map clojure.string/trim)
(vec))))
(defn nil-kv?
"presents a sequence of [:key value] in terms of {:key (nil? value)}"
[kv]
(reduce-kv (fn [m k v] (assoc m k (nil? v))) {} kv))
(defn environment
"return the environment map for nemo"
[]
{:db-host (-> env :db-host)
:db-user (-> env :db-user)
:db-pass (-> env :db-pass)
:db-port (-> env :db-port util/numberize)
:db-keyspace (-> env :db-keyspace)
:db-tables (-> env :db-tables string->vector)
:db-connect-timeout-millis (util/numberize
(or (-> env :db-connect-timeout-millis) 30000))
:db-read-timeout-millis (util/numberize
(or (-> env :db-read-timeout-millis) 600000))
:http-port (-> env :http-port)
:load-balancing-policy lb/round-robin-policy
:consistency :quorum})
(defn ok?
"checks environment for nil values"
[e]
(let [missing (keys (filter #(true? (second %)) (nil-kv? e)))
message (format "Missing environment variables: %s" missing)]
(if (empty? missing)
(merge e {:ok true})
(merge e {:ok false :message message}))))
(defn with-except
"checks state of environment and raises an exception if not ok"
[e]
(if (:ok e)
e
(do (log/fatal (:message e))
(-> e :message str Exception. throw))))
(defn checked-environment
"returns environment map or raises exception if there are missing values"
[]
(-> (environment) ok? with-except))
(defn sanitize
"returns environment map safe to print in logs minus credentials"
[e]
(assoc e :db-pass "<PASSWORD>"))
(defn alia
"alia shaped configuration"
[e]
{:contact-points (-> e :db-host string->vector)
:port (:db-port e)
:credentials {:user (:db-user e) :password (:db-pass e)}
:query-options {:consistency (:consistency e)}
:load-balancing-policy (:load-balancing-policy e)
:socket-options {:read-timeout-millis (:db-read-timeout-millis e)
:connect-timeout-millis (:db-connect-timeout-millis e)}})
| true |
(ns lcmap.nemo.config
"Configuration related functions.
Values are obtained from ENV variables and/or profiles.clj. These are:
| ENV | Description |
| --------------------------- | ----------------------------------------|
| `DB_HOST` | Cassandra node |
| `DB_USER` | Cassandra username |
| `DB_PASS` | Cassandra password |
| `DB_PORT` | Cassandra cluster port |
| `DB_KEYSPACE` | Cassandra keyspace name |
| `DB_TABLES` | Cassandra tables to expose as resources |
| `DB_CONNECT_TIMEOUT_MILLIS` | Cassandra connection timeout |
| `DB_READ_TIMEOUT_MILLIS` | Cassandra read timeout |
| `HTTP_PORT` | HTTP listener port |
"
(:require [clojure.tools.logging :as log]
[environ.core :refer [env]]
[lcmap.nemo.util :as util]
[qbits.alia.policy.load-balancing :as lb]))
(defn string->vector
"Split string on comma into vector"
[s]
(if (nil? s)
nil
(->> (clojure.string/split s #"[,]+")
(map clojure.string/trim)
(vec))))
(defn nil-kv?
"presents a sequence of [:key value] in terms of {:key (nil? value)}"
[kv]
(reduce-kv (fn [m k v] (assoc m k (nil? v))) {} kv))
(defn environment
"return the environment map for nemo"
[]
{:db-host (-> env :db-host)
:db-user (-> env :db-user)
:db-pass (-> env :db-pass)
:db-port (-> env :db-port util/numberize)
:db-keyspace (-> env :db-keyspace)
:db-tables (-> env :db-tables string->vector)
:db-connect-timeout-millis (util/numberize
(or (-> env :db-connect-timeout-millis) 30000))
:db-read-timeout-millis (util/numberize
(or (-> env :db-read-timeout-millis) 600000))
:http-port (-> env :http-port)
:load-balancing-policy lb/round-robin-policy
:consistency :quorum})
(defn ok?
"checks environment for nil values"
[e]
(let [missing (keys (filter #(true? (second %)) (nil-kv? e)))
message (format "Missing environment variables: %s" missing)]
(if (empty? missing)
(merge e {:ok true})
(merge e {:ok false :message message}))))
(defn with-except
"checks state of environment and raises an exception if not ok"
[e]
(if (:ok e)
e
(do (log/fatal (:message e))
(-> e :message str Exception. throw))))
(defn checked-environment
"returns environment map or raises exception if there are missing values"
[]
(-> (environment) ok? with-except))
(defn sanitize
"returns environment map safe to print in logs minus credentials"
[e]
(assoc e :db-pass "PI:PASSWORD:<PASSWORD>END_PI"))
(defn alia
"alia shaped configuration"
[e]
{:contact-points (-> e :db-host string->vector)
:port (:db-port e)
:credentials {:user (:db-user e) :password (:db-pass e)}
:query-options {:consistency (:consistency e)}
:load-balancing-policy (:load-balancing-policy e)
:socket-options {:read-timeout-millis (:db-read-timeout-millis e)
:connect-timeout-millis (:db-connect-timeout-millis e)}})
|
[
{
"context": " shipping to SCServer.\"\n :author \"Sam Aaron\"}\n overtone.sc.machinery.ugen.sc-ugen\n (:use ",
"end": 336,
"score": 0.9998794198036194,
"start": 327,
"tag": "NAME",
"value": "Sam Aaron"
}
] |
src/overtone/sc/machinery/ugen/sc_ugen.clj
|
jamesblunt/overtone
| 1 |
(ns ^{:doc "Records and fns for representing SCUgens. These are to be
distinguished from ugens which are Overtone functions which
compile down into SCUGens. Trees of SCUGens can then, in
turn, be compiled down into a binary synth format for
shipping to SCServer."
:author "Sam Aaron"}
overtone.sc.machinery.ugen.sc-ugen
(:use [overtone.sc.machinery.ugen defaults]
[overtone.helpers lib]))
(defrecord SCUGen [id name rate rate-name special args n-outputs spec])
(derive SCUGen ::sc-ugen)
(defn sc-ugen? [obj] (isa? (type obj) ::sc-ugen))
(defn sc-ugen
"Create a new SCUGen instance. Throws an error if any of the args are nil."
[id name rate rate-name special args n-outputs spec]
(if (or (nil? id)
(nil? name)
(nil? rate)
(nil? rate-name)
(nil? special)
(nil? args)
(nil? n-outputs)
(nil? spec))
(throw (IllegalArgumentException. (str "Attempted to create an SCUGen with nil args. Got " [id name rate rate-name special args n-outputs spec])))
(SCUGen. id name rate rate-name special args n-outputs spec)))
(defn count-ugen-args
"Count the number of ugens in the args of ug (and their args recursively)"
[ug]
(let [args (:args ug)]
(reduce (fn [sum arg]
(if (sc-ugen? arg)
(+ sum 1 (count-ugen-args arg))
sum))
0
args)))
(defmethod print-method SCUGen [ug w]
(.write w (str "#<sc-ugen: " (overtone-ugen-name (:name ug)) (:rate-name ug) " [" (count-ugen-args ug) "]>")))
(defrecord ControlProxy [name value rate rate-name])
(derive ControlProxy ::control-proxy)
(derive ::control-proxy ::sc-ugen)
(defn control-proxy
"Create a new control proxy with the specified name, value and rate. Rate
defaults to :kr. Specifically handles :tr which is really a TrigControl
ugen at :kr. Throws an error if any of the args are nil."
([name value] (control-proxy name value :kr))
([name value rate-name]
(let [rate (if (= rate-name :tr)
(:kr RATES)
(rate-name RATES))]
(if (or (nil? name)
(nil? value)
(nil? rate)
(nil? rate-name))
(throw (IllegalArgumentException. (str "Attempted to create a ControlProxy with nil args. Got " [name value rate rate-name])))
(ControlProxy. name value rate rate-name)))))
(defrecord OutputProxy [name ugen rate rate-name index])
(derive OutputProxy ::output-proxy)
(derive ::output-proxy ::sc-ugen)
(defn output-proxy
"Create a new output proxy. Throws an error if any of the args are nil."
[ugen index]
(let [rate (:rate ugen)
rate-name (REVERSE-RATES (:rate ugen))]
(if (or (nil? ugen)
(nil? rate)
(nil? rate-name)
(nil? index))
(throw (IllegalArgumentException. (str "Attempted to create an OutputProxy with nil args. Got " [ugen rate rate-name index])))
(OutputProxy. "OutputProxy" ugen rate rate-name index))))
(defn control-proxy?
[obj]
(isa? (type obj) ::control-proxy))
(defn output-proxy?
[obj]
(isa? (type obj) ::output-proxy))
(defn mappify-ugen
"Converts all nested SCUgen records into maps creating a data
structure that can play more nicely with Clojure's functions.
For debugging or visualising a ugen tree."
[scug]
(if (map? scug)
(assoc
(into {} scug) :args (map mappify-ugen (:args scug)))
scug))
(defn simplify-ugen
"Turns SCUgen-tree into a simple map of maps and removes all specs.
For debugging or visualising a ugen tree."
[scug]
(if (map? scug)
(assoc
(dissoc (into {} scug) :spec :arg-map :orig-args) :args (map simplify-ugen (:args scug)))
scug))
|
119045
|
(ns ^{:doc "Records and fns for representing SCUgens. These are to be
distinguished from ugens which are Overtone functions which
compile down into SCUGens. Trees of SCUGens can then, in
turn, be compiled down into a binary synth format for
shipping to SCServer."
:author "<NAME>"}
overtone.sc.machinery.ugen.sc-ugen
(:use [overtone.sc.machinery.ugen defaults]
[overtone.helpers lib]))
(defrecord SCUGen [id name rate rate-name special args n-outputs spec])
(derive SCUGen ::sc-ugen)
(defn sc-ugen? [obj] (isa? (type obj) ::sc-ugen))
(defn sc-ugen
"Create a new SCUGen instance. Throws an error if any of the args are nil."
[id name rate rate-name special args n-outputs spec]
(if (or (nil? id)
(nil? name)
(nil? rate)
(nil? rate-name)
(nil? special)
(nil? args)
(nil? n-outputs)
(nil? spec))
(throw (IllegalArgumentException. (str "Attempted to create an SCUGen with nil args. Got " [id name rate rate-name special args n-outputs spec])))
(SCUGen. id name rate rate-name special args n-outputs spec)))
(defn count-ugen-args
"Count the number of ugens in the args of ug (and their args recursively)"
[ug]
(let [args (:args ug)]
(reduce (fn [sum arg]
(if (sc-ugen? arg)
(+ sum 1 (count-ugen-args arg))
sum))
0
args)))
(defmethod print-method SCUGen [ug w]
(.write w (str "#<sc-ugen: " (overtone-ugen-name (:name ug)) (:rate-name ug) " [" (count-ugen-args ug) "]>")))
(defrecord ControlProxy [name value rate rate-name])
(derive ControlProxy ::control-proxy)
(derive ::control-proxy ::sc-ugen)
(defn control-proxy
"Create a new control proxy with the specified name, value and rate. Rate
defaults to :kr. Specifically handles :tr which is really a TrigControl
ugen at :kr. Throws an error if any of the args are nil."
([name value] (control-proxy name value :kr))
([name value rate-name]
(let [rate (if (= rate-name :tr)
(:kr RATES)
(rate-name RATES))]
(if (or (nil? name)
(nil? value)
(nil? rate)
(nil? rate-name))
(throw (IllegalArgumentException. (str "Attempted to create a ControlProxy with nil args. Got " [name value rate rate-name])))
(ControlProxy. name value rate rate-name)))))
(defrecord OutputProxy [name ugen rate rate-name index])
(derive OutputProxy ::output-proxy)
(derive ::output-proxy ::sc-ugen)
(defn output-proxy
"Create a new output proxy. Throws an error if any of the args are nil."
[ugen index]
(let [rate (:rate ugen)
rate-name (REVERSE-RATES (:rate ugen))]
(if (or (nil? ugen)
(nil? rate)
(nil? rate-name)
(nil? index))
(throw (IllegalArgumentException. (str "Attempted to create an OutputProxy with nil args. Got " [ugen rate rate-name index])))
(OutputProxy. "OutputProxy" ugen rate rate-name index))))
(defn control-proxy?
[obj]
(isa? (type obj) ::control-proxy))
(defn output-proxy?
[obj]
(isa? (type obj) ::output-proxy))
(defn mappify-ugen
"Converts all nested SCUgen records into maps creating a data
structure that can play more nicely with Clojure's functions.
For debugging or visualising a ugen tree."
[scug]
(if (map? scug)
(assoc
(into {} scug) :args (map mappify-ugen (:args scug)))
scug))
(defn simplify-ugen
"Turns SCUgen-tree into a simple map of maps and removes all specs.
For debugging or visualising a ugen tree."
[scug]
(if (map? scug)
(assoc
(dissoc (into {} scug) :spec :arg-map :orig-args) :args (map simplify-ugen (:args scug)))
scug))
| true |
(ns ^{:doc "Records and fns for representing SCUgens. These are to be
distinguished from ugens which are Overtone functions which
compile down into SCUGens. Trees of SCUGens can then, in
turn, be compiled down into a binary synth format for
shipping to SCServer."
:author "PI:NAME:<NAME>END_PI"}
overtone.sc.machinery.ugen.sc-ugen
(:use [overtone.sc.machinery.ugen defaults]
[overtone.helpers lib]))
(defrecord SCUGen [id name rate rate-name special args n-outputs spec])
(derive SCUGen ::sc-ugen)
(defn sc-ugen? [obj] (isa? (type obj) ::sc-ugen))
(defn sc-ugen
"Create a new SCUGen instance. Throws an error if any of the args are nil."
[id name rate rate-name special args n-outputs spec]
(if (or (nil? id)
(nil? name)
(nil? rate)
(nil? rate-name)
(nil? special)
(nil? args)
(nil? n-outputs)
(nil? spec))
(throw (IllegalArgumentException. (str "Attempted to create an SCUGen with nil args. Got " [id name rate rate-name special args n-outputs spec])))
(SCUGen. id name rate rate-name special args n-outputs spec)))
(defn count-ugen-args
"Count the number of ugens in the args of ug (and their args recursively)"
[ug]
(let [args (:args ug)]
(reduce (fn [sum arg]
(if (sc-ugen? arg)
(+ sum 1 (count-ugen-args arg))
sum))
0
args)))
(defmethod print-method SCUGen [ug w]
(.write w (str "#<sc-ugen: " (overtone-ugen-name (:name ug)) (:rate-name ug) " [" (count-ugen-args ug) "]>")))
(defrecord ControlProxy [name value rate rate-name])
(derive ControlProxy ::control-proxy)
(derive ::control-proxy ::sc-ugen)
(defn control-proxy
"Create a new control proxy with the specified name, value and rate. Rate
defaults to :kr. Specifically handles :tr which is really a TrigControl
ugen at :kr. Throws an error if any of the args are nil."
([name value] (control-proxy name value :kr))
([name value rate-name]
(let [rate (if (= rate-name :tr)
(:kr RATES)
(rate-name RATES))]
(if (or (nil? name)
(nil? value)
(nil? rate)
(nil? rate-name))
(throw (IllegalArgumentException. (str "Attempted to create a ControlProxy with nil args. Got " [name value rate rate-name])))
(ControlProxy. name value rate rate-name)))))
(defrecord OutputProxy [name ugen rate rate-name index])
(derive OutputProxy ::output-proxy)
(derive ::output-proxy ::sc-ugen)
(defn output-proxy
"Create a new output proxy. Throws an error if any of the args are nil."
[ugen index]
(let [rate (:rate ugen)
rate-name (REVERSE-RATES (:rate ugen))]
(if (or (nil? ugen)
(nil? rate)
(nil? rate-name)
(nil? index))
(throw (IllegalArgumentException. (str "Attempted to create an OutputProxy with nil args. Got " [ugen rate rate-name index])))
(OutputProxy. "OutputProxy" ugen rate rate-name index))))
(defn control-proxy?
[obj]
(isa? (type obj) ::control-proxy))
(defn output-proxy?
[obj]
(isa? (type obj) ::output-proxy))
(defn mappify-ugen
"Converts all nested SCUgen records into maps creating a data
structure that can play more nicely with Clojure's functions.
For debugging or visualising a ugen tree."
[scug]
(if (map? scug)
(assoc
(into {} scug) :args (map mappify-ugen (:args scug)))
scug))
(defn simplify-ugen
"Turns SCUgen-tree into a simple map of maps and removes all specs.
For debugging or visualising a ugen tree."
[scug]
(if (map? scug)
(assoc
(dissoc (into {} scug) :spec :arg-map :orig-args) :args (map simplify-ugen (:args scug)))
scug))
|
[
{
"context": ":find [e]\n :where [[e :name \"Ivan\"]]}\n :multiple-clauses '{:find [e]\n ",
"end": 430,
"score": 0.9997282028198242,
"start": 426,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :where [[e :name \"Ivan\"]\n [e :l",
"end": 535,
"score": 0.9997375011444092,
"start": 531,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [e :last-name \"Ivanov\"]]}\n :join '{:find [e2]\n ",
"end": 601,
"score": 0.9997667670249939,
"start": 595,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "[e2]\n :where [[e :last-name \"Ivanov\"]\n [e :last-name nam",
"end": 690,
"score": 0.9997546076774597,
"start": 684,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "]]\n :args [{:name \"davros\"}]}})\n\n(defmacro duration\n \"Times the execution ",
"end": 1072,
"score": 0.9996075630187988,
"start": 1066,
"tag": "NAME",
"value": "davros"
},
{
"context": "id\n :name \"davros\")]\n :n 10000\n :samples 10000\n ",
"end": 4542,
"score": 0.9613326787948608,
"start": 4536,
"tag": "NAME",
"value": "davros"
},
{
"context": "id\n :name \"davros\")]\n :n 10000\n :samples 10000\n ",
"end": 4807,
"score": 0.9734687209129333,
"start": 4801,
"tag": "NAME",
"value": "davros"
}
] |
crux-test/test/crux/bench_test.clj
|
msladecek/crux
| 0 |
(ns crux.bench-test
(:require [criterium.core :as crit]
[crux.api :as api]
[crux.db :as db]
[crux.fixtures :refer [*api*] :as fix]
[crux.fixtures.kv :as fkv]
[clojure.spec.alpha :as s]
[clojure.test :as t]
[clojure.tools.logging :as log])
(:import java.util.Date))
(def queries {:name '{:find [e]
:where [[e :name "Ivan"]]}
:multiple-clauses '{:find [e]
:where [[e :name "Ivan"]
[e :last-name "Ivanov"]]}
:join '{:find [e2]
:where [[e :last-name "Ivanov"]
[e :last-name name1]
[e2 :last-name name1]]}
:range '{:find [e]
:where [[e :age age]
[(> age 20)]]}
:hardcoded-name '{:find [e]
:where [[e :name name]]
:args [{:name "davros"}]}})
(defmacro duration
"Times the execution of a function,
discarding the output and returning the elapsed time in seconds"
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(double (/ (- (System/nanoTime) start#) 1e9)))))
(defmacro duration-millis
"Times the execution of a function,
discarding the output and returning the elapsed time in milliseconds"
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(double (/ (- (System/nanoTime) start#) 1e6)))))
(defn- insert-docs [ts docs]
(api/submit-tx *api* (fix/maps->tx-ops docs ts)))
(defn- insert-data [n batch-size ts]
(doseq [[i people] (map-indexed vector (partition-all batch-size (take n (repeatedly fix/random-person))))]
(insert-docs ts people)))
(defn- perform-query [ts query]
(let [q (query queries)
q-fn (fn []
(let [db (api/db *api* ts)]
(if (= query :id)
(api/entity db :hardcoded-id)
(api/q db q))))]
;; Assert this query is in good working order first:
(assert (pos? (count (q-fn))))
(q-fn)))
(defn- do-benchmark [ts samples speed verbose query]
(when verbose
(print (str query "... ")) (flush)
(print (str (perform-query ts query) "... ")) (flush))
(let [result
(-> (case speed
:normal
(-> (crit/benchmark
(perform-query ts query) {:samples samples})
:mean
first)
:quick ;; faster but "less rigorous"
(-> (crit/quick-benchmark
(perform-query ts query) {:samples samples})
:mean
first)
:instant ;; even faster, even less rigorous
(as-> (map (fn [_] (duration (perform-query ts query)))
(range samples)) x
(apply + x)
(/ x samples)))
(* 1000))] ;; secs -> msecs
(when verbose (println result))
result))
(defn bench
[& {:keys [n batch-size ts query samples kv speed verbose preload]
:or {n 1000
batch-size 10
samples 100 ;; should always be >2
query :name
ts (Date.)
kv :rocks
speed :instant
verbose false}}]
((case kv
:rocks fkv/with-rocksdb
:lmdb fkv/with-lmdb
:mem fkv/with-memdb)
(fn []
(fix/with-kv-dir
(fn []
(fix/with-standalone-topology
(fn []
(fix/with-node
(fn []
(when verbose (print ":insert... ") (flush))
(when preload
(insert-docs ts preload))
(let [insert-time (duration (insert-data n batch-size ts))
queries-to-bench (if (= query :all)
(keys queries)
(flatten [query]))]
(when verbose (println insert-time))
(merge {:insert insert-time}
(zipmap
queries-to-bench
(map (partial do-benchmark ts samples speed verbose)
queries-to-bench)))))))))))))
(comment
(bench)
(bench :verbose true :preload [(assoc (fix/random-person)
:crux.db/id :hardcoded-id
:name "davros")]
:n 10000
:samples 10000
:query :hardcoded-name) ;;2.5
(bench :verbose true :preload [(assoc (fix/random-person)
:crux.db/id :hardcoded-id
:name "davros")]
:n 10000
:samples 10000
:query :id) ;;2.3
)
(defn acceptable-duration ;; for one query, in msec
[query]
(case query
:insert 500
:range 200
100)) ;; default
(log/warn "Not running crux.bench-test, it's failing intermittently on Circle")
#_(t/deftest test-query-speed
(let [benchmark (bench
:sample 3
:query [:name :multiple-clauses :range] ;; excluding :join until it's fixed
:speed :instant)]
(run! (fn [query]
(t/testing (str query " is reasonably fast")
(t/is
(< (query benchmark)
(acceptable-duration query)))))
(keys benchmark))))
|
1886
|
(ns crux.bench-test
(:require [criterium.core :as crit]
[crux.api :as api]
[crux.db :as db]
[crux.fixtures :refer [*api*] :as fix]
[crux.fixtures.kv :as fkv]
[clojure.spec.alpha :as s]
[clojure.test :as t]
[clojure.tools.logging :as log])
(:import java.util.Date))
(def queries {:name '{:find [e]
:where [[e :name "<NAME>"]]}
:multiple-clauses '{:find [e]
:where [[e :name "<NAME>"]
[e :last-name "<NAME>"]]}
:join '{:find [e2]
:where [[e :last-name "<NAME>"]
[e :last-name name1]
[e2 :last-name name1]]}
:range '{:find [e]
:where [[e :age age]
[(> age 20)]]}
:hardcoded-name '{:find [e]
:where [[e :name name]]
:args [{:name "<NAME>"}]}})
(defmacro duration
"Times the execution of a function,
discarding the output and returning the elapsed time in seconds"
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(double (/ (- (System/nanoTime) start#) 1e9)))))
(defmacro duration-millis
"Times the execution of a function,
discarding the output and returning the elapsed time in milliseconds"
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(double (/ (- (System/nanoTime) start#) 1e6)))))
(defn- insert-docs [ts docs]
(api/submit-tx *api* (fix/maps->tx-ops docs ts)))
(defn- insert-data [n batch-size ts]
(doseq [[i people] (map-indexed vector (partition-all batch-size (take n (repeatedly fix/random-person))))]
(insert-docs ts people)))
(defn- perform-query [ts query]
(let [q (query queries)
q-fn (fn []
(let [db (api/db *api* ts)]
(if (= query :id)
(api/entity db :hardcoded-id)
(api/q db q))))]
;; Assert this query is in good working order first:
(assert (pos? (count (q-fn))))
(q-fn)))
(defn- do-benchmark [ts samples speed verbose query]
(when verbose
(print (str query "... ")) (flush)
(print (str (perform-query ts query) "... ")) (flush))
(let [result
(-> (case speed
:normal
(-> (crit/benchmark
(perform-query ts query) {:samples samples})
:mean
first)
:quick ;; faster but "less rigorous"
(-> (crit/quick-benchmark
(perform-query ts query) {:samples samples})
:mean
first)
:instant ;; even faster, even less rigorous
(as-> (map (fn [_] (duration (perform-query ts query)))
(range samples)) x
(apply + x)
(/ x samples)))
(* 1000))] ;; secs -> msecs
(when verbose (println result))
result))
(defn bench
[& {:keys [n batch-size ts query samples kv speed verbose preload]
:or {n 1000
batch-size 10
samples 100 ;; should always be >2
query :name
ts (Date.)
kv :rocks
speed :instant
verbose false}}]
((case kv
:rocks fkv/with-rocksdb
:lmdb fkv/with-lmdb
:mem fkv/with-memdb)
(fn []
(fix/with-kv-dir
(fn []
(fix/with-standalone-topology
(fn []
(fix/with-node
(fn []
(when verbose (print ":insert... ") (flush))
(when preload
(insert-docs ts preload))
(let [insert-time (duration (insert-data n batch-size ts))
queries-to-bench (if (= query :all)
(keys queries)
(flatten [query]))]
(when verbose (println insert-time))
(merge {:insert insert-time}
(zipmap
queries-to-bench
(map (partial do-benchmark ts samples speed verbose)
queries-to-bench)))))))))))))
(comment
(bench)
(bench :verbose true :preload [(assoc (fix/random-person)
:crux.db/id :hardcoded-id
:name "<NAME>")]
:n 10000
:samples 10000
:query :hardcoded-name) ;;2.5
(bench :verbose true :preload [(assoc (fix/random-person)
:crux.db/id :hardcoded-id
:name "<NAME>")]
:n 10000
:samples 10000
:query :id) ;;2.3
)
(defn acceptable-duration ;; for one query, in msec
[query]
(case query
:insert 500
:range 200
100)) ;; default
(log/warn "Not running crux.bench-test, it's failing intermittently on Circle")
#_(t/deftest test-query-speed
(let [benchmark (bench
:sample 3
:query [:name :multiple-clauses :range] ;; excluding :join until it's fixed
:speed :instant)]
(run! (fn [query]
(t/testing (str query " is reasonably fast")
(t/is
(< (query benchmark)
(acceptable-duration query)))))
(keys benchmark))))
| true |
(ns crux.bench-test
(:require [criterium.core :as crit]
[crux.api :as api]
[crux.db :as db]
[crux.fixtures :refer [*api*] :as fix]
[crux.fixtures.kv :as fkv]
[clojure.spec.alpha :as s]
[clojure.test :as t]
[clojure.tools.logging :as log])
(:import java.util.Date))
(def queries {:name '{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]}
:multiple-clauses '{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]
[e :last-name "PI:NAME:<NAME>END_PI"]]}
:join '{:find [e2]
:where [[e :last-name "PI:NAME:<NAME>END_PI"]
[e :last-name name1]
[e2 :last-name name1]]}
:range '{:find [e]
:where [[e :age age]
[(> age 20)]]}
:hardcoded-name '{:find [e]
:where [[e :name name]]
:args [{:name "PI:NAME:<NAME>END_PI"}]}})
(defmacro duration
"Times the execution of a function,
discarding the output and returning the elapsed time in seconds"
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(double (/ (- (System/nanoTime) start#) 1e9)))))
(defmacro duration-millis
"Times the execution of a function,
discarding the output and returning the elapsed time in milliseconds"
([& forms]
`(let [start# (System/nanoTime)]
~@forms
(double (/ (- (System/nanoTime) start#) 1e6)))))
(defn- insert-docs [ts docs]
(api/submit-tx *api* (fix/maps->tx-ops docs ts)))
(defn- insert-data [n batch-size ts]
(doseq [[i people] (map-indexed vector (partition-all batch-size (take n (repeatedly fix/random-person))))]
(insert-docs ts people)))
(defn- perform-query [ts query]
(let [q (query queries)
q-fn (fn []
(let [db (api/db *api* ts)]
(if (= query :id)
(api/entity db :hardcoded-id)
(api/q db q))))]
;; Assert this query is in good working order first:
(assert (pos? (count (q-fn))))
(q-fn)))
(defn- do-benchmark [ts samples speed verbose query]
(when verbose
(print (str query "... ")) (flush)
(print (str (perform-query ts query) "... ")) (flush))
(let [result
(-> (case speed
:normal
(-> (crit/benchmark
(perform-query ts query) {:samples samples})
:mean
first)
:quick ;; faster but "less rigorous"
(-> (crit/quick-benchmark
(perform-query ts query) {:samples samples})
:mean
first)
:instant ;; even faster, even less rigorous
(as-> (map (fn [_] (duration (perform-query ts query)))
(range samples)) x
(apply + x)
(/ x samples)))
(* 1000))] ;; secs -> msecs
(when verbose (println result))
result))
(defn bench
[& {:keys [n batch-size ts query samples kv speed verbose preload]
:or {n 1000
batch-size 10
samples 100 ;; should always be >2
query :name
ts (Date.)
kv :rocks
speed :instant
verbose false}}]
((case kv
:rocks fkv/with-rocksdb
:lmdb fkv/with-lmdb
:mem fkv/with-memdb)
(fn []
(fix/with-kv-dir
(fn []
(fix/with-standalone-topology
(fn []
(fix/with-node
(fn []
(when verbose (print ":insert... ") (flush))
(when preload
(insert-docs ts preload))
(let [insert-time (duration (insert-data n batch-size ts))
queries-to-bench (if (= query :all)
(keys queries)
(flatten [query]))]
(when verbose (println insert-time))
(merge {:insert insert-time}
(zipmap
queries-to-bench
(map (partial do-benchmark ts samples speed verbose)
queries-to-bench)))))))))))))
(comment
(bench)
(bench :verbose true :preload [(assoc (fix/random-person)
:crux.db/id :hardcoded-id
:name "PI:NAME:<NAME>END_PI")]
:n 10000
:samples 10000
:query :hardcoded-name) ;;2.5
(bench :verbose true :preload [(assoc (fix/random-person)
:crux.db/id :hardcoded-id
:name "PI:NAME:<NAME>END_PI")]
:n 10000
:samples 10000
:query :id) ;;2.3
)
(defn acceptable-duration ;; for one query, in msec
[query]
(case query
:insert 500
:range 200
100)) ;; default
(log/warn "Not running crux.bench-test, it's failing intermittently on Circle")
#_(t/deftest test-query-speed
(let [benchmark (bench
:sample 3
:query [:name :multiple-clauses :range] ;; excluding :join until it's fixed
:speed :instant)]
(run! (fn [query]
(t/testing (str query " is reasonably fast")
(t/is
(< (query benchmark)
(acceptable-duration query)))))
(keys benchmark))))
|
[
{
"context": ", backed by cassandra\"\n :url \"https://github.com/pyr/cyanite\"\n :license {:name \"MIT License\"\n ",
"end": 150,
"score": 0.9995841979980469,
"start": 147,
"tag": "USERNAME",
"value": "pyr"
},
{
"context": "MIT License\"\n :url \"https://github.com/pyr/cyanite/tree/master/LICENSE\"}\n :maintainer {:ema",
"end": 232,
"score": 0.9995913505554199,
"start": 229,
"tag": "USERNAME",
"value": "pyr"
},
{
"context": "nite/tree/master/LICENSE\"}\n :maintainer {:email \"[email protected]\"}\n :main org.spootnik.cyanite\n :dependencies [[",
"end": 302,
"score": 0.9999302625656128,
"start": 286,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
project.clj
|
feangulo/cyanite
| 1 |
(defproject org.spootnik/cyanite "0.1.0"
:description "Alternative storage backend for graphite, backed by cassandra"
:url "https://github.com/pyr/cyanite"
:license {:name "MIT License"
:url "https://github.com/pyr/cyanite/tree/master/LICENSE"}
:maintainer {:email "[email protected]"}
:main org.spootnik.cyanite
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/tools.logging "0.2.6"]
[org.clojure/tools.cli "0.2.4"]
[commons-logging/commons-logging "1.1.3"]
[ring/ring-codec "1.0.0"]
[aleph "0.3.0"]
[clj-yaml "0.4.0"]
[cc.qbits/alia "2.0.0-beta10"]
[net.jpountz.lz4/lz4 "1.2.0"]
[org.xerial.snappy/snappy-java "1.0.5"]
[clucy "0.4.0"]
[org.slf4j/slf4j-log4j12 "1.6.4"]
[log4j/apache-log4j-extras "1.0"]
[log4j/log4j "1.2.16"
:exclusions [javax.mail/mail
javax.jms/jms
com.sun.jdkmk/jmxtools
com.sun.jmx/jmxri]]])
|
83236
|
(defproject org.spootnik/cyanite "0.1.0"
:description "Alternative storage backend for graphite, backed by cassandra"
:url "https://github.com/pyr/cyanite"
:license {:name "MIT License"
:url "https://github.com/pyr/cyanite/tree/master/LICENSE"}
:maintainer {:email "<EMAIL>"}
:main org.spootnik.cyanite
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/tools.logging "0.2.6"]
[org.clojure/tools.cli "0.2.4"]
[commons-logging/commons-logging "1.1.3"]
[ring/ring-codec "1.0.0"]
[aleph "0.3.0"]
[clj-yaml "0.4.0"]
[cc.qbits/alia "2.0.0-beta10"]
[net.jpountz.lz4/lz4 "1.2.0"]
[org.xerial.snappy/snappy-java "1.0.5"]
[clucy "0.4.0"]
[org.slf4j/slf4j-log4j12 "1.6.4"]
[log4j/apache-log4j-extras "1.0"]
[log4j/log4j "1.2.16"
:exclusions [javax.mail/mail
javax.jms/jms
com.sun.jdkmk/jmxtools
com.sun.jmx/jmxri]]])
| true |
(defproject org.spootnik/cyanite "0.1.0"
:description "Alternative storage backend for graphite, backed by cassandra"
:url "https://github.com/pyr/cyanite"
:license {:name "MIT License"
:url "https://github.com/pyr/cyanite/tree/master/LICENSE"}
:maintainer {:email "PI:EMAIL:<EMAIL>END_PI"}
:main org.spootnik.cyanite
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/tools.logging "0.2.6"]
[org.clojure/tools.cli "0.2.4"]
[commons-logging/commons-logging "1.1.3"]
[ring/ring-codec "1.0.0"]
[aleph "0.3.0"]
[clj-yaml "0.4.0"]
[cc.qbits/alia "2.0.0-beta10"]
[net.jpountz.lz4/lz4 "1.2.0"]
[org.xerial.snappy/snappy-java "1.0.5"]
[clucy "0.4.0"]
[org.slf4j/slf4j-log4j12 "1.6.4"]
[log4j/apache-log4j-extras "1.0"]
[log4j/log4j "1.2.16"
:exclusions [javax.mail/mail
javax.jms/jms
com.sun.jdkmk/jmxtools
com.sun.jmx/jmxri]]])
|
[
{
"context": "\"Library Card Renewal\"\n :name \"Harold Harnold\"\n :address {:city \"Hamilton\"\n",
"end": 765,
"score": 0.9998912811279297,
"start": 751,
"tag": "NAME",
"value": "Harold Harnold"
},
{
"context": "-First Century\"\n \"Thomas Piketty\"\n false\n ",
"end": 1072,
"score": 0.9992133975028992,
"start": 1058,
"tag": "NAME",
"value": "Thomas Piketty"
},
{
"context": " and Our Lives\"\n \"Joseph Heath\"\n false\n ",
"end": 1310,
"score": 0.8855805397033691,
"start": 1298,
"tag": "NAME",
"value": "Joseph Heath"
},
{
"context": "anadian Answer\"\n \"Donald J. Savoie\"\n false\n ",
"end": 1519,
"score": 0.9998730421066284,
"start": 1503,
"tag": "NAME",
"value": "Donald J. Savoie"
},
{
"context": "Little Schemer\"\n \"Daniel P. Friedman and Matthias Felleisen\"\n ",
"end": 1702,
"score": 0.9998897910118103,
"start": 1684,
"tag": "NAME",
"value": "Daniel P. Friedman"
},
{
"context": " \"Daniel P. Friedman and Matthias Felleisen\"\n true\n ",
"end": 1725,
"score": 0.9998911619186401,
"start": 1707,
"tag": "NAME",
"value": "Matthias Felleisen"
},
{
"context": "book \"Jampires\"\n \"David O'Connell and Sarah McIntyre\"\n ",
"end": 1897,
"score": 0.9998821020126343,
"start": 1882,
"tag": "NAME",
"value": "David O'Connell"
},
{
"context": " \"David O'Connell and Sarah McIntyre\"\n false\n ",
"end": 1916,
"score": 0.9998948574066162,
"start": 1902,
"tag": "NAME",
"value": "Sarah McIntyre"
}
] |
src/rulescript/laboratory.clj
|
rgscherf/rulescript
| 1 |
(ns rulescript.laboratory
(:require [clojure.java.io :as jio]
[clojure.edn :as edn]
[rulescript.lang.operations :refer :all]
[rulescript.lang.invocations :refer :all]
[rulescript.io.main :refer :all]
[cheshire.core :as cheshire]))
(comment
(eval-from-strings
"(validate-document (inp) (rule i-fail (< 2 (in inp find fail))) (rule is-hello (= 1 (in inp find age))) (rule age-over-ten (> 10 (in inp find age))))"
"{\"age\":12}"
:pprint true)
(defn book
[title author overdue fines]
{:title title
:author author
:overdue overdue
:fines fines})
(def library-application
{:type-of-application "Library Card Renewal"
:name "Harold Harnold"
:address {:city "Hamilton"
:province "Ontario"}
:current-member true
:times-renewed 1
:old-fines 2.40
:checkouts [(book "Capital in the Twenty-First Century"
"Thomas Piketty"
false
0)
(book "Enlightenment 2.0: Restoring Sanity to Our Politics, Our Economy, and Our Lives"
"Joseph Heath"
false
0)
(book "What Is Government Good At?: A Canadian Answer"
"Donald J. Savoie"
false
0)
(book "The Little Schemer"
"Daniel P. Friedman and Matthias Felleisen"
true
0.90)
(book "Jampires"
"David O'Connell and Sarah McIntyre"
false
0)]})
(def application
(-> "drao.json"
jio/resource
slurp
(cheshire/parse-string keyword)))
(def spec
(-> "drao.edn"
jio/resource
slurp
edn/read-string))
((eval spec) application))
|
58710
|
(ns rulescript.laboratory
(:require [clojure.java.io :as jio]
[clojure.edn :as edn]
[rulescript.lang.operations :refer :all]
[rulescript.lang.invocations :refer :all]
[rulescript.io.main :refer :all]
[cheshire.core :as cheshire]))
(comment
(eval-from-strings
"(validate-document (inp) (rule i-fail (< 2 (in inp find fail))) (rule is-hello (= 1 (in inp find age))) (rule age-over-ten (> 10 (in inp find age))))"
"{\"age\":12}"
:pprint true)
(defn book
[title author overdue fines]
{:title title
:author author
:overdue overdue
:fines fines})
(def library-application
{:type-of-application "Library Card Renewal"
:name "<NAME>"
:address {:city "Hamilton"
:province "Ontario"}
:current-member true
:times-renewed 1
:old-fines 2.40
:checkouts [(book "Capital in the Twenty-First Century"
"<NAME>"
false
0)
(book "Enlightenment 2.0: Restoring Sanity to Our Politics, Our Economy, and Our Lives"
"<NAME>"
false
0)
(book "What Is Government Good At?: A Canadian Answer"
"<NAME>"
false
0)
(book "The Little Schemer"
"<NAME> and <NAME>"
true
0.90)
(book "Jampires"
"<NAME> and <NAME>"
false
0)]})
(def application
(-> "drao.json"
jio/resource
slurp
(cheshire/parse-string keyword)))
(def spec
(-> "drao.edn"
jio/resource
slurp
edn/read-string))
((eval spec) application))
| true |
(ns rulescript.laboratory
(:require [clojure.java.io :as jio]
[clojure.edn :as edn]
[rulescript.lang.operations :refer :all]
[rulescript.lang.invocations :refer :all]
[rulescript.io.main :refer :all]
[cheshire.core :as cheshire]))
(comment
(eval-from-strings
"(validate-document (inp) (rule i-fail (< 2 (in inp find fail))) (rule is-hello (= 1 (in inp find age))) (rule age-over-ten (> 10 (in inp find age))))"
"{\"age\":12}"
:pprint true)
(defn book
[title author overdue fines]
{:title title
:author author
:overdue overdue
:fines fines})
(def library-application
{:type-of-application "Library Card Renewal"
:name "PI:NAME:<NAME>END_PI"
:address {:city "Hamilton"
:province "Ontario"}
:current-member true
:times-renewed 1
:old-fines 2.40
:checkouts [(book "Capital in the Twenty-First Century"
"PI:NAME:<NAME>END_PI"
false
0)
(book "Enlightenment 2.0: Restoring Sanity to Our Politics, Our Economy, and Our Lives"
"PI:NAME:<NAME>END_PI"
false
0)
(book "What Is Government Good At?: A Canadian Answer"
"PI:NAME:<NAME>END_PI"
false
0)
(book "The Little Schemer"
"PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"
true
0.90)
(book "Jampires"
"PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"
false
0)]})
(def application
(-> "drao.json"
jio/resource
slurp
(cheshire/parse-string keyword)))
(def spec
(-> "drao.edn"
jio/resource
slurp
edn/read-string))
((eval spec) application))
|
[
{
"context": ";; The MIT License\n;;\n;; Copyright (c) 2010 Erik Soehnel\n;;\n;; Permission is hereby granted, free of charg",
"end": 56,
"score": 0.9998571276664734,
"start": 44,
"tag": "NAME",
"value": "Erik Soehnel"
},
{
"context": " \"//localhost\"\n ;; ;;:username user\n ;; :user user\n ;; ",
"end": 51269,
"score": 0.8539474010467529,
"start": 51265,
"tag": "USERNAME",
"value": "user"
},
{
"context": " ;;:username user\n ;; :user user\n ;; :password pwd})\n c",
"end": 51304,
"score": 0.5838353037834167,
"start": 51300,
"tag": "USERNAME",
"value": "user"
},
{
"context": " :user user\n ;; :password pwd})\n conn (Connection. state)]\n (dosync (",
"end": 51342,
"score": 0.9988271594047546,
"start": 51339,
"tag": "PASSWORD",
"value": "pwd"
}
] |
data/clojure/2822bbba1dc1eb35723defae5d85b1b3_jdbc.clj
|
maxim5/code-inspector
| 5 |
;; The MIT License
;;
;; Copyright (c) 2010 Erik Soehnel
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
;; provide a basic jdbc-interface for the cdc-system
(ns cdc.jdbc
(:use [clojure.pprint :only [pprint]])
(:require [cdc.mysql-binlog :as binlog]
;;[clojure.contrib.sql.internal :as sql]
)
(:import (java.sql DriverManager
DriverPropertyInfo)
(java.util Properties)
java.util.concurrent.LinkedBlockingQueue))
;; do not import the classes we are implementing
(def jdbc-state (ref {:connection nil
:statement nil
:resultset nil
:binlog-state nil
:queue nil}))
(defn set-new-queue
"set a new queue"
[]
(let [queue (LinkedBlockingQueue. 10)
event-fn #(do (println "event-fn: got" (count %) "events!")
(.put #^LinkedBlockingQueue queue %))]
(dosync (alter jdbc-state assoc :queue queue)
(send (:binlog-state @jdbc-state) assoc :event-fn event-fn))))
(defn throwf-sql-not-supported [& args]
(throw (java.sql.SQLFeatureNotSupportedException. (apply format (or args [""])))))
(defn throwf-unsupported [& args]
(throw (UnsupportedOperationException. (apply format (or args [""])))))
(defn throwf-illegal [& args]
(throw (IllegalArgumentException. (apply format (or args [""])))))
(defn throwf [& [format-string & args]]
(throw (Exception. (apply format (str "cdc.jdbc: " format-string) args))))
(defn driver-property-info [& {n :name,
v :value,
d :description,
c :choices,
r? :required}]
(let [info (DriverPropertyInfo. (str n) (str v))]
(set! (.choices info) (into-array String (map str c)))
(set! (.description info) (str d))
(set! (.required info) (boolean r?))
info))
;;(def _ee (binlog/read-binlog "/var/log/mysql/binlog.001024"))
(deftype ResultSetMetaData [schema table row]
java.sql.ResultSetMetaData
(getCatalogName [t c] "") ;; Gets the designated column's table's catalog name.
(getColumnClassName [t c] (type (nth row (dec c)))) ;;Returns the fully-qualified name of the Java class whose instances are manufactured if the method ResultSet.getObject is called to retrieve a value from the column.
(getColumnCount [t] (count row)) ;; int; Returns the number of columns in this ResultSet object.
(getColumnDisplaySize [t c] 1024) ;; int; Indicates the designated column's normal maximum width in characters.
(getColumnLabel [t c] (str c)) ;; String; Gets the designated column's suggested title for use in printouts and displays.
(getColumnName [t c] (str c)) ;; String; Get the designated column's name.
(getColumnType [t c] ;; int; Retrieves the designated column's SQL type.
(let [v (nth row (dec c))]
(cond (decimal? v) java.sql.Types/DECIMAL
(integer? v) java.sql.Types/INTEGER
(string? v) java.sql.Types/VARCHAR
:else (throwf "unsupported type: %s" (type v)))))
(getColumnTypeName [t c] (str (.getColumnType t c))) ;; String; Retrieves the designated column's database-specific type name.
(getPrecision [t c] 10) ;; int; Get the designated column's specified column size.
(getScale [t c] 10) ;; int; Gets the designated column's number of digits to right of the decimal point.
(getSchemaName [t c] schema) ;; String; Get the designated column's table's schema.
(getTableName [t c] table) ;; String; Gets the designated column's table name.
(isAutoIncrement [t c] false) ;; boolean; Indicates whether the designated column is automatically numbered.
(isCaseSensitive [t c] true) ;; boolean; Indicates whether a column's case matters.
(isCurrency [t c] false) ;; boolean; Indicates whether the designated column is a cash value.
(isDefinitelyWritable [t c] false) ;; boolean; Indicates whether a write on the designated column will definitely succeed.
(isNullable [t c] java.sql.ResultSetMetaData/columnNullableUnknown) ;; int; Indicates the nullability of values in the designated column.
(isReadOnly [t c] true) ;; boolean; Indicates whether the designated column is definitely not writable.
(isSearchable [t c] false) ;; boolean; Indicates whether the designated column can be used in a where clause.
(isSigned [t c] true) ;; boolean; Indicates whether values in the designated column are signed numbers.
(isWritable [t c] false)) ;; boolean; Indicates whether it is possible for a write on the designated column to succeed.
(defn rows-delta-type
"Return a fn that, given an event returns a seq of rows according to
the quantifier."
[{r :rows, t :type, tbl :table}]
(mapcat (condp = t
'WRITE_ROWS_EVENT #(list (conj % "insert"))
'DELETE_ROWS_EVENT #(list (conj % "delete"))
'UPDATE_ROWS_EVENT #(list (conj (first %) "update-before")
(conj (second %) "update"))
;; ignore non-data events
nil)
r))
(def _example-statement "select * from \"foo\".\"auto\" where _delta_type = ' insert'")
(defn tokenize-statement [s]
(loop [[t & more :as s] (.split s " ")
ast []]
(cond (empty? s) ast
(or (= t "\"") (= t "'"))
(recur (drop-while #(not= % t) more)
(->> more
(take-while #(not= % t))
(map #(if (= "" %) " " %))
(apply str t)
(conj ast)))
(= t "")
(recur more ast)
:else
(recur more (conj ast t)))))
(defn parse-statement [s]
(loop [[t & more :as s] (tokenize-statement s)
ast {:select nil :from nil :where nil}]
(cond (empty? s) ast
(#{"select"} t)
(recur (next more) (assoc ast :select (first more)))
(#{"from"} t)
(recur (drop-while #(not= % "where") more)
(assoc ast :from (apply str (take-while #(not= % "where") more))))
(= t "where")
(assoc ast :where (next s))
:else
(throwf-illegal "unknown statement: %s" t))))
;;(parse-statement _example-statement)
(defn really-lazy-concat
"circumvent a bug in mapcat which prevents full lazyness."
([r]
(lazy-seq (really-lazy-concat (first r) (rest r))))
([s r]
(lazy-seq
(if (empty? s)
(if (empty? r)
nil
(really-lazy-concat r))
(cons (first s)
(really-lazy-concat (rest s) r))))))
(defn create-resultset-seq
"given a simple sql expression and queue, return lazy seq of vectors
from queue."
[sql queue]
(let [{table :from [_ _ dtype] :where} (parse-statement sql)
dtype (when dtype (.replace dtype "'" ""))
[table-name schema-name] (-> table ;; for now, don't allow dots in table names
(.replace "\"" "")
(.split "\\.")
reverse)
s (->> (repeatedly #(.take queue))
(really-lazy-concat)
(filter #(and (= (:table-name %) table-name)
(= (:db-name %) schema-name)))
(map rows-delta-type)
(really-lazy-concat)
(filter (if dtype
#(= (last %) dtype)
identity))
;; in jdbc, one must call .next on the resultset to get the first row
(cons nil))]
s))
(defmacro getcol []
`(if-let [v# (nth (first ~'rows) (dec ~'i))]
(do (set! ~'was-null? false)
v#)
(do (set! ~'was-null? true)
nil)))
(defmacro getcol-by-name []
`(if-let [v# (nth (first ~'rows) (.findColumn ~'t ~'c))]
(do (set! ~'was-null? false)
v#)
(do (set! ~'was-null? true)
nil)))
;; generic resultset implementation
;; please, single threaded access only!
;; mind the gap, nothing coordinated
;; jdbc column numbering is 1<=colNum<=colCount!!!
(deftype ResultSet [#^{:volatile-mutable true} rows ;; a set of vectors of columnvalues, starting with a nil
#^{:volatile-mutable true} was-null?
sql]
java.sql.ResultSet
;; essential methods
(close [t] (dosync (set-new-queue)
(alter jdbc-state assoc :resultset nil)))
(isClosed [t])
(next [t]
;; moves cursor one row forward if there is a row
(if-let [r (next rows)]
(do (set! rows r)
true)
false))
(wasNull [t] (boolean was-null?)) ;; whether the last access to any col was sql-null
(getMetaData [t]
;; generate resultset metadata using the first row
(ResultSetMetaData. "" "" (second rows))) ;; ResultSetMetaData
(findColumn [t label]
;; returns the colnumber from the colname,
;; colnames are currently only printed numbers: "1", "2" ...
(Integer/valueOf label))
;; data getters
(^String getString [t ^int i] (getcol))
(^String getString [t ^String c] (getcol-by-name))
(^boolean getBoolean [t ^int i])
(^boolean getBoolean [t ^String c])
(^byte getByte [t ^int i] (getcol))
(^byte getByte [t ^String c] (getcol-by-name))
(^short getShort [t ^int i] (getcol))
(^short getShort [t ^String c] (getcol-by-name))
(^int getInt [t ^int i] (getcol))
(^int getInt [t ^String c] (getcol-by-name))
(^long getLong [t ^int i] (getcol))
(^long getLong [t ^String c] (getcol-by-name))
(^float getFloat [t ^int i] (getcol))
(^float getFloat [t ^String c] (getcol-by-name))
(^double getDouble [t ^int i] (getcol))
(^double getDouble [t ^String c] (getcol-by-name))
(^BigDecimal getBigDecimal [t ^int i] (java.math.BigDecimal. (str (getcol))))
(^BigDecimal getBigDecimal [t ^String c] (java.math.BigDecimal. (str (getcol-by-name))))
(^BigDecimal getBigDecimal [t ^int i ^int scale] (.getBigDecimal t i))
(^BigDecimal getBigDecimal [t ^String c ^int scale] (.getBigDecimal t c))
(^bytes getBytes [t ^int i])
(^bytes getBytes [t ^String c])
(^java.sql.Date getDate [t ^int i])
(^java.sql.Date getDate [t ^String c])
(^java.sql.Date getDate [t ^int i ^java.util.Calendar cal])
(^java.sql.Date getDate [t ^String c ^java.util.Calendar cal])
(^java.sql.Time getTime [t ^int i])
(^java.sql.Time getTime [t ^String c])
(^java.sql.Time getTime [t ^int i ^java.util.Calendar cal])
(^java.sql.Time getTime [t ^String c ^java.util.Calendar cal])
(^java.sql.Timestamp getTimestamp [t ^int i])
(^java.sql.Timestamp getTimestamp [t ^String c])
(^java.sql.Timestamp getTimestamp [t ^int i ^java.util.Calendar cal])
(^java.sql.Timestamp getTimestamp [t ^String c ^java.util.Calendar cal])
(^java.io.InputStream getAsciiStream [t ^int i])
(^java.io.InputStream getAsciiStream [t ^String c])
(^java.io.InputStream getUnicodeStream [t ^int i])
(^java.io.InputStream getUnicodeStream [t ^String c])
(^java.io.InputStream getBinaryStream [t ^int i])
(^java.io.InputStream getBinaryStream [t ^String c])
(getObject [t ^int i] (getcol))
(getObject [t ^String c] (getcol-by-name))
(getObject [t ^int i ^java.util.Map m]) ;; get object with mapping
(getObject [t ^String c ^java.util.Map m])
(^java.io.Reader getCharacterStream [t ^int i])
(^java.io.Reader getCharacterStream [t ^String c])
(^java.sql.Ref getRef [t ^int i])
(^java.sql.Ref getRef [t ^String c])
(^java.sql.Blob getBlob [t ^int i])
(^java.sql.Blob getBlob [t ^String c])
(^java.sql.Clob getClob [t ^int i])
(^java.sql.Clob getClob [t ^String c])
(^java.sql.Array getArray [t ^int i])
(^java.sql.Array getArray [t ^String c])
(^java.net.URL getURL [t ^int i])
(^java.net.URL getURL [t ^String c])
(^java.sql.NClob getNClob [t ^int i])
(^java.sql.NClob getNClob [t ^String c])
(^java.sql.SQLXML getSQLXML [t ^int i])
(^java.sql.SQLXML getSQLXML [t ^String c])
(^String getNString [t ^int i])
(^String getNString [t ^String c])
(^java.io.Reader getNCharacterStream [t ^int i])
(^java.io.Reader getNCharacterStream [t ^String c])
;; unsupported cursor methods
(getCursorName [t] (throwf-sql-not-supported))
(absolute [t r] (throwf-sql-not-supported))
(afterLast [t] (throwf-sql-not-supported))
(beforeFirst [t] (throwf-sql-not-supported))
(relative [t r] (throwf-sql-not-supported))
(isBeforeFirst [t] (throwf-sql-not-supported))
(isAfterLast [t] (throwf-sql-not-supported))
(isFirst [t] (throwf-sql-not-supported))
(isLast [t] (throwf-sql-not-supported))
(first [t] (throwf-sql-not-supported))
(last [t] (throwf-sql-not-supported))
(previous [t] (throwf-sql-not-supported))
(setFetchDirection [t dir] (throwf-sql-not-supported))
(getFetchDirection [t] 0)
(moveToInsertRow [t] (throwf-sql-not-supported))
(moveToCurrentRow [t] (throwf-sql-not-supported))
;; misc
(setFetchSize [t s])
(getFetchSize [t] 0)
(getType [t] java.sql.ResultSet/TYPE_FORWARD_ONLY)
(getConcurrency [t] java.sql.ResultSet/CONCUR_READ_ONLY)
(getRow [t] (throwf-sql-not-supported))
(getWarnings [t] )
(clearWarnings [t])
(^java.sql.RowId getRowId [t ^int i] (throwf-sql-not-supported))
(^java.sql.RowId getRowId [t ^String c] (throwf-sql-not-supported))
(getHoldability [t] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT)
;; update functions
(rowUpdated [t] (throwf-sql-not-supported))
(rowDeleted [t] (throwf-sql-not-supported))
(rowInserted [t] (throwf-sql-not-supported))
(updateRow [t] (throwf-sql-not-supported))
(deleteRow [t] (throwf-sql-not-supported))
(insertRow [t] (throwf-sql-not-supported))
(cancelRowUpdates [t] (throwf-sql-not-supported)))
(defn create-resultset [sql]
(ResultSet. (create-resultset-seq sql (:queue @jdbc-state)) false sql))
(defn create-resultset-from-seq
"Return a resultset implementation from the given seq of vectors.
a string may be supplied for debug purposes which is stored in the
resultset sql field."
[s & [sql-string]]
(ResultSet. (cons nil s) false sql-string))
(deftype Statement []
java.sql.Statement
;; essential methods
(close [t] (dosync (when-let [rs (:resultset @jdbc-state)] (.close rs))
(alter jdbc-state assoc :statement nil)))
(executeQuery [t sql]
(dosync (if-let [rs (:resultset @jdbc-state)]
(throwf "Close Resultset %s first." rs)
(let [rs (create-resultset sql)]
(alter jdbc-state assoc :resultset rs)
rs))))
(execute [t sql] (.executeQuery t sql) true)
;; we do not have autogenerated keys
(^boolean execute [t ^String sql ^int _] (.execute t sql))
(^boolean execute [t ^String sql ^ints _] (boolean (.execute t sql)))
(^boolean execute [t ^String sql ^"[Ljava.lang.String;" _] (boolean (.execute t sql)))
(getResultSet [t] (:resultset @jdbc-state))
;; misc, mostly unsupported or ignored
(addBatch [t s] (throwf-unsupported))
(executeBatch [t] (throwf-unsupported))
(cancel [t] (.close t))
(clearBatch [t] (throwf-unsupported))
(clearWarnings [t] (throwf-unsupported))
(executeUpdate [t sql] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^int _] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^ints _] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^"[Ljava.lang.String;" _] (throwf-unsupported))
(getConnection [t] (:connection @jdbc-state))
(getFetchDirection [t] java.sql.ResultSet/FETCH_UNKNOWN)
(getFetchSize [t] 1)
(getGeneratedKeys [t] (throwf-sql-not-supported))
(getMaxFieldSize [t] 0) ;; unlimited
(getMoreResults [t] false) ;; only ever one rs
(getMoreResults [t _] false)
(getQueryTimeout [t] 0) ;; no timeout
(getResultSetConcurrency [t] java.sql.ResultSet/CONCUR_READ_ONLY)
(getResultSetHoldability [t] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT)
(getResultSetType [t] java.sql.ResultSet/TYPE_FORWARD_ONLY)
(getUpdateCount [t] -1)
(getWarnings [t] nil)
(isClosed [t] false)
(isPoolable [t] false)
(setCursorName [t s] (throwf-sql-not-supported))
(setEscapeProcessing [t flag]) ;; ignore
(setFetchDirection [t dir]) ;; ignore
(setFetchSize [t n]) ;; ignore
(setMaxFieldSize [t s]) ;; ignore, may be useful to obey to for varchars
(setMaxRows [t s]) ;; ignore
(setPoolable [t flag]) ;; ignore
(setQueryTimeout [t seconds]))
(deftype ConnectionMetadata []
java.sql.DatabaseMetaData
(^boolean allProceduresAreCallable [_] false) ;; Retrieves whether the current user can call all the procedures returned by the method getProcedures.
(^boolean allTablesAreSelectable [_] false) ;; Retrieves whether the current user can use all the tables returned by the method getTables in a SELECT statement.
(^boolean autoCommitFailureClosesAllResultSets [_] false) ;; Retrieves whether a SQLException while autoCommit is true inidcates that all open ResultSets are closed, even ones that are holdable.
(^boolean dataDefinitionCausesTransactionCommit [_] false) ;; Retrieves whether a data definition statement within a transaction forces the transaction to commit.
(^boolean dataDefinitionIgnoredInTransactions [_] true) ;; Retrieves whether this database ignores a data definition statement within a transaction.
(^boolean deletesAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row delete can be detected by calling the method ResultSet.rowDeleted.
(^boolean doesMaxRowSizeIncludeBlobs [_] false) ;; Retrieves whether the return value for the method getMaxRowSize includes the SQL data types LONGVARCHAR and LONGVARBINARY.
(^java.sql.ResultSet getAttributes [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern, ^String attributeNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given attribute of the given type for a userdefined type (UDT) that is available in the given schema and catalog.
(^java.sql.ResultSet getBestRowIdentifier [_ ^String catalog, ^String schema, ^String table, ^int scope, ^boolean nullable] (create-resultset-from-seq [])) ;; Retrieves a description of a table's optimal set of columns that uniquely identifies a row.
(^java.sql.ResultSet getCatalogs [_] (create-resultset-from-seq [])) ;; Retrieves the catalog names available in this database.
(^String getCatalogSeparator [_] ".") ;; Retrieves the String that this database uses as the separator between a catalog and table name.
(^String getCatalogTerm [_] "") ;; Retrieves the database vendor's preferred term for "catalog".
(^java.sql.ResultSet getClientInfoProperties [_] (create-resultset-from-seq [])) ;; Retrieves a list of the client info properties that the driver supports.
(^java.sql.ResultSet getColumnPrivileges [_ ^String catalog, ^String schema, ^String table, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the access rights for a table's columns.
(^java.sql.ResultSet getColumns [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of table columns available in the specified catalog.
(^java.sql.Connection getConnection [_] (:connection @jdbc-state)) ;; Retrieves the connection that produced this metadata object.
(^java.sql.ResultSet getCrossReference [_ ^String parentCatalog, ^String parentSchema, ^String parentTable, ^String foreignCatalog, ^String foreignSchema, ^String foreignTable] (create-resultset-from-seq [])) ;; Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
(^int getDatabaseMajorVersion [_] -1) ;; Retrieves the major version number of the underlying database.
(^int getDatabaseMinorVersion [_] -1) ;; Retrieves the minor version number of the underlying database.
(^String getDatabaseProductName [_] "mysql") ;; Retrieves the name of this database product.
(^String getDatabaseProductVersion [_] "0.1") ;; Retrieves the version number of this database product.
(^int getDefaultTransactionIsolation [_] java.sql.Connection/TRANSACTION_NONE) ;; Retrieves this database's default transaction isolation level.
(^int getDriverMajorVersion [_] 0) ;; Retrieves this JDBC driver's major version number.
(^int getDriverMinorVersion [_] 1) ;; Retrieves this JDBC driver's minor version number.
(^String getDriverName [_] "mysql binlog cdc jdbc interface") ;; Retrieves the name of this JDBC driver.
(^String getDriverVersion [_] "0.1") ;; Retrieves the version number of this JDBC driver as a String.
(^java.sql.ResultSet getExportedKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
(^String getExtraNameCharacters [_] "") ;; Retrieves all the "extra" characters that can be used in unquoted identifier names (those beyond az, AZ, 09 and _).
(^java.sql.ResultSet getFunctionColumns [_ ^String catalog, ^String schemaPattern, ^String functionNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given catalog's system or user function parameters and return type.
(^java.sql.ResultSet getFunctions [_ ^String catalog, ^String schemaPattern, ^String functionNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the system and user functions available in the given catalog.
(^String getIdentifierQuoteString [_] "\"") ;; Retrieves the string used to quote SQL identifiers.
(^java.sql.ResultSet getImportedKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the primary key columns that are referenced by the given table's foreign key columns (the primary keys imported by a table).
(^java.sql.ResultSet getIndexInfo [_ ^String catalog, ^String schema, ^String table, ^boolean unique, ^boolean approximate] (create-resultset-from-seq [])) ;; Retrieves a description of the given table's indices and statistics.
(^int getJDBCMajorVersion [_] -1) ;; Retrieves the major JDBC version number for this driver.
(^int getJDBCMinorVersion [_] -1) ;; Retrieves the minor JDBC version number for this driver.
(^int getMaxBinaryLiteralLength [_] -1) ;; Retrieves the maximum number of hex characters this database allows in an inline binary literal.
(^int getMaxCatalogNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a catalog name.
(^int getMaxCharLiteralLength [_] -1) ;; Retrieves the maximum number of characters this database allows for a character literal.
(^int getMaxColumnNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows for a column name.
(^int getMaxColumnsInGroupBy [_] -1) ;; Retrieves the maximum number of columns this database allows in a GROUP BY clause.
(^int getMaxColumnsInIndex [_] -1) ;; Retrieves the maximum number of columns this database allows in an index.
(^int getMaxColumnsInOrderBy [_] -1) ;; Retrieves the maximum number of columns this database allows in an ORDER BY clause.
(^int getMaxColumnsInSelect [_] -1) ;; Retrieves the maximum number of columns this database allows in a SELECT list.
(^int getMaxColumnsInTable [_] -1) ;; Retrieves the maximum number of columns this database allows in a table.
(^int getMaxConnections [_] -1) ;; Retrieves the maximum number of concurrent connections to this database that are possible.
(^int getMaxCursorNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a cursor name.
(^int getMaxIndexLength [_] -1) ;; Retrieves the maximum number of bytes this database allows for an index, including all of the parts of the index.
(^int getMaxProcedureNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a procedure name.
(^int getMaxRowSize [_] -1) ;; Retrieves the maximum number of bytes this database allows in a single row.
(^int getMaxSchemaNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a schema name.
(^int getMaxStatementLength [_] -1) ;; Retrieves the maximum number of characters this database allows in an SQL statement.
(^int getMaxStatements [_] -1) ;; Retrieves the maximum number of active statements to this database that can be open at the same time.
(^int getMaxTableNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows in a table name.
(^int getMaxTablesInSelect [_] -1) ;; Retrieves the maximum number of tables this database allows in a SELECT statement.
(^int getMaxUserNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows in a user name.
(^String getNumericFunctions [_] "") ;; Retrieves a commaseparated list of math functions available with this database.
(^java.sql.ResultSet getPrimaryKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the given table's primary key columns.
(^java.sql.ResultSet getProcedureColumns [_ ^String catalog, ^String schemaPattern, ^String procedureNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given catalog's stored procedure parameter and result columns.
(^java.sql.ResultSet getProcedures [_ ^String catalog, ^String schemaPattern, ^String procedureNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the stored procedures available in the given catalog.
(^String getProcedureTerm [_] "procedure") ;; Retrieves the database vendor's preferred term for "procedure".
(^int getResultSetHoldability [_] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT) ;; Retrieves this database's default holdability for ResultSet objects.
(^java.sql.RowIdLifetime getRowIdLifetime [_] java.sql.RowIdLifetime/ROWID_UNSUPPORTED) ;; Indicates whether or not this data source supports the SQL ROWID type, and if so the lifetime for which a RowId object remains valid.
(^java.sql.ResultSet getSchemas [_] (create-resultset-from-seq [])) ;; Retrieves the schema names available in this database.
(^java.sql.ResultSet getSchemas [_ ^String catalog, ^String schemaPattern] (create-resultset-from-seq [])) ;; Retrieves the schema names available in this database.
(^String getSchemaTerm [_] "schema") ;; Retrieves the database vendor's preferred term for "schema".
(^String getSearchStringEscape [_] "") ;; Retrieves the string that can be used to escape wildcard characters.
(^String getSQLKeywords [_] "") ;; Retrieves a commaseparated list of all of this database's SQL keywords that are NOT also SQL:2003 keywords.
(^int getSQLStateType [_] -1) ;; Indicates whether the SQLSTATE returned by SQLException.getSQLState is X/Open (now known as Open Group) SQL CLI or SQL:2003.
(^String getStringFunctions [_] "") ;; Retrieves a commaseparated list of string functions available with this database.
(^java.sql.ResultSet getSuperTables [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the table hierarchies defined in a particular schema in this database.
(^java.sql.ResultSet getSuperTypes [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the userdefined type (UDT) hierarchies defined in a particular schema in this database.
(^String getSystemFunctions [_] "") ;; Retrieves a commaseparated list of system functions available with this database.
(^java.sql.ResultSet getTablePrivileges [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the access rights for each table available in a catalog.
(^java.sql.ResultSet getTables [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern, ^"[Ljava.lang.String;" types] (create-resultset-from-seq [])) ;;String[] ;; Retrieves a description of the tables available in the given catalog.
(^java.sql.ResultSet getTableTypes [_] (create-resultset-from-seq [])) ;; Retrieves the table types available in this database.
(^String getTimeDateFunctions [_] "") ;; Retrieves a commaseparated list of the time and date functions available with this database.
(^java.sql.ResultSet getTypeInfo [_] (create-resultset-from-seq [])) ;; Retrieves a description of all the data types supported by this database.
(^java.sql.ResultSet getUDTs [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern, ^ints types] (create-resultset-from-seq [])) ;; Retrieves a description of the userdefined types (UDTs) defined in a particular schema.
(^String getURL [_] "") ;; Retrieves the URL for this DBMS.
(^String getUserName [_] "") ;; Retrieves the user name as known to this database.
(^java.sql.ResultSet getVersionColumns [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of a table's columns that are automatically updated when any value in a row is updated.
(^boolean insertsAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row insert can be detected by calling the method ResultSet.rowInserted.
(^boolean isCatalogAtStart [_] false) ;; Retrieves whether a catalog appears at the start of a fully qualified table name.
(^boolean isReadOnly [_] true) ;; Retrieves whether this database is in readonly mode.
(^boolean locatorsUpdateCopy [_] false) ;; Indicates whether updates made to a LOB are made on a copy or directly to the LOB.
(^boolean nullPlusNonNullIsNull [_] false) ;; Retrieves whether this database supports concatenations between NULL and nonNULL values being NULL.
(^boolean nullsAreSortedAtEnd [_] false) ;; Retrieves whether NULL values are sorted at the end regardless of sort order.
(^boolean nullsAreSortedAtStart [_] false) ;; Retrieves whether NULL values are sorted at the start regardless of sort order.
(^boolean nullsAreSortedHigh [_] false) ;; Retrieves whether NULL values are sorted high.
(^boolean nullsAreSortedLow [_] false) ;; Retrieves whether NULL values are sorted low.
(^boolean othersDeletesAreVisible [_ ^int type] false) ;; Retrieves whether deletes made by others are visible.
(^boolean othersInsertsAreVisible [_ ^int type] false) ;; Retrieves whether inserts made by others are visible.
(^boolean othersUpdatesAreVisible [_ ^int type] false) ;; Retrieves whether updates made by others are visible.
(^boolean ownDeletesAreVisible [_ ^int type] false) ;; Retrieves whether a result set's own deletes are visible.
(^boolean ownInsertsAreVisible [_ ^int type] false) ;; Retrieves whether a result set's own inserts are visible.
(^boolean ownUpdatesAreVisible [_ ^int type] false) ;; Retrieves whether for the given type of ResultSet object, the result set's own updates are visible.
(^boolean storesLowerCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in lower case.
(^boolean storesLowerCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in lower case.
(^boolean storesMixedCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in mixed case.
(^boolean storesMixedCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in mixed case.
(^boolean storesUpperCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in upper case.
(^boolean storesUpperCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in upper case.
(^boolean supportsAlterTableWithAddColumn [_] false) ;; Retrieves whether this database supports ALTER TABLE with add column.
(^boolean supportsAlterTableWithDropColumn [_] false) ;; Retrieves whether this database supports ALTER TABLE with drop column.
(^boolean supportsANSI92EntryLevelSQL [_] false) ;; Retrieves whether this database supports the ANSI92 entry level SQL grammar.
(^boolean supportsANSI92FullSQL [_] false) ;; Retrieves whether this database supports the ANSI92 full SQL grammar supported.
(^boolean supportsANSI92IntermediateSQL [_] false) ;; Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported.
(^boolean supportsBatchUpdates [_] false) ;; Retrieves whether this database supports batch updates.
(^boolean supportsCatalogsInDataManipulation [_] false) ;; Retrieves whether a catalog name can be used in a data manipulation statement.
(^boolean supportsCatalogsInIndexDefinitions [_] false) ;; Retrieves whether a catalog name can be used in an index definition statement.
(^boolean supportsCatalogsInPrivilegeDefinitions [_] false) ;; Retrieves whether a catalog name can be used in a privilege definition statement.
(^boolean supportsCatalogsInProcedureCalls [_] false) ;; Retrieves whether a catalog name can be used in a procedure call statement.
(^boolean supportsCatalogsInTableDefinitions [_] false) ;; Retrieves whether a catalog name can be used in a table definition statement.
(^boolean supportsColumnAliasing [_] false) ;; Retrieves whether this database supports column aliasing.
(^boolean supportsConvert [_] false) ;; Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion of one JDBC type to another.
(^boolean supportsConvert [_ ^int fromType, ^int toType] false) ;; Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType.
(^boolean supportsCoreSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Core SQL grammar.
(^boolean supportsCorrelatedSubqueries [_] false) ;; Retrieves whether this database supports correlated subqueries.
(^boolean supportsDataDefinitionAndDataManipulationTransactions [_] false) ;; Retrieves whether this database supports both data definition and data manipulation statements within a transaction.
(^boolean supportsDataManipulationTransactionsOnly [_] false) ;; Retrieves whether this database supports only data manipulation statements within a transaction.
(^boolean supportsDifferentTableCorrelationNames [_] false) ;; Retrieves whether, when table correlation names are supported, they are restricted to being different from the names of the tables.
(^boolean supportsExpressionsInOrderBy [_] false) ;; Retrieves whether this database supports expressions in ORDER BY lists.
(^boolean supportsExtendedSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Extended SQL grammar.
(^boolean supportsFullOuterJoins [_] false) ;; Retrieves whether this database supports full nested outer joins.
(^boolean supportsGetGeneratedKeys [_] false) ;; Retrieves whether autogenerated keys can be retrieved after a statement has been executed
(^boolean supportsGroupBy [_] false) ;; Retrieves whether this database supports some form of GROUP BY clause.
(^boolean supportsGroupByBeyondSelect [_] false) ;; Retrieves whether this database supports using columns not included in the SELECT statement in a GROUP BY clause provided that all of the columns in the SELECT statement are included in the GROUP BY clause.
(^boolean supportsGroupByUnrelated [_] false) ;; Retrieves whether this database supports using a column that is not in the SELECT statement in a GROUP BY clause.
(^boolean supportsIntegrityEnhancementFacility [_] false) ;; Retrieves whether this database supports the SQL Integrity Enhancement Facility.
(^boolean supportsLikeEscapeClause [_] false) ;; Retrieves whether this database supports specifying a LIKE escape clause.
(^boolean supportsLimitedOuterJoins [_] false) ;; Retrieves whether this database provides limited support for outer joins.
(^boolean supportsMinimumSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Minimum SQL grammar.
(^boolean supportsMixedCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and as a result stores them in mixed case.
(^boolean supportsMixedCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as a result stores them in mixed case.
(^boolean supportsMultipleOpenResults [_] false) ;; Retrieves whether it is possible to have multiple ResultSet objects returned from a CallableStatement object simultaneously.
(^boolean supportsMultipleResultSets [_] false) ;; Retrieves whether this database supports getting multiple ResultSet objects from a single call to the method execute.
(^boolean supportsMultipleTransactions [_] false) ;; Retrieves whether this database allows having multiple transactions open at once (on different connections).
(^boolean supportsNamedParameters [_] false) ;; Retrieves whether this database supports named parameters to callable statements.
(^boolean supportsNonNullableColumns [_] false) ;; Retrieves whether columns in this database may be defined as nonnullable.
(^boolean supportsOpenCursorsAcrossCommit [_] false) ;; Retrieves whether this database supports keeping cursors open across commits.
(^boolean supportsOpenCursorsAcrossRollback [_] false) ;; Retrieves whether this database supports keeping cursors open across rollbacks.
(^boolean supportsOpenStatementsAcrossCommit [_] false) ;; Retrieves whether this database supports keeping statements open across commits.
(^boolean supportsOpenStatementsAcrossRollback [_] false) ;; Retrieves whether this database supports keeping statements open across rollbacks.
(^boolean supportsOrderByUnrelated [_] false) ;; Retrieves whether this database supports using a column that is not in the SELECT statement in an ORDER BY clause.
(^boolean supportsOuterJoins [_] false) ;; Retrieves whether this database supports some form of outer join.
(^boolean supportsPositionedDelete [_] false) ;; Retrieves whether this database supports positioned DELETE statements.
(^boolean supportsPositionedUpdate [_] false) ;; Retrieves whether this database supports positioned UPDATE statements.
(^boolean supportsResultSetConcurrency [_ ^int type, ^int concurrency] false) ;; Retrieves whether this database supports the given concurrency type in combination with the given result set type.
(^boolean supportsResultSetHoldability [_ ^int holdability] false) ;; Retrieves whether this database supports the given result set holdability.
(^boolean supportsResultSetType [_ ^int type] false) ;; Retrieves whether this database supports the given result set type.
(^boolean supportsSavepoints [_] false) ;; Retrieves whether this database supports savepoints.
(^boolean supportsSchemasInDataManipulation [_] false) ;; Retrieves whether a schema name can be used in a data manipulation statement.
(^boolean supportsSchemasInIndexDefinitions [_] false) ;; Retrieves whether a schema name can be used in an index definition statement.
(^boolean supportsSchemasInPrivilegeDefinitions [_] false) ;; Retrieves whether a schema name can be used in a privilege definition statement.
(^boolean supportsSchemasInProcedureCalls [_] false) ;; Retrieves whether a schema name can be used in a procedure call statement.
(^boolean supportsSchemasInTableDefinitions [_] false) ;; Retrieves whether a schema name can be used in a table definition statement.
(^boolean supportsSelectForUpdate [_] false) ;; Retrieves whether this database supports SELECT FOR UPDATE statements.
(^boolean supportsStatementPooling [_] false) ;; Retrieves whether this database supports statement pooling.
(^boolean supportsStoredFunctionsUsingCallSyntax [_] false) ;; Retrieves whether this database supports invoking userdefined or vendor functions using the stored procedure escape syntax.
(^boolean supportsStoredProcedures [_] false) ;; Retrieves whether this database supports stored procedure calls that use the stored procedure escape syntax.
(^boolean supportsSubqueriesInComparisons [_] false) ;; Retrieves whether this database supports subqueries in comparison expressions.
(^boolean supportsSubqueriesInExists [_] false) ;; Retrieves whether this database supports subqueries in EXISTS expressions.
(^boolean supportsSubqueriesInIns [_] false) ;; Retrieves whether this database supports subqueries in IN expressions.
(^boolean supportsSubqueriesInQuantifieds [_] false) ;; Retrieves whether this database supports subqueries in quantified expressions.
(^boolean supportsTableCorrelationNames [_] false) ;; Retrieves whether this database supports table correlation names.
(^boolean supportsTransactionIsolationLevel [_ ^int level] false) ;; Retrieves whether this database supports the given transaction isolation level.
(^boolean supportsTransactions [_] false) ;; Retrieves whether this database supports transactions.
(^boolean supportsUnion [_] false) ;; Retrieves whether this database supports SQL UNION.
(^boolean supportsUnionAll [_] false) ;; Retrieves whether this database supports SQL UNION ALL.
(^boolean updatesAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row update can be detected by calling the method ResultSet.rowUpdated.
(^boolean usesLocalFilePerTable [_] false) ;; Retrieves whether this database uses a file for each table.
(^boolean usesLocalFiles [_] true)) ;; Retrieves whether this database stores tables in a local file.
(deftype Connection [binlog-state]
java.sql.Connection
(close [_]
;; Releases this Connection object's database and JDBC
;; resources immediately instead of waiting for them to be
;; automatically released.
(dosync (when-let [st (:statement @jdbc-state)] (.close st))
(alter jdbc-state assoc :closed true :connection nil)
(send-off (:binlog-state @jdbc-state) binlog/cdc-stop)))
(createStatement [t]
(dosync (if (:statement @jdbc-state)
(throwf "Close statement %s first" (:statement @jdbc-state))
(let [s (Statement.)]
(alter jdbc-state assoc :statement s)
s))))
(createStatement [t rs-type rs-cncrcy] (.createStatement t))
(createStatement [t rs-type rs-cncrcy rs-holdabilityb] (.createStatement t))
;; (^java.sql.Statement createStatement [t]) ;; Creates a Statement object for sending SQL statements to the database.
;; (^java.sql.Statement createStatement [t ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a Statement object that will generate ResultSet objects with the given type and concurrency.
;; (^java.sql.Statement createStatement [t ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability.
(getMetaData [t] (ConnectionMetadata.))
;; unimplemented
(^void clearWarnings [t]) ;; Clears all warnings reported for this Connection object.
(^void commit [t]) ;; Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
(^java.sql.Array createArrayOf [t ^String typeName, ^"[Ljava.lang.Object;" elements]) ;; Factory method for creating Array objects.
(^java.sql.Blob createBlob [t]) ;; Constructs an object that implements the Blob interface.
(^java.sql.Clob createClob [t]) ;; Constructs an object that implements the Clob interface.
(^java.sql.NClob createNClob [t]) ;; Constructs an object that implements the NClob interface.
(^java.sql.SQLXML createSQLXML [t]) ;; Constructs an object that implements the SQLXML interface.
(^java.sql.Struct createStruct [t ^String typeName, ^"[Ljava.lang.Object;" attributes]) ;; Factory method for creating Struct objects.
(^boolean getAutoCommit [t] false) ;; Retrieves the current autocommit mode for this Connection object.
(^String getCatalog [t] "") ;; Retrieves this Connection object's current catalog name.
(^java.util.Properties getClientInfo [t] {}) ;; Returns a list containing the name and current value of each client info property supported by the driver.
(^String getClientInfo [t ^String name] "") ;; Returns the value of the client info property specified by name.
(^int getHoldability [t] 0) ;; Retrieves the current holdability of ResultSet objects created using this Connection object.
(^int getTransactionIsolation [t] 0) ;; Retrieves this Connection object's current transaction isolation level.
(^java.util.Map getTypeMap [t] {}) ;; Retrieves the Map object associated with this Connection object.
(^java.sql.SQLWarning getWarnings [t]) ;; Retrieves the first warning reported by calls on this Connection object.
(^boolean isClosed [t] (:closed @jdbc-state)) ;; Retrieves whether this Connection object has been closed.
(^boolean isReadOnly [t] true) ;; Retrieves whether this Connection object is in readonly mode.
(^boolean isValid [t ^int timeout] true) ;; Returns true if the connection has not been closed and is still valid.
(^String nativeSQL [t ^String sql] sql) ;; Converts the given SQL statement into the system's native SQL grammar.
(^java.sql.CallableStatement prepareCall [t ^String sql]) ;; Creates a CallableStatement object for calling database stored procedures.
(^java.sql.CallableStatement prepareCall [t ^String sql, ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.CallableStatement prepareCall [t ^String sql, ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.PreparedStatement prepareStatement [t ^String sql]) ;; Creates a PreparedStatement object for sending parameterized SQL statements to the database.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int autoGeneratedKeys]) ;; Creates a default PreparedStatement object that has the capability to retrieve autogenerated keys.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^ints columnIndexes]) ;; Creates a default PreparedStatement object capable of returning the autogenerated keys designated by the given array.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^"[Ljava.lang.String;" columnNames]) ;; Creates a default PreparedStatement object capable of returning the autogenerated keys designated by the given array.
(^void releaseSavepoint [t ^java.sql.Savepoint savepoint]) ;; Removes the specified Savepoint and subsequent Savepoint objects from the current transaction.
(^void rollback [t]) ;; Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
(^void rollback [t ^java.sql.Savepoint savepoint]) ;; Undoes all changes made after the given Savepoint object was set.
(^void setAutoCommit [t ^boolean autoCommit]) ;; Sets this connection's autocommit mode to the given state.
(^void setCatalog [t ^String catalog]) ;; Sets the given catalog name in order to select a subspace of this Connection object's database in which to work.
(^void setClientInfo [t ^Properties properties]) ;; Sets the value of the connection's client info properties.
(^void setClientInfo [t ^String name, ^String value]) ;; Sets the value of the client info property specified by name to the value specified by value.
(^void setHoldability [t ^int holdability]) ;; Changes the default holdability of ResultSet objects created using this Connection object to the given holdability.
(^void setReadOnly [t ^boolean readOnly]) ;; Puts this connection in readonly mode as a hint to the driver to enable database optimizations.
(^java.sql.Savepoint setSavepoint [t]) ;; Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.
(^java.sql.Savepoint setSavepoint [t ^String name]) ;; Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.
(^void setTransactionIsolation [t ^int level]) ;; Attempts to change the transaction isolation level for this Connection object to the one given.
(^void setTypeMap [t ^java.util.Map map]) ;; Installs the given TypeMap object as the type map for this Connection object.
java.sql.Wrapper
(isWrapperFor [_ iface])
(unwrap [_ iface]))
(defn create-connection [binlog-index-file user pwd]
(let [state (binlog/cdc-init (fn [_]))
;; mysql-conn (sql/get-connection
;; {:classname "com.mysql.jdbc.Driver"
;; :subprotocol "mysql"
;; :subname "//localhost"
;; ;;:username user
;; :user user
;; :password pwd})
conn (Connection. state)]
(dosync (alter jdbc-state assoc
:statement nil
:resultset nil
:connection conn
:binlog-state state
:closed false))
(set-new-queue)
(send state binlog/cdc-start binlog-index-file)
conn))
|
76256
|
;; The MIT License
;;
;; Copyright (c) 2010 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
;; provide a basic jdbc-interface for the cdc-system
(ns cdc.jdbc
(:use [clojure.pprint :only [pprint]])
(:require [cdc.mysql-binlog :as binlog]
;;[clojure.contrib.sql.internal :as sql]
)
(:import (java.sql DriverManager
DriverPropertyInfo)
(java.util Properties)
java.util.concurrent.LinkedBlockingQueue))
;; do not import the classes we are implementing
(def jdbc-state (ref {:connection nil
:statement nil
:resultset nil
:binlog-state nil
:queue nil}))
(defn set-new-queue
"set a new queue"
[]
(let [queue (LinkedBlockingQueue. 10)
event-fn #(do (println "event-fn: got" (count %) "events!")
(.put #^LinkedBlockingQueue queue %))]
(dosync (alter jdbc-state assoc :queue queue)
(send (:binlog-state @jdbc-state) assoc :event-fn event-fn))))
(defn throwf-sql-not-supported [& args]
(throw (java.sql.SQLFeatureNotSupportedException. (apply format (or args [""])))))
(defn throwf-unsupported [& args]
(throw (UnsupportedOperationException. (apply format (or args [""])))))
(defn throwf-illegal [& args]
(throw (IllegalArgumentException. (apply format (or args [""])))))
(defn throwf [& [format-string & args]]
(throw (Exception. (apply format (str "cdc.jdbc: " format-string) args))))
(defn driver-property-info [& {n :name,
v :value,
d :description,
c :choices,
r? :required}]
(let [info (DriverPropertyInfo. (str n) (str v))]
(set! (.choices info) (into-array String (map str c)))
(set! (.description info) (str d))
(set! (.required info) (boolean r?))
info))
;;(def _ee (binlog/read-binlog "/var/log/mysql/binlog.001024"))
(deftype ResultSetMetaData [schema table row]
java.sql.ResultSetMetaData
(getCatalogName [t c] "") ;; Gets the designated column's table's catalog name.
(getColumnClassName [t c] (type (nth row (dec c)))) ;;Returns the fully-qualified name of the Java class whose instances are manufactured if the method ResultSet.getObject is called to retrieve a value from the column.
(getColumnCount [t] (count row)) ;; int; Returns the number of columns in this ResultSet object.
(getColumnDisplaySize [t c] 1024) ;; int; Indicates the designated column's normal maximum width in characters.
(getColumnLabel [t c] (str c)) ;; String; Gets the designated column's suggested title for use in printouts and displays.
(getColumnName [t c] (str c)) ;; String; Get the designated column's name.
(getColumnType [t c] ;; int; Retrieves the designated column's SQL type.
(let [v (nth row (dec c))]
(cond (decimal? v) java.sql.Types/DECIMAL
(integer? v) java.sql.Types/INTEGER
(string? v) java.sql.Types/VARCHAR
:else (throwf "unsupported type: %s" (type v)))))
(getColumnTypeName [t c] (str (.getColumnType t c))) ;; String; Retrieves the designated column's database-specific type name.
(getPrecision [t c] 10) ;; int; Get the designated column's specified column size.
(getScale [t c] 10) ;; int; Gets the designated column's number of digits to right of the decimal point.
(getSchemaName [t c] schema) ;; String; Get the designated column's table's schema.
(getTableName [t c] table) ;; String; Gets the designated column's table name.
(isAutoIncrement [t c] false) ;; boolean; Indicates whether the designated column is automatically numbered.
(isCaseSensitive [t c] true) ;; boolean; Indicates whether a column's case matters.
(isCurrency [t c] false) ;; boolean; Indicates whether the designated column is a cash value.
(isDefinitelyWritable [t c] false) ;; boolean; Indicates whether a write on the designated column will definitely succeed.
(isNullable [t c] java.sql.ResultSetMetaData/columnNullableUnknown) ;; int; Indicates the nullability of values in the designated column.
(isReadOnly [t c] true) ;; boolean; Indicates whether the designated column is definitely not writable.
(isSearchable [t c] false) ;; boolean; Indicates whether the designated column can be used in a where clause.
(isSigned [t c] true) ;; boolean; Indicates whether values in the designated column are signed numbers.
(isWritable [t c] false)) ;; boolean; Indicates whether it is possible for a write on the designated column to succeed.
(defn rows-delta-type
"Return a fn that, given an event returns a seq of rows according to
the quantifier."
[{r :rows, t :type, tbl :table}]
(mapcat (condp = t
'WRITE_ROWS_EVENT #(list (conj % "insert"))
'DELETE_ROWS_EVENT #(list (conj % "delete"))
'UPDATE_ROWS_EVENT #(list (conj (first %) "update-before")
(conj (second %) "update"))
;; ignore non-data events
nil)
r))
(def _example-statement "select * from \"foo\".\"auto\" where _delta_type = ' insert'")
(defn tokenize-statement [s]
(loop [[t & more :as s] (.split s " ")
ast []]
(cond (empty? s) ast
(or (= t "\"") (= t "'"))
(recur (drop-while #(not= % t) more)
(->> more
(take-while #(not= % t))
(map #(if (= "" %) " " %))
(apply str t)
(conj ast)))
(= t "")
(recur more ast)
:else
(recur more (conj ast t)))))
(defn parse-statement [s]
(loop [[t & more :as s] (tokenize-statement s)
ast {:select nil :from nil :where nil}]
(cond (empty? s) ast
(#{"select"} t)
(recur (next more) (assoc ast :select (first more)))
(#{"from"} t)
(recur (drop-while #(not= % "where") more)
(assoc ast :from (apply str (take-while #(not= % "where") more))))
(= t "where")
(assoc ast :where (next s))
:else
(throwf-illegal "unknown statement: %s" t))))
;;(parse-statement _example-statement)
(defn really-lazy-concat
"circumvent a bug in mapcat which prevents full lazyness."
([r]
(lazy-seq (really-lazy-concat (first r) (rest r))))
([s r]
(lazy-seq
(if (empty? s)
(if (empty? r)
nil
(really-lazy-concat r))
(cons (first s)
(really-lazy-concat (rest s) r))))))
(defn create-resultset-seq
"given a simple sql expression and queue, return lazy seq of vectors
from queue."
[sql queue]
(let [{table :from [_ _ dtype] :where} (parse-statement sql)
dtype (when dtype (.replace dtype "'" ""))
[table-name schema-name] (-> table ;; for now, don't allow dots in table names
(.replace "\"" "")
(.split "\\.")
reverse)
s (->> (repeatedly #(.take queue))
(really-lazy-concat)
(filter #(and (= (:table-name %) table-name)
(= (:db-name %) schema-name)))
(map rows-delta-type)
(really-lazy-concat)
(filter (if dtype
#(= (last %) dtype)
identity))
;; in jdbc, one must call .next on the resultset to get the first row
(cons nil))]
s))
(defmacro getcol []
`(if-let [v# (nth (first ~'rows) (dec ~'i))]
(do (set! ~'was-null? false)
v#)
(do (set! ~'was-null? true)
nil)))
(defmacro getcol-by-name []
`(if-let [v# (nth (first ~'rows) (.findColumn ~'t ~'c))]
(do (set! ~'was-null? false)
v#)
(do (set! ~'was-null? true)
nil)))
;; generic resultset implementation
;; please, single threaded access only!
;; mind the gap, nothing coordinated
;; jdbc column numbering is 1<=colNum<=colCount!!!
(deftype ResultSet [#^{:volatile-mutable true} rows ;; a set of vectors of columnvalues, starting with a nil
#^{:volatile-mutable true} was-null?
sql]
java.sql.ResultSet
;; essential methods
(close [t] (dosync (set-new-queue)
(alter jdbc-state assoc :resultset nil)))
(isClosed [t])
(next [t]
;; moves cursor one row forward if there is a row
(if-let [r (next rows)]
(do (set! rows r)
true)
false))
(wasNull [t] (boolean was-null?)) ;; whether the last access to any col was sql-null
(getMetaData [t]
;; generate resultset metadata using the first row
(ResultSetMetaData. "" "" (second rows))) ;; ResultSetMetaData
(findColumn [t label]
;; returns the colnumber from the colname,
;; colnames are currently only printed numbers: "1", "2" ...
(Integer/valueOf label))
;; data getters
(^String getString [t ^int i] (getcol))
(^String getString [t ^String c] (getcol-by-name))
(^boolean getBoolean [t ^int i])
(^boolean getBoolean [t ^String c])
(^byte getByte [t ^int i] (getcol))
(^byte getByte [t ^String c] (getcol-by-name))
(^short getShort [t ^int i] (getcol))
(^short getShort [t ^String c] (getcol-by-name))
(^int getInt [t ^int i] (getcol))
(^int getInt [t ^String c] (getcol-by-name))
(^long getLong [t ^int i] (getcol))
(^long getLong [t ^String c] (getcol-by-name))
(^float getFloat [t ^int i] (getcol))
(^float getFloat [t ^String c] (getcol-by-name))
(^double getDouble [t ^int i] (getcol))
(^double getDouble [t ^String c] (getcol-by-name))
(^BigDecimal getBigDecimal [t ^int i] (java.math.BigDecimal. (str (getcol))))
(^BigDecimal getBigDecimal [t ^String c] (java.math.BigDecimal. (str (getcol-by-name))))
(^BigDecimal getBigDecimal [t ^int i ^int scale] (.getBigDecimal t i))
(^BigDecimal getBigDecimal [t ^String c ^int scale] (.getBigDecimal t c))
(^bytes getBytes [t ^int i])
(^bytes getBytes [t ^String c])
(^java.sql.Date getDate [t ^int i])
(^java.sql.Date getDate [t ^String c])
(^java.sql.Date getDate [t ^int i ^java.util.Calendar cal])
(^java.sql.Date getDate [t ^String c ^java.util.Calendar cal])
(^java.sql.Time getTime [t ^int i])
(^java.sql.Time getTime [t ^String c])
(^java.sql.Time getTime [t ^int i ^java.util.Calendar cal])
(^java.sql.Time getTime [t ^String c ^java.util.Calendar cal])
(^java.sql.Timestamp getTimestamp [t ^int i])
(^java.sql.Timestamp getTimestamp [t ^String c])
(^java.sql.Timestamp getTimestamp [t ^int i ^java.util.Calendar cal])
(^java.sql.Timestamp getTimestamp [t ^String c ^java.util.Calendar cal])
(^java.io.InputStream getAsciiStream [t ^int i])
(^java.io.InputStream getAsciiStream [t ^String c])
(^java.io.InputStream getUnicodeStream [t ^int i])
(^java.io.InputStream getUnicodeStream [t ^String c])
(^java.io.InputStream getBinaryStream [t ^int i])
(^java.io.InputStream getBinaryStream [t ^String c])
(getObject [t ^int i] (getcol))
(getObject [t ^String c] (getcol-by-name))
(getObject [t ^int i ^java.util.Map m]) ;; get object with mapping
(getObject [t ^String c ^java.util.Map m])
(^java.io.Reader getCharacterStream [t ^int i])
(^java.io.Reader getCharacterStream [t ^String c])
(^java.sql.Ref getRef [t ^int i])
(^java.sql.Ref getRef [t ^String c])
(^java.sql.Blob getBlob [t ^int i])
(^java.sql.Blob getBlob [t ^String c])
(^java.sql.Clob getClob [t ^int i])
(^java.sql.Clob getClob [t ^String c])
(^java.sql.Array getArray [t ^int i])
(^java.sql.Array getArray [t ^String c])
(^java.net.URL getURL [t ^int i])
(^java.net.URL getURL [t ^String c])
(^java.sql.NClob getNClob [t ^int i])
(^java.sql.NClob getNClob [t ^String c])
(^java.sql.SQLXML getSQLXML [t ^int i])
(^java.sql.SQLXML getSQLXML [t ^String c])
(^String getNString [t ^int i])
(^String getNString [t ^String c])
(^java.io.Reader getNCharacterStream [t ^int i])
(^java.io.Reader getNCharacterStream [t ^String c])
;; unsupported cursor methods
(getCursorName [t] (throwf-sql-not-supported))
(absolute [t r] (throwf-sql-not-supported))
(afterLast [t] (throwf-sql-not-supported))
(beforeFirst [t] (throwf-sql-not-supported))
(relative [t r] (throwf-sql-not-supported))
(isBeforeFirst [t] (throwf-sql-not-supported))
(isAfterLast [t] (throwf-sql-not-supported))
(isFirst [t] (throwf-sql-not-supported))
(isLast [t] (throwf-sql-not-supported))
(first [t] (throwf-sql-not-supported))
(last [t] (throwf-sql-not-supported))
(previous [t] (throwf-sql-not-supported))
(setFetchDirection [t dir] (throwf-sql-not-supported))
(getFetchDirection [t] 0)
(moveToInsertRow [t] (throwf-sql-not-supported))
(moveToCurrentRow [t] (throwf-sql-not-supported))
;; misc
(setFetchSize [t s])
(getFetchSize [t] 0)
(getType [t] java.sql.ResultSet/TYPE_FORWARD_ONLY)
(getConcurrency [t] java.sql.ResultSet/CONCUR_READ_ONLY)
(getRow [t] (throwf-sql-not-supported))
(getWarnings [t] )
(clearWarnings [t])
(^java.sql.RowId getRowId [t ^int i] (throwf-sql-not-supported))
(^java.sql.RowId getRowId [t ^String c] (throwf-sql-not-supported))
(getHoldability [t] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT)
;; update functions
(rowUpdated [t] (throwf-sql-not-supported))
(rowDeleted [t] (throwf-sql-not-supported))
(rowInserted [t] (throwf-sql-not-supported))
(updateRow [t] (throwf-sql-not-supported))
(deleteRow [t] (throwf-sql-not-supported))
(insertRow [t] (throwf-sql-not-supported))
(cancelRowUpdates [t] (throwf-sql-not-supported)))
(defn create-resultset [sql]
(ResultSet. (create-resultset-seq sql (:queue @jdbc-state)) false sql))
(defn create-resultset-from-seq
"Return a resultset implementation from the given seq of vectors.
a string may be supplied for debug purposes which is stored in the
resultset sql field."
[s & [sql-string]]
(ResultSet. (cons nil s) false sql-string))
(deftype Statement []
java.sql.Statement
;; essential methods
(close [t] (dosync (when-let [rs (:resultset @jdbc-state)] (.close rs))
(alter jdbc-state assoc :statement nil)))
(executeQuery [t sql]
(dosync (if-let [rs (:resultset @jdbc-state)]
(throwf "Close Resultset %s first." rs)
(let [rs (create-resultset sql)]
(alter jdbc-state assoc :resultset rs)
rs))))
(execute [t sql] (.executeQuery t sql) true)
;; we do not have autogenerated keys
(^boolean execute [t ^String sql ^int _] (.execute t sql))
(^boolean execute [t ^String sql ^ints _] (boolean (.execute t sql)))
(^boolean execute [t ^String sql ^"[Ljava.lang.String;" _] (boolean (.execute t sql)))
(getResultSet [t] (:resultset @jdbc-state))
;; misc, mostly unsupported or ignored
(addBatch [t s] (throwf-unsupported))
(executeBatch [t] (throwf-unsupported))
(cancel [t] (.close t))
(clearBatch [t] (throwf-unsupported))
(clearWarnings [t] (throwf-unsupported))
(executeUpdate [t sql] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^int _] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^ints _] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^"[Ljava.lang.String;" _] (throwf-unsupported))
(getConnection [t] (:connection @jdbc-state))
(getFetchDirection [t] java.sql.ResultSet/FETCH_UNKNOWN)
(getFetchSize [t] 1)
(getGeneratedKeys [t] (throwf-sql-not-supported))
(getMaxFieldSize [t] 0) ;; unlimited
(getMoreResults [t] false) ;; only ever one rs
(getMoreResults [t _] false)
(getQueryTimeout [t] 0) ;; no timeout
(getResultSetConcurrency [t] java.sql.ResultSet/CONCUR_READ_ONLY)
(getResultSetHoldability [t] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT)
(getResultSetType [t] java.sql.ResultSet/TYPE_FORWARD_ONLY)
(getUpdateCount [t] -1)
(getWarnings [t] nil)
(isClosed [t] false)
(isPoolable [t] false)
(setCursorName [t s] (throwf-sql-not-supported))
(setEscapeProcessing [t flag]) ;; ignore
(setFetchDirection [t dir]) ;; ignore
(setFetchSize [t n]) ;; ignore
(setMaxFieldSize [t s]) ;; ignore, may be useful to obey to for varchars
(setMaxRows [t s]) ;; ignore
(setPoolable [t flag]) ;; ignore
(setQueryTimeout [t seconds]))
(deftype ConnectionMetadata []
java.sql.DatabaseMetaData
(^boolean allProceduresAreCallable [_] false) ;; Retrieves whether the current user can call all the procedures returned by the method getProcedures.
(^boolean allTablesAreSelectable [_] false) ;; Retrieves whether the current user can use all the tables returned by the method getTables in a SELECT statement.
(^boolean autoCommitFailureClosesAllResultSets [_] false) ;; Retrieves whether a SQLException while autoCommit is true inidcates that all open ResultSets are closed, even ones that are holdable.
(^boolean dataDefinitionCausesTransactionCommit [_] false) ;; Retrieves whether a data definition statement within a transaction forces the transaction to commit.
(^boolean dataDefinitionIgnoredInTransactions [_] true) ;; Retrieves whether this database ignores a data definition statement within a transaction.
(^boolean deletesAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row delete can be detected by calling the method ResultSet.rowDeleted.
(^boolean doesMaxRowSizeIncludeBlobs [_] false) ;; Retrieves whether the return value for the method getMaxRowSize includes the SQL data types LONGVARCHAR and LONGVARBINARY.
(^java.sql.ResultSet getAttributes [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern, ^String attributeNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given attribute of the given type for a userdefined type (UDT) that is available in the given schema and catalog.
(^java.sql.ResultSet getBestRowIdentifier [_ ^String catalog, ^String schema, ^String table, ^int scope, ^boolean nullable] (create-resultset-from-seq [])) ;; Retrieves a description of a table's optimal set of columns that uniquely identifies a row.
(^java.sql.ResultSet getCatalogs [_] (create-resultset-from-seq [])) ;; Retrieves the catalog names available in this database.
(^String getCatalogSeparator [_] ".") ;; Retrieves the String that this database uses as the separator between a catalog and table name.
(^String getCatalogTerm [_] "") ;; Retrieves the database vendor's preferred term for "catalog".
(^java.sql.ResultSet getClientInfoProperties [_] (create-resultset-from-seq [])) ;; Retrieves a list of the client info properties that the driver supports.
(^java.sql.ResultSet getColumnPrivileges [_ ^String catalog, ^String schema, ^String table, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the access rights for a table's columns.
(^java.sql.ResultSet getColumns [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of table columns available in the specified catalog.
(^java.sql.Connection getConnection [_] (:connection @jdbc-state)) ;; Retrieves the connection that produced this metadata object.
(^java.sql.ResultSet getCrossReference [_ ^String parentCatalog, ^String parentSchema, ^String parentTable, ^String foreignCatalog, ^String foreignSchema, ^String foreignTable] (create-resultset-from-seq [])) ;; Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
(^int getDatabaseMajorVersion [_] -1) ;; Retrieves the major version number of the underlying database.
(^int getDatabaseMinorVersion [_] -1) ;; Retrieves the minor version number of the underlying database.
(^String getDatabaseProductName [_] "mysql") ;; Retrieves the name of this database product.
(^String getDatabaseProductVersion [_] "0.1") ;; Retrieves the version number of this database product.
(^int getDefaultTransactionIsolation [_] java.sql.Connection/TRANSACTION_NONE) ;; Retrieves this database's default transaction isolation level.
(^int getDriverMajorVersion [_] 0) ;; Retrieves this JDBC driver's major version number.
(^int getDriverMinorVersion [_] 1) ;; Retrieves this JDBC driver's minor version number.
(^String getDriverName [_] "mysql binlog cdc jdbc interface") ;; Retrieves the name of this JDBC driver.
(^String getDriverVersion [_] "0.1") ;; Retrieves the version number of this JDBC driver as a String.
(^java.sql.ResultSet getExportedKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
(^String getExtraNameCharacters [_] "") ;; Retrieves all the "extra" characters that can be used in unquoted identifier names (those beyond az, AZ, 09 and _).
(^java.sql.ResultSet getFunctionColumns [_ ^String catalog, ^String schemaPattern, ^String functionNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given catalog's system or user function parameters and return type.
(^java.sql.ResultSet getFunctions [_ ^String catalog, ^String schemaPattern, ^String functionNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the system and user functions available in the given catalog.
(^String getIdentifierQuoteString [_] "\"") ;; Retrieves the string used to quote SQL identifiers.
(^java.sql.ResultSet getImportedKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the primary key columns that are referenced by the given table's foreign key columns (the primary keys imported by a table).
(^java.sql.ResultSet getIndexInfo [_ ^String catalog, ^String schema, ^String table, ^boolean unique, ^boolean approximate] (create-resultset-from-seq [])) ;; Retrieves a description of the given table's indices and statistics.
(^int getJDBCMajorVersion [_] -1) ;; Retrieves the major JDBC version number for this driver.
(^int getJDBCMinorVersion [_] -1) ;; Retrieves the minor JDBC version number for this driver.
(^int getMaxBinaryLiteralLength [_] -1) ;; Retrieves the maximum number of hex characters this database allows in an inline binary literal.
(^int getMaxCatalogNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a catalog name.
(^int getMaxCharLiteralLength [_] -1) ;; Retrieves the maximum number of characters this database allows for a character literal.
(^int getMaxColumnNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows for a column name.
(^int getMaxColumnsInGroupBy [_] -1) ;; Retrieves the maximum number of columns this database allows in a GROUP BY clause.
(^int getMaxColumnsInIndex [_] -1) ;; Retrieves the maximum number of columns this database allows in an index.
(^int getMaxColumnsInOrderBy [_] -1) ;; Retrieves the maximum number of columns this database allows in an ORDER BY clause.
(^int getMaxColumnsInSelect [_] -1) ;; Retrieves the maximum number of columns this database allows in a SELECT list.
(^int getMaxColumnsInTable [_] -1) ;; Retrieves the maximum number of columns this database allows in a table.
(^int getMaxConnections [_] -1) ;; Retrieves the maximum number of concurrent connections to this database that are possible.
(^int getMaxCursorNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a cursor name.
(^int getMaxIndexLength [_] -1) ;; Retrieves the maximum number of bytes this database allows for an index, including all of the parts of the index.
(^int getMaxProcedureNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a procedure name.
(^int getMaxRowSize [_] -1) ;; Retrieves the maximum number of bytes this database allows in a single row.
(^int getMaxSchemaNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a schema name.
(^int getMaxStatementLength [_] -1) ;; Retrieves the maximum number of characters this database allows in an SQL statement.
(^int getMaxStatements [_] -1) ;; Retrieves the maximum number of active statements to this database that can be open at the same time.
(^int getMaxTableNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows in a table name.
(^int getMaxTablesInSelect [_] -1) ;; Retrieves the maximum number of tables this database allows in a SELECT statement.
(^int getMaxUserNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows in a user name.
(^String getNumericFunctions [_] "") ;; Retrieves a commaseparated list of math functions available with this database.
(^java.sql.ResultSet getPrimaryKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the given table's primary key columns.
(^java.sql.ResultSet getProcedureColumns [_ ^String catalog, ^String schemaPattern, ^String procedureNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given catalog's stored procedure parameter and result columns.
(^java.sql.ResultSet getProcedures [_ ^String catalog, ^String schemaPattern, ^String procedureNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the stored procedures available in the given catalog.
(^String getProcedureTerm [_] "procedure") ;; Retrieves the database vendor's preferred term for "procedure".
(^int getResultSetHoldability [_] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT) ;; Retrieves this database's default holdability for ResultSet objects.
(^java.sql.RowIdLifetime getRowIdLifetime [_] java.sql.RowIdLifetime/ROWID_UNSUPPORTED) ;; Indicates whether or not this data source supports the SQL ROWID type, and if so the lifetime for which a RowId object remains valid.
(^java.sql.ResultSet getSchemas [_] (create-resultset-from-seq [])) ;; Retrieves the schema names available in this database.
(^java.sql.ResultSet getSchemas [_ ^String catalog, ^String schemaPattern] (create-resultset-from-seq [])) ;; Retrieves the schema names available in this database.
(^String getSchemaTerm [_] "schema") ;; Retrieves the database vendor's preferred term for "schema".
(^String getSearchStringEscape [_] "") ;; Retrieves the string that can be used to escape wildcard characters.
(^String getSQLKeywords [_] "") ;; Retrieves a commaseparated list of all of this database's SQL keywords that are NOT also SQL:2003 keywords.
(^int getSQLStateType [_] -1) ;; Indicates whether the SQLSTATE returned by SQLException.getSQLState is X/Open (now known as Open Group) SQL CLI or SQL:2003.
(^String getStringFunctions [_] "") ;; Retrieves a commaseparated list of string functions available with this database.
(^java.sql.ResultSet getSuperTables [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the table hierarchies defined in a particular schema in this database.
(^java.sql.ResultSet getSuperTypes [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the userdefined type (UDT) hierarchies defined in a particular schema in this database.
(^String getSystemFunctions [_] "") ;; Retrieves a commaseparated list of system functions available with this database.
(^java.sql.ResultSet getTablePrivileges [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the access rights for each table available in a catalog.
(^java.sql.ResultSet getTables [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern, ^"[Ljava.lang.String;" types] (create-resultset-from-seq [])) ;;String[] ;; Retrieves a description of the tables available in the given catalog.
(^java.sql.ResultSet getTableTypes [_] (create-resultset-from-seq [])) ;; Retrieves the table types available in this database.
(^String getTimeDateFunctions [_] "") ;; Retrieves a commaseparated list of the time and date functions available with this database.
(^java.sql.ResultSet getTypeInfo [_] (create-resultset-from-seq [])) ;; Retrieves a description of all the data types supported by this database.
(^java.sql.ResultSet getUDTs [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern, ^ints types] (create-resultset-from-seq [])) ;; Retrieves a description of the userdefined types (UDTs) defined in a particular schema.
(^String getURL [_] "") ;; Retrieves the URL for this DBMS.
(^String getUserName [_] "") ;; Retrieves the user name as known to this database.
(^java.sql.ResultSet getVersionColumns [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of a table's columns that are automatically updated when any value in a row is updated.
(^boolean insertsAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row insert can be detected by calling the method ResultSet.rowInserted.
(^boolean isCatalogAtStart [_] false) ;; Retrieves whether a catalog appears at the start of a fully qualified table name.
(^boolean isReadOnly [_] true) ;; Retrieves whether this database is in readonly mode.
(^boolean locatorsUpdateCopy [_] false) ;; Indicates whether updates made to a LOB are made on a copy or directly to the LOB.
(^boolean nullPlusNonNullIsNull [_] false) ;; Retrieves whether this database supports concatenations between NULL and nonNULL values being NULL.
(^boolean nullsAreSortedAtEnd [_] false) ;; Retrieves whether NULL values are sorted at the end regardless of sort order.
(^boolean nullsAreSortedAtStart [_] false) ;; Retrieves whether NULL values are sorted at the start regardless of sort order.
(^boolean nullsAreSortedHigh [_] false) ;; Retrieves whether NULL values are sorted high.
(^boolean nullsAreSortedLow [_] false) ;; Retrieves whether NULL values are sorted low.
(^boolean othersDeletesAreVisible [_ ^int type] false) ;; Retrieves whether deletes made by others are visible.
(^boolean othersInsertsAreVisible [_ ^int type] false) ;; Retrieves whether inserts made by others are visible.
(^boolean othersUpdatesAreVisible [_ ^int type] false) ;; Retrieves whether updates made by others are visible.
(^boolean ownDeletesAreVisible [_ ^int type] false) ;; Retrieves whether a result set's own deletes are visible.
(^boolean ownInsertsAreVisible [_ ^int type] false) ;; Retrieves whether a result set's own inserts are visible.
(^boolean ownUpdatesAreVisible [_ ^int type] false) ;; Retrieves whether for the given type of ResultSet object, the result set's own updates are visible.
(^boolean storesLowerCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in lower case.
(^boolean storesLowerCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in lower case.
(^boolean storesMixedCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in mixed case.
(^boolean storesMixedCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in mixed case.
(^boolean storesUpperCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in upper case.
(^boolean storesUpperCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in upper case.
(^boolean supportsAlterTableWithAddColumn [_] false) ;; Retrieves whether this database supports ALTER TABLE with add column.
(^boolean supportsAlterTableWithDropColumn [_] false) ;; Retrieves whether this database supports ALTER TABLE with drop column.
(^boolean supportsANSI92EntryLevelSQL [_] false) ;; Retrieves whether this database supports the ANSI92 entry level SQL grammar.
(^boolean supportsANSI92FullSQL [_] false) ;; Retrieves whether this database supports the ANSI92 full SQL grammar supported.
(^boolean supportsANSI92IntermediateSQL [_] false) ;; Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported.
(^boolean supportsBatchUpdates [_] false) ;; Retrieves whether this database supports batch updates.
(^boolean supportsCatalogsInDataManipulation [_] false) ;; Retrieves whether a catalog name can be used in a data manipulation statement.
(^boolean supportsCatalogsInIndexDefinitions [_] false) ;; Retrieves whether a catalog name can be used in an index definition statement.
(^boolean supportsCatalogsInPrivilegeDefinitions [_] false) ;; Retrieves whether a catalog name can be used in a privilege definition statement.
(^boolean supportsCatalogsInProcedureCalls [_] false) ;; Retrieves whether a catalog name can be used in a procedure call statement.
(^boolean supportsCatalogsInTableDefinitions [_] false) ;; Retrieves whether a catalog name can be used in a table definition statement.
(^boolean supportsColumnAliasing [_] false) ;; Retrieves whether this database supports column aliasing.
(^boolean supportsConvert [_] false) ;; Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion of one JDBC type to another.
(^boolean supportsConvert [_ ^int fromType, ^int toType] false) ;; Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType.
(^boolean supportsCoreSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Core SQL grammar.
(^boolean supportsCorrelatedSubqueries [_] false) ;; Retrieves whether this database supports correlated subqueries.
(^boolean supportsDataDefinitionAndDataManipulationTransactions [_] false) ;; Retrieves whether this database supports both data definition and data manipulation statements within a transaction.
(^boolean supportsDataManipulationTransactionsOnly [_] false) ;; Retrieves whether this database supports only data manipulation statements within a transaction.
(^boolean supportsDifferentTableCorrelationNames [_] false) ;; Retrieves whether, when table correlation names are supported, they are restricted to being different from the names of the tables.
(^boolean supportsExpressionsInOrderBy [_] false) ;; Retrieves whether this database supports expressions in ORDER BY lists.
(^boolean supportsExtendedSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Extended SQL grammar.
(^boolean supportsFullOuterJoins [_] false) ;; Retrieves whether this database supports full nested outer joins.
(^boolean supportsGetGeneratedKeys [_] false) ;; Retrieves whether autogenerated keys can be retrieved after a statement has been executed
(^boolean supportsGroupBy [_] false) ;; Retrieves whether this database supports some form of GROUP BY clause.
(^boolean supportsGroupByBeyondSelect [_] false) ;; Retrieves whether this database supports using columns not included in the SELECT statement in a GROUP BY clause provided that all of the columns in the SELECT statement are included in the GROUP BY clause.
(^boolean supportsGroupByUnrelated [_] false) ;; Retrieves whether this database supports using a column that is not in the SELECT statement in a GROUP BY clause.
(^boolean supportsIntegrityEnhancementFacility [_] false) ;; Retrieves whether this database supports the SQL Integrity Enhancement Facility.
(^boolean supportsLikeEscapeClause [_] false) ;; Retrieves whether this database supports specifying a LIKE escape clause.
(^boolean supportsLimitedOuterJoins [_] false) ;; Retrieves whether this database provides limited support for outer joins.
(^boolean supportsMinimumSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Minimum SQL grammar.
(^boolean supportsMixedCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and as a result stores them in mixed case.
(^boolean supportsMixedCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as a result stores them in mixed case.
(^boolean supportsMultipleOpenResults [_] false) ;; Retrieves whether it is possible to have multiple ResultSet objects returned from a CallableStatement object simultaneously.
(^boolean supportsMultipleResultSets [_] false) ;; Retrieves whether this database supports getting multiple ResultSet objects from a single call to the method execute.
(^boolean supportsMultipleTransactions [_] false) ;; Retrieves whether this database allows having multiple transactions open at once (on different connections).
(^boolean supportsNamedParameters [_] false) ;; Retrieves whether this database supports named parameters to callable statements.
(^boolean supportsNonNullableColumns [_] false) ;; Retrieves whether columns in this database may be defined as nonnullable.
(^boolean supportsOpenCursorsAcrossCommit [_] false) ;; Retrieves whether this database supports keeping cursors open across commits.
(^boolean supportsOpenCursorsAcrossRollback [_] false) ;; Retrieves whether this database supports keeping cursors open across rollbacks.
(^boolean supportsOpenStatementsAcrossCommit [_] false) ;; Retrieves whether this database supports keeping statements open across commits.
(^boolean supportsOpenStatementsAcrossRollback [_] false) ;; Retrieves whether this database supports keeping statements open across rollbacks.
(^boolean supportsOrderByUnrelated [_] false) ;; Retrieves whether this database supports using a column that is not in the SELECT statement in an ORDER BY clause.
(^boolean supportsOuterJoins [_] false) ;; Retrieves whether this database supports some form of outer join.
(^boolean supportsPositionedDelete [_] false) ;; Retrieves whether this database supports positioned DELETE statements.
(^boolean supportsPositionedUpdate [_] false) ;; Retrieves whether this database supports positioned UPDATE statements.
(^boolean supportsResultSetConcurrency [_ ^int type, ^int concurrency] false) ;; Retrieves whether this database supports the given concurrency type in combination with the given result set type.
(^boolean supportsResultSetHoldability [_ ^int holdability] false) ;; Retrieves whether this database supports the given result set holdability.
(^boolean supportsResultSetType [_ ^int type] false) ;; Retrieves whether this database supports the given result set type.
(^boolean supportsSavepoints [_] false) ;; Retrieves whether this database supports savepoints.
(^boolean supportsSchemasInDataManipulation [_] false) ;; Retrieves whether a schema name can be used in a data manipulation statement.
(^boolean supportsSchemasInIndexDefinitions [_] false) ;; Retrieves whether a schema name can be used in an index definition statement.
(^boolean supportsSchemasInPrivilegeDefinitions [_] false) ;; Retrieves whether a schema name can be used in a privilege definition statement.
(^boolean supportsSchemasInProcedureCalls [_] false) ;; Retrieves whether a schema name can be used in a procedure call statement.
(^boolean supportsSchemasInTableDefinitions [_] false) ;; Retrieves whether a schema name can be used in a table definition statement.
(^boolean supportsSelectForUpdate [_] false) ;; Retrieves whether this database supports SELECT FOR UPDATE statements.
(^boolean supportsStatementPooling [_] false) ;; Retrieves whether this database supports statement pooling.
(^boolean supportsStoredFunctionsUsingCallSyntax [_] false) ;; Retrieves whether this database supports invoking userdefined or vendor functions using the stored procedure escape syntax.
(^boolean supportsStoredProcedures [_] false) ;; Retrieves whether this database supports stored procedure calls that use the stored procedure escape syntax.
(^boolean supportsSubqueriesInComparisons [_] false) ;; Retrieves whether this database supports subqueries in comparison expressions.
(^boolean supportsSubqueriesInExists [_] false) ;; Retrieves whether this database supports subqueries in EXISTS expressions.
(^boolean supportsSubqueriesInIns [_] false) ;; Retrieves whether this database supports subqueries in IN expressions.
(^boolean supportsSubqueriesInQuantifieds [_] false) ;; Retrieves whether this database supports subqueries in quantified expressions.
(^boolean supportsTableCorrelationNames [_] false) ;; Retrieves whether this database supports table correlation names.
(^boolean supportsTransactionIsolationLevel [_ ^int level] false) ;; Retrieves whether this database supports the given transaction isolation level.
(^boolean supportsTransactions [_] false) ;; Retrieves whether this database supports transactions.
(^boolean supportsUnion [_] false) ;; Retrieves whether this database supports SQL UNION.
(^boolean supportsUnionAll [_] false) ;; Retrieves whether this database supports SQL UNION ALL.
(^boolean updatesAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row update can be detected by calling the method ResultSet.rowUpdated.
(^boolean usesLocalFilePerTable [_] false) ;; Retrieves whether this database uses a file for each table.
(^boolean usesLocalFiles [_] true)) ;; Retrieves whether this database stores tables in a local file.
(deftype Connection [binlog-state]
java.sql.Connection
(close [_]
;; Releases this Connection object's database and JDBC
;; resources immediately instead of waiting for them to be
;; automatically released.
(dosync (when-let [st (:statement @jdbc-state)] (.close st))
(alter jdbc-state assoc :closed true :connection nil)
(send-off (:binlog-state @jdbc-state) binlog/cdc-stop)))
(createStatement [t]
(dosync (if (:statement @jdbc-state)
(throwf "Close statement %s first" (:statement @jdbc-state))
(let [s (Statement.)]
(alter jdbc-state assoc :statement s)
s))))
(createStatement [t rs-type rs-cncrcy] (.createStatement t))
(createStatement [t rs-type rs-cncrcy rs-holdabilityb] (.createStatement t))
;; (^java.sql.Statement createStatement [t]) ;; Creates a Statement object for sending SQL statements to the database.
;; (^java.sql.Statement createStatement [t ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a Statement object that will generate ResultSet objects with the given type and concurrency.
;; (^java.sql.Statement createStatement [t ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability.
(getMetaData [t] (ConnectionMetadata.))
;; unimplemented
(^void clearWarnings [t]) ;; Clears all warnings reported for this Connection object.
(^void commit [t]) ;; Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
(^java.sql.Array createArrayOf [t ^String typeName, ^"[Ljava.lang.Object;" elements]) ;; Factory method for creating Array objects.
(^java.sql.Blob createBlob [t]) ;; Constructs an object that implements the Blob interface.
(^java.sql.Clob createClob [t]) ;; Constructs an object that implements the Clob interface.
(^java.sql.NClob createNClob [t]) ;; Constructs an object that implements the NClob interface.
(^java.sql.SQLXML createSQLXML [t]) ;; Constructs an object that implements the SQLXML interface.
(^java.sql.Struct createStruct [t ^String typeName, ^"[Ljava.lang.Object;" attributes]) ;; Factory method for creating Struct objects.
(^boolean getAutoCommit [t] false) ;; Retrieves the current autocommit mode for this Connection object.
(^String getCatalog [t] "") ;; Retrieves this Connection object's current catalog name.
(^java.util.Properties getClientInfo [t] {}) ;; Returns a list containing the name and current value of each client info property supported by the driver.
(^String getClientInfo [t ^String name] "") ;; Returns the value of the client info property specified by name.
(^int getHoldability [t] 0) ;; Retrieves the current holdability of ResultSet objects created using this Connection object.
(^int getTransactionIsolation [t] 0) ;; Retrieves this Connection object's current transaction isolation level.
(^java.util.Map getTypeMap [t] {}) ;; Retrieves the Map object associated with this Connection object.
(^java.sql.SQLWarning getWarnings [t]) ;; Retrieves the first warning reported by calls on this Connection object.
(^boolean isClosed [t] (:closed @jdbc-state)) ;; Retrieves whether this Connection object has been closed.
(^boolean isReadOnly [t] true) ;; Retrieves whether this Connection object is in readonly mode.
(^boolean isValid [t ^int timeout] true) ;; Returns true if the connection has not been closed and is still valid.
(^String nativeSQL [t ^String sql] sql) ;; Converts the given SQL statement into the system's native SQL grammar.
(^java.sql.CallableStatement prepareCall [t ^String sql]) ;; Creates a CallableStatement object for calling database stored procedures.
(^java.sql.CallableStatement prepareCall [t ^String sql, ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.CallableStatement prepareCall [t ^String sql, ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.PreparedStatement prepareStatement [t ^String sql]) ;; Creates a PreparedStatement object for sending parameterized SQL statements to the database.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int autoGeneratedKeys]) ;; Creates a default PreparedStatement object that has the capability to retrieve autogenerated keys.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^ints columnIndexes]) ;; Creates a default PreparedStatement object capable of returning the autogenerated keys designated by the given array.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^"[Ljava.lang.String;" columnNames]) ;; Creates a default PreparedStatement object capable of returning the autogenerated keys designated by the given array.
(^void releaseSavepoint [t ^java.sql.Savepoint savepoint]) ;; Removes the specified Savepoint and subsequent Savepoint objects from the current transaction.
(^void rollback [t]) ;; Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
(^void rollback [t ^java.sql.Savepoint savepoint]) ;; Undoes all changes made after the given Savepoint object was set.
(^void setAutoCommit [t ^boolean autoCommit]) ;; Sets this connection's autocommit mode to the given state.
(^void setCatalog [t ^String catalog]) ;; Sets the given catalog name in order to select a subspace of this Connection object's database in which to work.
(^void setClientInfo [t ^Properties properties]) ;; Sets the value of the connection's client info properties.
(^void setClientInfo [t ^String name, ^String value]) ;; Sets the value of the client info property specified by name to the value specified by value.
(^void setHoldability [t ^int holdability]) ;; Changes the default holdability of ResultSet objects created using this Connection object to the given holdability.
(^void setReadOnly [t ^boolean readOnly]) ;; Puts this connection in readonly mode as a hint to the driver to enable database optimizations.
(^java.sql.Savepoint setSavepoint [t]) ;; Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.
(^java.sql.Savepoint setSavepoint [t ^String name]) ;; Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.
(^void setTransactionIsolation [t ^int level]) ;; Attempts to change the transaction isolation level for this Connection object to the one given.
(^void setTypeMap [t ^java.util.Map map]) ;; Installs the given TypeMap object as the type map for this Connection object.
java.sql.Wrapper
(isWrapperFor [_ iface])
(unwrap [_ iface]))
(defn create-connection [binlog-index-file user pwd]
(let [state (binlog/cdc-init (fn [_]))
;; mysql-conn (sql/get-connection
;; {:classname "com.mysql.jdbc.Driver"
;; :subprotocol "mysql"
;; :subname "//localhost"
;; ;;:username user
;; :user user
;; :password <PASSWORD>})
conn (Connection. state)]
(dosync (alter jdbc-state assoc
:statement nil
:resultset nil
:connection conn
:binlog-state state
:closed false))
(set-new-queue)
(send state binlog/cdc-start binlog-index-file)
conn))
| true |
;; The MIT License
;;
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
;; provide a basic jdbc-interface for the cdc-system
(ns cdc.jdbc
(:use [clojure.pprint :only [pprint]])
(:require [cdc.mysql-binlog :as binlog]
;;[clojure.contrib.sql.internal :as sql]
)
(:import (java.sql DriverManager
DriverPropertyInfo)
(java.util Properties)
java.util.concurrent.LinkedBlockingQueue))
;; do not import the classes we are implementing
(def jdbc-state (ref {:connection nil
:statement nil
:resultset nil
:binlog-state nil
:queue nil}))
(defn set-new-queue
"set a new queue"
[]
(let [queue (LinkedBlockingQueue. 10)
event-fn #(do (println "event-fn: got" (count %) "events!")
(.put #^LinkedBlockingQueue queue %))]
(dosync (alter jdbc-state assoc :queue queue)
(send (:binlog-state @jdbc-state) assoc :event-fn event-fn))))
(defn throwf-sql-not-supported [& args]
(throw (java.sql.SQLFeatureNotSupportedException. (apply format (or args [""])))))
(defn throwf-unsupported [& args]
(throw (UnsupportedOperationException. (apply format (or args [""])))))
(defn throwf-illegal [& args]
(throw (IllegalArgumentException. (apply format (or args [""])))))
(defn throwf [& [format-string & args]]
(throw (Exception. (apply format (str "cdc.jdbc: " format-string) args))))
(defn driver-property-info [& {n :name,
v :value,
d :description,
c :choices,
r? :required}]
(let [info (DriverPropertyInfo. (str n) (str v))]
(set! (.choices info) (into-array String (map str c)))
(set! (.description info) (str d))
(set! (.required info) (boolean r?))
info))
;;(def _ee (binlog/read-binlog "/var/log/mysql/binlog.001024"))
(deftype ResultSetMetaData [schema table row]
java.sql.ResultSetMetaData
(getCatalogName [t c] "") ;; Gets the designated column's table's catalog name.
(getColumnClassName [t c] (type (nth row (dec c)))) ;;Returns the fully-qualified name of the Java class whose instances are manufactured if the method ResultSet.getObject is called to retrieve a value from the column.
(getColumnCount [t] (count row)) ;; int; Returns the number of columns in this ResultSet object.
(getColumnDisplaySize [t c] 1024) ;; int; Indicates the designated column's normal maximum width in characters.
(getColumnLabel [t c] (str c)) ;; String; Gets the designated column's suggested title for use in printouts and displays.
(getColumnName [t c] (str c)) ;; String; Get the designated column's name.
(getColumnType [t c] ;; int; Retrieves the designated column's SQL type.
(let [v (nth row (dec c))]
(cond (decimal? v) java.sql.Types/DECIMAL
(integer? v) java.sql.Types/INTEGER
(string? v) java.sql.Types/VARCHAR
:else (throwf "unsupported type: %s" (type v)))))
(getColumnTypeName [t c] (str (.getColumnType t c))) ;; String; Retrieves the designated column's database-specific type name.
(getPrecision [t c] 10) ;; int; Get the designated column's specified column size.
(getScale [t c] 10) ;; int; Gets the designated column's number of digits to right of the decimal point.
(getSchemaName [t c] schema) ;; String; Get the designated column's table's schema.
(getTableName [t c] table) ;; String; Gets the designated column's table name.
(isAutoIncrement [t c] false) ;; boolean; Indicates whether the designated column is automatically numbered.
(isCaseSensitive [t c] true) ;; boolean; Indicates whether a column's case matters.
(isCurrency [t c] false) ;; boolean; Indicates whether the designated column is a cash value.
(isDefinitelyWritable [t c] false) ;; boolean; Indicates whether a write on the designated column will definitely succeed.
(isNullable [t c] java.sql.ResultSetMetaData/columnNullableUnknown) ;; int; Indicates the nullability of values in the designated column.
(isReadOnly [t c] true) ;; boolean; Indicates whether the designated column is definitely not writable.
(isSearchable [t c] false) ;; boolean; Indicates whether the designated column can be used in a where clause.
(isSigned [t c] true) ;; boolean; Indicates whether values in the designated column are signed numbers.
(isWritable [t c] false)) ;; boolean; Indicates whether it is possible for a write on the designated column to succeed.
(defn rows-delta-type
"Return a fn that, given an event returns a seq of rows according to
the quantifier."
[{r :rows, t :type, tbl :table}]
(mapcat (condp = t
'WRITE_ROWS_EVENT #(list (conj % "insert"))
'DELETE_ROWS_EVENT #(list (conj % "delete"))
'UPDATE_ROWS_EVENT #(list (conj (first %) "update-before")
(conj (second %) "update"))
;; ignore non-data events
nil)
r))
(def _example-statement "select * from \"foo\".\"auto\" where _delta_type = ' insert'")
(defn tokenize-statement [s]
(loop [[t & more :as s] (.split s " ")
ast []]
(cond (empty? s) ast
(or (= t "\"") (= t "'"))
(recur (drop-while #(not= % t) more)
(->> more
(take-while #(not= % t))
(map #(if (= "" %) " " %))
(apply str t)
(conj ast)))
(= t "")
(recur more ast)
:else
(recur more (conj ast t)))))
(defn parse-statement [s]
(loop [[t & more :as s] (tokenize-statement s)
ast {:select nil :from nil :where nil}]
(cond (empty? s) ast
(#{"select"} t)
(recur (next more) (assoc ast :select (first more)))
(#{"from"} t)
(recur (drop-while #(not= % "where") more)
(assoc ast :from (apply str (take-while #(not= % "where") more))))
(= t "where")
(assoc ast :where (next s))
:else
(throwf-illegal "unknown statement: %s" t))))
;;(parse-statement _example-statement)
(defn really-lazy-concat
"circumvent a bug in mapcat which prevents full lazyness."
([r]
(lazy-seq (really-lazy-concat (first r) (rest r))))
([s r]
(lazy-seq
(if (empty? s)
(if (empty? r)
nil
(really-lazy-concat r))
(cons (first s)
(really-lazy-concat (rest s) r))))))
(defn create-resultset-seq
"given a simple sql expression and queue, return lazy seq of vectors
from queue."
[sql queue]
(let [{table :from [_ _ dtype] :where} (parse-statement sql)
dtype (when dtype (.replace dtype "'" ""))
[table-name schema-name] (-> table ;; for now, don't allow dots in table names
(.replace "\"" "")
(.split "\\.")
reverse)
s (->> (repeatedly #(.take queue))
(really-lazy-concat)
(filter #(and (= (:table-name %) table-name)
(= (:db-name %) schema-name)))
(map rows-delta-type)
(really-lazy-concat)
(filter (if dtype
#(= (last %) dtype)
identity))
;; in jdbc, one must call .next on the resultset to get the first row
(cons nil))]
s))
(defmacro getcol []
`(if-let [v# (nth (first ~'rows) (dec ~'i))]
(do (set! ~'was-null? false)
v#)
(do (set! ~'was-null? true)
nil)))
(defmacro getcol-by-name []
`(if-let [v# (nth (first ~'rows) (.findColumn ~'t ~'c))]
(do (set! ~'was-null? false)
v#)
(do (set! ~'was-null? true)
nil)))
;; generic resultset implementation
;; please, single threaded access only!
;; mind the gap, nothing coordinated
;; jdbc column numbering is 1<=colNum<=colCount!!!
(deftype ResultSet [#^{:volatile-mutable true} rows ;; a set of vectors of columnvalues, starting with a nil
#^{:volatile-mutable true} was-null?
sql]
java.sql.ResultSet
;; essential methods
(close [t] (dosync (set-new-queue)
(alter jdbc-state assoc :resultset nil)))
(isClosed [t])
(next [t]
;; moves cursor one row forward if there is a row
(if-let [r (next rows)]
(do (set! rows r)
true)
false))
(wasNull [t] (boolean was-null?)) ;; whether the last access to any col was sql-null
(getMetaData [t]
;; generate resultset metadata using the first row
(ResultSetMetaData. "" "" (second rows))) ;; ResultSetMetaData
(findColumn [t label]
;; returns the colnumber from the colname,
;; colnames are currently only printed numbers: "1", "2" ...
(Integer/valueOf label))
;; data getters
(^String getString [t ^int i] (getcol))
(^String getString [t ^String c] (getcol-by-name))
(^boolean getBoolean [t ^int i])
(^boolean getBoolean [t ^String c])
(^byte getByte [t ^int i] (getcol))
(^byte getByte [t ^String c] (getcol-by-name))
(^short getShort [t ^int i] (getcol))
(^short getShort [t ^String c] (getcol-by-name))
(^int getInt [t ^int i] (getcol))
(^int getInt [t ^String c] (getcol-by-name))
(^long getLong [t ^int i] (getcol))
(^long getLong [t ^String c] (getcol-by-name))
(^float getFloat [t ^int i] (getcol))
(^float getFloat [t ^String c] (getcol-by-name))
(^double getDouble [t ^int i] (getcol))
(^double getDouble [t ^String c] (getcol-by-name))
(^BigDecimal getBigDecimal [t ^int i] (java.math.BigDecimal. (str (getcol))))
(^BigDecimal getBigDecimal [t ^String c] (java.math.BigDecimal. (str (getcol-by-name))))
(^BigDecimal getBigDecimal [t ^int i ^int scale] (.getBigDecimal t i))
(^BigDecimal getBigDecimal [t ^String c ^int scale] (.getBigDecimal t c))
(^bytes getBytes [t ^int i])
(^bytes getBytes [t ^String c])
(^java.sql.Date getDate [t ^int i])
(^java.sql.Date getDate [t ^String c])
(^java.sql.Date getDate [t ^int i ^java.util.Calendar cal])
(^java.sql.Date getDate [t ^String c ^java.util.Calendar cal])
(^java.sql.Time getTime [t ^int i])
(^java.sql.Time getTime [t ^String c])
(^java.sql.Time getTime [t ^int i ^java.util.Calendar cal])
(^java.sql.Time getTime [t ^String c ^java.util.Calendar cal])
(^java.sql.Timestamp getTimestamp [t ^int i])
(^java.sql.Timestamp getTimestamp [t ^String c])
(^java.sql.Timestamp getTimestamp [t ^int i ^java.util.Calendar cal])
(^java.sql.Timestamp getTimestamp [t ^String c ^java.util.Calendar cal])
(^java.io.InputStream getAsciiStream [t ^int i])
(^java.io.InputStream getAsciiStream [t ^String c])
(^java.io.InputStream getUnicodeStream [t ^int i])
(^java.io.InputStream getUnicodeStream [t ^String c])
(^java.io.InputStream getBinaryStream [t ^int i])
(^java.io.InputStream getBinaryStream [t ^String c])
(getObject [t ^int i] (getcol))
(getObject [t ^String c] (getcol-by-name))
(getObject [t ^int i ^java.util.Map m]) ;; get object with mapping
(getObject [t ^String c ^java.util.Map m])
(^java.io.Reader getCharacterStream [t ^int i])
(^java.io.Reader getCharacterStream [t ^String c])
(^java.sql.Ref getRef [t ^int i])
(^java.sql.Ref getRef [t ^String c])
(^java.sql.Blob getBlob [t ^int i])
(^java.sql.Blob getBlob [t ^String c])
(^java.sql.Clob getClob [t ^int i])
(^java.sql.Clob getClob [t ^String c])
(^java.sql.Array getArray [t ^int i])
(^java.sql.Array getArray [t ^String c])
(^java.net.URL getURL [t ^int i])
(^java.net.URL getURL [t ^String c])
(^java.sql.NClob getNClob [t ^int i])
(^java.sql.NClob getNClob [t ^String c])
(^java.sql.SQLXML getSQLXML [t ^int i])
(^java.sql.SQLXML getSQLXML [t ^String c])
(^String getNString [t ^int i])
(^String getNString [t ^String c])
(^java.io.Reader getNCharacterStream [t ^int i])
(^java.io.Reader getNCharacterStream [t ^String c])
;; unsupported cursor methods
(getCursorName [t] (throwf-sql-not-supported))
(absolute [t r] (throwf-sql-not-supported))
(afterLast [t] (throwf-sql-not-supported))
(beforeFirst [t] (throwf-sql-not-supported))
(relative [t r] (throwf-sql-not-supported))
(isBeforeFirst [t] (throwf-sql-not-supported))
(isAfterLast [t] (throwf-sql-not-supported))
(isFirst [t] (throwf-sql-not-supported))
(isLast [t] (throwf-sql-not-supported))
(first [t] (throwf-sql-not-supported))
(last [t] (throwf-sql-not-supported))
(previous [t] (throwf-sql-not-supported))
(setFetchDirection [t dir] (throwf-sql-not-supported))
(getFetchDirection [t] 0)
(moveToInsertRow [t] (throwf-sql-not-supported))
(moveToCurrentRow [t] (throwf-sql-not-supported))
;; misc
(setFetchSize [t s])
(getFetchSize [t] 0)
(getType [t] java.sql.ResultSet/TYPE_FORWARD_ONLY)
(getConcurrency [t] java.sql.ResultSet/CONCUR_READ_ONLY)
(getRow [t] (throwf-sql-not-supported))
(getWarnings [t] )
(clearWarnings [t])
(^java.sql.RowId getRowId [t ^int i] (throwf-sql-not-supported))
(^java.sql.RowId getRowId [t ^String c] (throwf-sql-not-supported))
(getHoldability [t] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT)
;; update functions
(rowUpdated [t] (throwf-sql-not-supported))
(rowDeleted [t] (throwf-sql-not-supported))
(rowInserted [t] (throwf-sql-not-supported))
(updateRow [t] (throwf-sql-not-supported))
(deleteRow [t] (throwf-sql-not-supported))
(insertRow [t] (throwf-sql-not-supported))
(cancelRowUpdates [t] (throwf-sql-not-supported)))
(defn create-resultset [sql]
(ResultSet. (create-resultset-seq sql (:queue @jdbc-state)) false sql))
(defn create-resultset-from-seq
"Return a resultset implementation from the given seq of vectors.
a string may be supplied for debug purposes which is stored in the
resultset sql field."
[s & [sql-string]]
(ResultSet. (cons nil s) false sql-string))
(deftype Statement []
java.sql.Statement
;; essential methods
(close [t] (dosync (when-let [rs (:resultset @jdbc-state)] (.close rs))
(alter jdbc-state assoc :statement nil)))
(executeQuery [t sql]
(dosync (if-let [rs (:resultset @jdbc-state)]
(throwf "Close Resultset %s first." rs)
(let [rs (create-resultset sql)]
(alter jdbc-state assoc :resultset rs)
rs))))
(execute [t sql] (.executeQuery t sql) true)
;; we do not have autogenerated keys
(^boolean execute [t ^String sql ^int _] (.execute t sql))
(^boolean execute [t ^String sql ^ints _] (boolean (.execute t sql)))
(^boolean execute [t ^String sql ^"[Ljava.lang.String;" _] (boolean (.execute t sql)))
(getResultSet [t] (:resultset @jdbc-state))
;; misc, mostly unsupported or ignored
(addBatch [t s] (throwf-unsupported))
(executeBatch [t] (throwf-unsupported))
(cancel [t] (.close t))
(clearBatch [t] (throwf-unsupported))
(clearWarnings [t] (throwf-unsupported))
(executeUpdate [t sql] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^int _] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^ints _] (throwf-unsupported))
(^int executeUpdate [t ^String sql ^"[Ljava.lang.String;" _] (throwf-unsupported))
(getConnection [t] (:connection @jdbc-state))
(getFetchDirection [t] java.sql.ResultSet/FETCH_UNKNOWN)
(getFetchSize [t] 1)
(getGeneratedKeys [t] (throwf-sql-not-supported))
(getMaxFieldSize [t] 0) ;; unlimited
(getMoreResults [t] false) ;; only ever one rs
(getMoreResults [t _] false)
(getQueryTimeout [t] 0) ;; no timeout
(getResultSetConcurrency [t] java.sql.ResultSet/CONCUR_READ_ONLY)
(getResultSetHoldability [t] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT)
(getResultSetType [t] java.sql.ResultSet/TYPE_FORWARD_ONLY)
(getUpdateCount [t] -1)
(getWarnings [t] nil)
(isClosed [t] false)
(isPoolable [t] false)
(setCursorName [t s] (throwf-sql-not-supported))
(setEscapeProcessing [t flag]) ;; ignore
(setFetchDirection [t dir]) ;; ignore
(setFetchSize [t n]) ;; ignore
(setMaxFieldSize [t s]) ;; ignore, may be useful to obey to for varchars
(setMaxRows [t s]) ;; ignore
(setPoolable [t flag]) ;; ignore
(setQueryTimeout [t seconds]))
(deftype ConnectionMetadata []
java.sql.DatabaseMetaData
(^boolean allProceduresAreCallable [_] false) ;; Retrieves whether the current user can call all the procedures returned by the method getProcedures.
(^boolean allTablesAreSelectable [_] false) ;; Retrieves whether the current user can use all the tables returned by the method getTables in a SELECT statement.
(^boolean autoCommitFailureClosesAllResultSets [_] false) ;; Retrieves whether a SQLException while autoCommit is true inidcates that all open ResultSets are closed, even ones that are holdable.
(^boolean dataDefinitionCausesTransactionCommit [_] false) ;; Retrieves whether a data definition statement within a transaction forces the transaction to commit.
(^boolean dataDefinitionIgnoredInTransactions [_] true) ;; Retrieves whether this database ignores a data definition statement within a transaction.
(^boolean deletesAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row delete can be detected by calling the method ResultSet.rowDeleted.
(^boolean doesMaxRowSizeIncludeBlobs [_] false) ;; Retrieves whether the return value for the method getMaxRowSize includes the SQL data types LONGVARCHAR and LONGVARBINARY.
(^java.sql.ResultSet getAttributes [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern, ^String attributeNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given attribute of the given type for a userdefined type (UDT) that is available in the given schema and catalog.
(^java.sql.ResultSet getBestRowIdentifier [_ ^String catalog, ^String schema, ^String table, ^int scope, ^boolean nullable] (create-resultset-from-seq [])) ;; Retrieves a description of a table's optimal set of columns that uniquely identifies a row.
(^java.sql.ResultSet getCatalogs [_] (create-resultset-from-seq [])) ;; Retrieves the catalog names available in this database.
(^String getCatalogSeparator [_] ".") ;; Retrieves the String that this database uses as the separator between a catalog and table name.
(^String getCatalogTerm [_] "") ;; Retrieves the database vendor's preferred term for "catalog".
(^java.sql.ResultSet getClientInfoProperties [_] (create-resultset-from-seq [])) ;; Retrieves a list of the client info properties that the driver supports.
(^java.sql.ResultSet getColumnPrivileges [_ ^String catalog, ^String schema, ^String table, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the access rights for a table's columns.
(^java.sql.ResultSet getColumns [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of table columns available in the specified catalog.
(^java.sql.Connection getConnection [_] (:connection @jdbc-state)) ;; Retrieves the connection that produced this metadata object.
(^java.sql.ResultSet getCrossReference [_ ^String parentCatalog, ^String parentSchema, ^String parentTable, ^String foreignCatalog, ^String foreignSchema, ^String foreignTable] (create-resultset-from-seq [])) ;; Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
(^int getDatabaseMajorVersion [_] -1) ;; Retrieves the major version number of the underlying database.
(^int getDatabaseMinorVersion [_] -1) ;; Retrieves the minor version number of the underlying database.
(^String getDatabaseProductName [_] "mysql") ;; Retrieves the name of this database product.
(^String getDatabaseProductVersion [_] "0.1") ;; Retrieves the version number of this database product.
(^int getDefaultTransactionIsolation [_] java.sql.Connection/TRANSACTION_NONE) ;; Retrieves this database's default transaction isolation level.
(^int getDriverMajorVersion [_] 0) ;; Retrieves this JDBC driver's major version number.
(^int getDriverMinorVersion [_] 1) ;; Retrieves this JDBC driver's minor version number.
(^String getDriverName [_] "mysql binlog cdc jdbc interface") ;; Retrieves the name of this JDBC driver.
(^String getDriverVersion [_] "0.1") ;; Retrieves the version number of this JDBC driver as a String.
(^java.sql.ResultSet getExportedKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
(^String getExtraNameCharacters [_] "") ;; Retrieves all the "extra" characters that can be used in unquoted identifier names (those beyond az, AZ, 09 and _).
(^java.sql.ResultSet getFunctionColumns [_ ^String catalog, ^String schemaPattern, ^String functionNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given catalog's system or user function parameters and return type.
(^java.sql.ResultSet getFunctions [_ ^String catalog, ^String schemaPattern, ^String functionNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the system and user functions available in the given catalog.
(^String getIdentifierQuoteString [_] "\"") ;; Retrieves the string used to quote SQL identifiers.
(^java.sql.ResultSet getImportedKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the primary key columns that are referenced by the given table's foreign key columns (the primary keys imported by a table).
(^java.sql.ResultSet getIndexInfo [_ ^String catalog, ^String schema, ^String table, ^boolean unique, ^boolean approximate] (create-resultset-from-seq [])) ;; Retrieves a description of the given table's indices and statistics.
(^int getJDBCMajorVersion [_] -1) ;; Retrieves the major JDBC version number for this driver.
(^int getJDBCMinorVersion [_] -1) ;; Retrieves the minor JDBC version number for this driver.
(^int getMaxBinaryLiteralLength [_] -1) ;; Retrieves the maximum number of hex characters this database allows in an inline binary literal.
(^int getMaxCatalogNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a catalog name.
(^int getMaxCharLiteralLength [_] -1) ;; Retrieves the maximum number of characters this database allows for a character literal.
(^int getMaxColumnNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows for a column name.
(^int getMaxColumnsInGroupBy [_] -1) ;; Retrieves the maximum number of columns this database allows in a GROUP BY clause.
(^int getMaxColumnsInIndex [_] -1) ;; Retrieves the maximum number of columns this database allows in an index.
(^int getMaxColumnsInOrderBy [_] -1) ;; Retrieves the maximum number of columns this database allows in an ORDER BY clause.
(^int getMaxColumnsInSelect [_] -1) ;; Retrieves the maximum number of columns this database allows in a SELECT list.
(^int getMaxColumnsInTable [_] -1) ;; Retrieves the maximum number of columns this database allows in a table.
(^int getMaxConnections [_] -1) ;; Retrieves the maximum number of concurrent connections to this database that are possible.
(^int getMaxCursorNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a cursor name.
(^int getMaxIndexLength [_] -1) ;; Retrieves the maximum number of bytes this database allows for an index, including all of the parts of the index.
(^int getMaxProcedureNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a procedure name.
(^int getMaxRowSize [_] -1) ;; Retrieves the maximum number of bytes this database allows in a single row.
(^int getMaxSchemaNameLength [_] -1) ;; Retrieves the maximum number of characters that this database allows in a schema name.
(^int getMaxStatementLength [_] -1) ;; Retrieves the maximum number of characters this database allows in an SQL statement.
(^int getMaxStatements [_] -1) ;; Retrieves the maximum number of active statements to this database that can be open at the same time.
(^int getMaxTableNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows in a table name.
(^int getMaxTablesInSelect [_] -1) ;; Retrieves the maximum number of tables this database allows in a SELECT statement.
(^int getMaxUserNameLength [_] -1) ;; Retrieves the maximum number of characters this database allows in a user name.
(^String getNumericFunctions [_] "") ;; Retrieves a commaseparated list of math functions available with this database.
(^java.sql.ResultSet getPrimaryKeys [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of the given table's primary key columns.
(^java.sql.ResultSet getProcedureColumns [_ ^String catalog, ^String schemaPattern, ^String procedureNamePattern, ^String columnNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the given catalog's stored procedure parameter and result columns.
(^java.sql.ResultSet getProcedures [_ ^String catalog, ^String schemaPattern, ^String procedureNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the stored procedures available in the given catalog.
(^String getProcedureTerm [_] "procedure") ;; Retrieves the database vendor's preferred term for "procedure".
(^int getResultSetHoldability [_] java.sql.ResultSet/HOLD_CURSORS_OVER_COMMIT) ;; Retrieves this database's default holdability for ResultSet objects.
(^java.sql.RowIdLifetime getRowIdLifetime [_] java.sql.RowIdLifetime/ROWID_UNSUPPORTED) ;; Indicates whether or not this data source supports the SQL ROWID type, and if so the lifetime for which a RowId object remains valid.
(^java.sql.ResultSet getSchemas [_] (create-resultset-from-seq [])) ;; Retrieves the schema names available in this database.
(^java.sql.ResultSet getSchemas [_ ^String catalog, ^String schemaPattern] (create-resultset-from-seq [])) ;; Retrieves the schema names available in this database.
(^String getSchemaTerm [_] "schema") ;; Retrieves the database vendor's preferred term for "schema".
(^String getSearchStringEscape [_] "") ;; Retrieves the string that can be used to escape wildcard characters.
(^String getSQLKeywords [_] "") ;; Retrieves a commaseparated list of all of this database's SQL keywords that are NOT also SQL:2003 keywords.
(^int getSQLStateType [_] -1) ;; Indicates whether the SQLSTATE returned by SQLException.getSQLState is X/Open (now known as Open Group) SQL CLI or SQL:2003.
(^String getStringFunctions [_] "") ;; Retrieves a commaseparated list of string functions available with this database.
(^java.sql.ResultSet getSuperTables [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the table hierarchies defined in a particular schema in this database.
(^java.sql.ResultSet getSuperTypes [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the userdefined type (UDT) hierarchies defined in a particular schema in this database.
(^String getSystemFunctions [_] "") ;; Retrieves a commaseparated list of system functions available with this database.
(^java.sql.ResultSet getTablePrivileges [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern] (create-resultset-from-seq [])) ;; Retrieves a description of the access rights for each table available in a catalog.
(^java.sql.ResultSet getTables [_ ^String catalog, ^String schemaPattern, ^String tableNamePattern, ^"[Ljava.lang.String;" types] (create-resultset-from-seq [])) ;;String[] ;; Retrieves a description of the tables available in the given catalog.
(^java.sql.ResultSet getTableTypes [_] (create-resultset-from-seq [])) ;; Retrieves the table types available in this database.
(^String getTimeDateFunctions [_] "") ;; Retrieves a commaseparated list of the time and date functions available with this database.
(^java.sql.ResultSet getTypeInfo [_] (create-resultset-from-seq [])) ;; Retrieves a description of all the data types supported by this database.
(^java.sql.ResultSet getUDTs [_ ^String catalog, ^String schemaPattern, ^String typeNamePattern, ^ints types] (create-resultset-from-seq [])) ;; Retrieves a description of the userdefined types (UDTs) defined in a particular schema.
(^String getURL [_] "") ;; Retrieves the URL for this DBMS.
(^String getUserName [_] "") ;; Retrieves the user name as known to this database.
(^java.sql.ResultSet getVersionColumns [_ ^String catalog, ^String schema, ^String table] (create-resultset-from-seq [])) ;; Retrieves a description of a table's columns that are automatically updated when any value in a row is updated.
(^boolean insertsAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row insert can be detected by calling the method ResultSet.rowInserted.
(^boolean isCatalogAtStart [_] false) ;; Retrieves whether a catalog appears at the start of a fully qualified table name.
(^boolean isReadOnly [_] true) ;; Retrieves whether this database is in readonly mode.
(^boolean locatorsUpdateCopy [_] false) ;; Indicates whether updates made to a LOB are made on a copy or directly to the LOB.
(^boolean nullPlusNonNullIsNull [_] false) ;; Retrieves whether this database supports concatenations between NULL and nonNULL values being NULL.
(^boolean nullsAreSortedAtEnd [_] false) ;; Retrieves whether NULL values are sorted at the end regardless of sort order.
(^boolean nullsAreSortedAtStart [_] false) ;; Retrieves whether NULL values are sorted at the start regardless of sort order.
(^boolean nullsAreSortedHigh [_] false) ;; Retrieves whether NULL values are sorted high.
(^boolean nullsAreSortedLow [_] false) ;; Retrieves whether NULL values are sorted low.
(^boolean othersDeletesAreVisible [_ ^int type] false) ;; Retrieves whether deletes made by others are visible.
(^boolean othersInsertsAreVisible [_ ^int type] false) ;; Retrieves whether inserts made by others are visible.
(^boolean othersUpdatesAreVisible [_ ^int type] false) ;; Retrieves whether updates made by others are visible.
(^boolean ownDeletesAreVisible [_ ^int type] false) ;; Retrieves whether a result set's own deletes are visible.
(^boolean ownInsertsAreVisible [_ ^int type] false) ;; Retrieves whether a result set's own inserts are visible.
(^boolean ownUpdatesAreVisible [_ ^int type] false) ;; Retrieves whether for the given type of ResultSet object, the result set's own updates are visible.
(^boolean storesLowerCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in lower case.
(^boolean storesLowerCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in lower case.
(^boolean storesMixedCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in mixed case.
(^boolean storesMixedCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in mixed case.
(^boolean storesUpperCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in upper case.
(^boolean storesUpperCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in upper case.
(^boolean supportsAlterTableWithAddColumn [_] false) ;; Retrieves whether this database supports ALTER TABLE with add column.
(^boolean supportsAlterTableWithDropColumn [_] false) ;; Retrieves whether this database supports ALTER TABLE with drop column.
(^boolean supportsANSI92EntryLevelSQL [_] false) ;; Retrieves whether this database supports the ANSI92 entry level SQL grammar.
(^boolean supportsANSI92FullSQL [_] false) ;; Retrieves whether this database supports the ANSI92 full SQL grammar supported.
(^boolean supportsANSI92IntermediateSQL [_] false) ;; Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported.
(^boolean supportsBatchUpdates [_] false) ;; Retrieves whether this database supports batch updates.
(^boolean supportsCatalogsInDataManipulation [_] false) ;; Retrieves whether a catalog name can be used in a data manipulation statement.
(^boolean supportsCatalogsInIndexDefinitions [_] false) ;; Retrieves whether a catalog name can be used in an index definition statement.
(^boolean supportsCatalogsInPrivilegeDefinitions [_] false) ;; Retrieves whether a catalog name can be used in a privilege definition statement.
(^boolean supportsCatalogsInProcedureCalls [_] false) ;; Retrieves whether a catalog name can be used in a procedure call statement.
(^boolean supportsCatalogsInTableDefinitions [_] false) ;; Retrieves whether a catalog name can be used in a table definition statement.
(^boolean supportsColumnAliasing [_] false) ;; Retrieves whether this database supports column aliasing.
(^boolean supportsConvert [_] false) ;; Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion of one JDBC type to another.
(^boolean supportsConvert [_ ^int fromType, ^int toType] false) ;; Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType.
(^boolean supportsCoreSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Core SQL grammar.
(^boolean supportsCorrelatedSubqueries [_] false) ;; Retrieves whether this database supports correlated subqueries.
(^boolean supportsDataDefinitionAndDataManipulationTransactions [_] false) ;; Retrieves whether this database supports both data definition and data manipulation statements within a transaction.
(^boolean supportsDataManipulationTransactionsOnly [_] false) ;; Retrieves whether this database supports only data manipulation statements within a transaction.
(^boolean supportsDifferentTableCorrelationNames [_] false) ;; Retrieves whether, when table correlation names are supported, they are restricted to being different from the names of the tables.
(^boolean supportsExpressionsInOrderBy [_] false) ;; Retrieves whether this database supports expressions in ORDER BY lists.
(^boolean supportsExtendedSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Extended SQL grammar.
(^boolean supportsFullOuterJoins [_] false) ;; Retrieves whether this database supports full nested outer joins.
(^boolean supportsGetGeneratedKeys [_] false) ;; Retrieves whether autogenerated keys can be retrieved after a statement has been executed
(^boolean supportsGroupBy [_] false) ;; Retrieves whether this database supports some form of GROUP BY clause.
(^boolean supportsGroupByBeyondSelect [_] false) ;; Retrieves whether this database supports using columns not included in the SELECT statement in a GROUP BY clause provided that all of the columns in the SELECT statement are included in the GROUP BY clause.
(^boolean supportsGroupByUnrelated [_] false) ;; Retrieves whether this database supports using a column that is not in the SELECT statement in a GROUP BY clause.
(^boolean supportsIntegrityEnhancementFacility [_] false) ;; Retrieves whether this database supports the SQL Integrity Enhancement Facility.
(^boolean supportsLikeEscapeClause [_] false) ;; Retrieves whether this database supports specifying a LIKE escape clause.
(^boolean supportsLimitedOuterJoins [_] false) ;; Retrieves whether this database provides limited support for outer joins.
(^boolean supportsMinimumSQLGrammar [_] false) ;; Retrieves whether this database supports the ODBC Minimum SQL grammar.
(^boolean supportsMixedCaseIdentifiers [_] false) ;; Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and as a result stores them in mixed case.
(^boolean supportsMixedCaseQuotedIdentifiers [_] false) ;; Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as a result stores them in mixed case.
(^boolean supportsMultipleOpenResults [_] false) ;; Retrieves whether it is possible to have multiple ResultSet objects returned from a CallableStatement object simultaneously.
(^boolean supportsMultipleResultSets [_] false) ;; Retrieves whether this database supports getting multiple ResultSet objects from a single call to the method execute.
(^boolean supportsMultipleTransactions [_] false) ;; Retrieves whether this database allows having multiple transactions open at once (on different connections).
(^boolean supportsNamedParameters [_] false) ;; Retrieves whether this database supports named parameters to callable statements.
(^boolean supportsNonNullableColumns [_] false) ;; Retrieves whether columns in this database may be defined as nonnullable.
(^boolean supportsOpenCursorsAcrossCommit [_] false) ;; Retrieves whether this database supports keeping cursors open across commits.
(^boolean supportsOpenCursorsAcrossRollback [_] false) ;; Retrieves whether this database supports keeping cursors open across rollbacks.
(^boolean supportsOpenStatementsAcrossCommit [_] false) ;; Retrieves whether this database supports keeping statements open across commits.
(^boolean supportsOpenStatementsAcrossRollback [_] false) ;; Retrieves whether this database supports keeping statements open across rollbacks.
(^boolean supportsOrderByUnrelated [_] false) ;; Retrieves whether this database supports using a column that is not in the SELECT statement in an ORDER BY clause.
(^boolean supportsOuterJoins [_] false) ;; Retrieves whether this database supports some form of outer join.
(^boolean supportsPositionedDelete [_] false) ;; Retrieves whether this database supports positioned DELETE statements.
(^boolean supportsPositionedUpdate [_] false) ;; Retrieves whether this database supports positioned UPDATE statements.
(^boolean supportsResultSetConcurrency [_ ^int type, ^int concurrency] false) ;; Retrieves whether this database supports the given concurrency type in combination with the given result set type.
(^boolean supportsResultSetHoldability [_ ^int holdability] false) ;; Retrieves whether this database supports the given result set holdability.
(^boolean supportsResultSetType [_ ^int type] false) ;; Retrieves whether this database supports the given result set type.
(^boolean supportsSavepoints [_] false) ;; Retrieves whether this database supports savepoints.
(^boolean supportsSchemasInDataManipulation [_] false) ;; Retrieves whether a schema name can be used in a data manipulation statement.
(^boolean supportsSchemasInIndexDefinitions [_] false) ;; Retrieves whether a schema name can be used in an index definition statement.
(^boolean supportsSchemasInPrivilegeDefinitions [_] false) ;; Retrieves whether a schema name can be used in a privilege definition statement.
(^boolean supportsSchemasInProcedureCalls [_] false) ;; Retrieves whether a schema name can be used in a procedure call statement.
(^boolean supportsSchemasInTableDefinitions [_] false) ;; Retrieves whether a schema name can be used in a table definition statement.
(^boolean supportsSelectForUpdate [_] false) ;; Retrieves whether this database supports SELECT FOR UPDATE statements.
(^boolean supportsStatementPooling [_] false) ;; Retrieves whether this database supports statement pooling.
(^boolean supportsStoredFunctionsUsingCallSyntax [_] false) ;; Retrieves whether this database supports invoking userdefined or vendor functions using the stored procedure escape syntax.
(^boolean supportsStoredProcedures [_] false) ;; Retrieves whether this database supports stored procedure calls that use the stored procedure escape syntax.
(^boolean supportsSubqueriesInComparisons [_] false) ;; Retrieves whether this database supports subqueries in comparison expressions.
(^boolean supportsSubqueriesInExists [_] false) ;; Retrieves whether this database supports subqueries in EXISTS expressions.
(^boolean supportsSubqueriesInIns [_] false) ;; Retrieves whether this database supports subqueries in IN expressions.
(^boolean supportsSubqueriesInQuantifieds [_] false) ;; Retrieves whether this database supports subqueries in quantified expressions.
(^boolean supportsTableCorrelationNames [_] false) ;; Retrieves whether this database supports table correlation names.
(^boolean supportsTransactionIsolationLevel [_ ^int level] false) ;; Retrieves whether this database supports the given transaction isolation level.
(^boolean supportsTransactions [_] false) ;; Retrieves whether this database supports transactions.
(^boolean supportsUnion [_] false) ;; Retrieves whether this database supports SQL UNION.
(^boolean supportsUnionAll [_] false) ;; Retrieves whether this database supports SQL UNION ALL.
(^boolean updatesAreDetected [_ ^int type] false) ;; Retrieves whether or not a visible row update can be detected by calling the method ResultSet.rowUpdated.
(^boolean usesLocalFilePerTable [_] false) ;; Retrieves whether this database uses a file for each table.
(^boolean usesLocalFiles [_] true)) ;; Retrieves whether this database stores tables in a local file.
(deftype Connection [binlog-state]
java.sql.Connection
(close [_]
;; Releases this Connection object's database and JDBC
;; resources immediately instead of waiting for them to be
;; automatically released.
(dosync (when-let [st (:statement @jdbc-state)] (.close st))
(alter jdbc-state assoc :closed true :connection nil)
(send-off (:binlog-state @jdbc-state) binlog/cdc-stop)))
(createStatement [t]
(dosync (if (:statement @jdbc-state)
(throwf "Close statement %s first" (:statement @jdbc-state))
(let [s (Statement.)]
(alter jdbc-state assoc :statement s)
s))))
(createStatement [t rs-type rs-cncrcy] (.createStatement t))
(createStatement [t rs-type rs-cncrcy rs-holdabilityb] (.createStatement t))
;; (^java.sql.Statement createStatement [t]) ;; Creates a Statement object for sending SQL statements to the database.
;; (^java.sql.Statement createStatement [t ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a Statement object that will generate ResultSet objects with the given type and concurrency.
;; (^java.sql.Statement createStatement [t ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a Statement object that will generate ResultSet objects with the given type, concurrency, and holdability.
(getMetaData [t] (ConnectionMetadata.))
;; unimplemented
(^void clearWarnings [t]) ;; Clears all warnings reported for this Connection object.
(^void commit [t]) ;; Makes all changes made since the previous commit/rollback permanent and releases any database locks currently held by this Connection object.
(^java.sql.Array createArrayOf [t ^String typeName, ^"[Ljava.lang.Object;" elements]) ;; Factory method for creating Array objects.
(^java.sql.Blob createBlob [t]) ;; Constructs an object that implements the Blob interface.
(^java.sql.Clob createClob [t]) ;; Constructs an object that implements the Clob interface.
(^java.sql.NClob createNClob [t]) ;; Constructs an object that implements the NClob interface.
(^java.sql.SQLXML createSQLXML [t]) ;; Constructs an object that implements the SQLXML interface.
(^java.sql.Struct createStruct [t ^String typeName, ^"[Ljava.lang.Object;" attributes]) ;; Factory method for creating Struct objects.
(^boolean getAutoCommit [t] false) ;; Retrieves the current autocommit mode for this Connection object.
(^String getCatalog [t] "") ;; Retrieves this Connection object's current catalog name.
(^java.util.Properties getClientInfo [t] {}) ;; Returns a list containing the name and current value of each client info property supported by the driver.
(^String getClientInfo [t ^String name] "") ;; Returns the value of the client info property specified by name.
(^int getHoldability [t] 0) ;; Retrieves the current holdability of ResultSet objects created using this Connection object.
(^int getTransactionIsolation [t] 0) ;; Retrieves this Connection object's current transaction isolation level.
(^java.util.Map getTypeMap [t] {}) ;; Retrieves the Map object associated with this Connection object.
(^java.sql.SQLWarning getWarnings [t]) ;; Retrieves the first warning reported by calls on this Connection object.
(^boolean isClosed [t] (:closed @jdbc-state)) ;; Retrieves whether this Connection object has been closed.
(^boolean isReadOnly [t] true) ;; Retrieves whether this Connection object is in readonly mode.
(^boolean isValid [t ^int timeout] true) ;; Returns true if the connection has not been closed and is still valid.
(^String nativeSQL [t ^String sql] sql) ;; Converts the given SQL statement into the system's native SQL grammar.
(^java.sql.CallableStatement prepareCall [t ^String sql]) ;; Creates a CallableStatement object for calling database stored procedures.
(^java.sql.CallableStatement prepareCall [t ^String sql, ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.CallableStatement prepareCall [t ^String sql, ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a CallableStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.PreparedStatement prepareStatement [t ^String sql]) ;; Creates a PreparedStatement object for sending parameterized SQL statements to the database.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int autoGeneratedKeys]) ;; Creates a default PreparedStatement object that has the capability to retrieve autogenerated keys.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^ints columnIndexes]) ;; Creates a default PreparedStatement object capable of returning the autogenerated keys designated by the given array.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int resultSetType, ^int resultSetConcurrency]) ;; Creates a PreparedStatement object that will generate ResultSet objects with the given type and concurrency.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^int resultSetType, ^int resultSetConcurrency, ^int resultSetHoldability]) ;; Creates a PreparedStatement object that will generate ResultSet objects with the given type, concurrency, and holdability.
(^java.sql.PreparedStatement prepareStatement [t ^String sql, ^"[Ljava.lang.String;" columnNames]) ;; Creates a default PreparedStatement object capable of returning the autogenerated keys designated by the given array.
(^void releaseSavepoint [t ^java.sql.Savepoint savepoint]) ;; Removes the specified Savepoint and subsequent Savepoint objects from the current transaction.
(^void rollback [t]) ;; Undoes all changes made in the current transaction and releases any database locks currently held by this Connection object.
(^void rollback [t ^java.sql.Savepoint savepoint]) ;; Undoes all changes made after the given Savepoint object was set.
(^void setAutoCommit [t ^boolean autoCommit]) ;; Sets this connection's autocommit mode to the given state.
(^void setCatalog [t ^String catalog]) ;; Sets the given catalog name in order to select a subspace of this Connection object's database in which to work.
(^void setClientInfo [t ^Properties properties]) ;; Sets the value of the connection's client info properties.
(^void setClientInfo [t ^String name, ^String value]) ;; Sets the value of the client info property specified by name to the value specified by value.
(^void setHoldability [t ^int holdability]) ;; Changes the default holdability of ResultSet objects created using this Connection object to the given holdability.
(^void setReadOnly [t ^boolean readOnly]) ;; Puts this connection in readonly mode as a hint to the driver to enable database optimizations.
(^java.sql.Savepoint setSavepoint [t]) ;; Creates an unnamed savepoint in the current transaction and returns the new Savepoint object that represents it.
(^java.sql.Savepoint setSavepoint [t ^String name]) ;; Creates a savepoint with the given name in the current transaction and returns the new Savepoint object that represents it.
(^void setTransactionIsolation [t ^int level]) ;; Attempts to change the transaction isolation level for this Connection object to the one given.
(^void setTypeMap [t ^java.util.Map map]) ;; Installs the given TypeMap object as the type map for this Connection object.
java.sql.Wrapper
(isWrapperFor [_ iface])
(unwrap [_ iface]))
(defn create-connection [binlog-index-file user pwd]
(let [state (binlog/cdc-init (fn [_]))
;; mysql-conn (sql/get-connection
;; {:classname "com.mysql.jdbc.Driver"
;; :subprotocol "mysql"
;; :subname "//localhost"
;; ;;:username user
;; :user user
;; :password PI:PASSWORD:<PASSWORD>END_PI})
conn (Connection. state)]
(dosync (alter jdbc-state assoc
:statement nil
:resultset nil
:connection conn
:binlog-state state
:closed false))
(set-new-queue)
(send state binlog/cdc-start binlog-index-file)
conn))
|
[
{
"context": ";; Copyright (c) 2017-present Konrad Grzanek\n;; Created 2017-04-06\n\n(ns kongra.prelude.io\n (:",
"end": 44,
"score": 0.9998573660850525,
"start": 30,
"tag": "NAME",
"value": "Konrad Grzanek"
}
] |
data/train/clojure/803425055852bab40944e007d337ea320c571aa5io.clj
|
harshp8l/deep-learning-lang-detection
| 84 |
;; Copyright (c) 2017-present Konrad Grzanek
;; Created 2017-04-06
(ns kongra.prelude.io
(:require [kongra.ch :refer :all])
(:import [java.io InputStream ByteArrayInputStream
File FileInputStream]
[java.nio.charset Charset]))
;; SYSTEM-WIDE CHARACTER ENCODING
(def ^Charset ENCODING (chC Charset (Charset/forName "UTF-8")))
;; CONVERSION TO InputStream
(defchC chInputStream InputStream) (regch chInputStream)
(defprotocol ToInputStream
(^InputStream input-stream [this]))
(extend-type InputStream
ToInputStream
(input-stream [this]
(chInputStream this)))
(extend-type String
ToInputStream
(input-stream [this]
(chInputStream (-> this (.getBytes ENCODING) ByteArrayInputStream.))))
(extend-type File
ToInputStream
(input-stream [this]
(chInputStream (FileInputStream. this))))
|
107692
|
;; Copyright (c) 2017-present <NAME>
;; Created 2017-04-06
(ns kongra.prelude.io
(:require [kongra.ch :refer :all])
(:import [java.io InputStream ByteArrayInputStream
File FileInputStream]
[java.nio.charset Charset]))
;; SYSTEM-WIDE CHARACTER ENCODING
(def ^Charset ENCODING (chC Charset (Charset/forName "UTF-8")))
;; CONVERSION TO InputStream
(defchC chInputStream InputStream) (regch chInputStream)
(defprotocol ToInputStream
(^InputStream input-stream [this]))
(extend-type InputStream
ToInputStream
(input-stream [this]
(chInputStream this)))
(extend-type String
ToInputStream
(input-stream [this]
(chInputStream (-> this (.getBytes ENCODING) ByteArrayInputStream.))))
(extend-type File
ToInputStream
(input-stream [this]
(chInputStream (FileInputStream. this))))
| true |
;; Copyright (c) 2017-present PI:NAME:<NAME>END_PI
;; Created 2017-04-06
(ns kongra.prelude.io
(:require [kongra.ch :refer :all])
(:import [java.io InputStream ByteArrayInputStream
File FileInputStream]
[java.nio.charset Charset]))
;; SYSTEM-WIDE CHARACTER ENCODING
(def ^Charset ENCODING (chC Charset (Charset/forName "UTF-8")))
;; CONVERSION TO InputStream
(defchC chInputStream InputStream) (regch chInputStream)
(defprotocol ToInputStream
(^InputStream input-stream [this]))
(extend-type InputStream
ToInputStream
(input-stream [this]
(chInputStream this)))
(extend-type String
ToInputStream
(input-stream [this]
(chInputStream (-> this (.getBytes ENCODING) ByteArrayInputStream.))))
(extend-type File
ToInputStream
(input-stream [this]
(chInputStream (FileInputStream. this))))
|
[
{
"context": "ken\")\n api/from-token (constantly \"barfoo\")]\n\n (let [system (run {})\n ",
"end": 983,
"score": 0.9636955261230469,
"start": 977,
"tag": "PASSWORD",
"value": "barfoo"
}
] |
test/org/zalando/stups/kio/integration_test/api_test.clj
|
oporkka/kio
| 25 |
(ns org.zalando.stups.kio.integration-test.api-test
(:require [com.stuartsierra.component :as component]
[clojure.test :refer [deftest is testing]]
[midje.sweet :refer :all]
[clj-http.client :as http]
[cheshire.core :as json]
[org.zalando.stups.kio.core :refer [run]]
[org.zalando.stups.kio.api :as api]
[org.zalando.stups.friboo.system.oauth2 :as oauth2]))
(defn api-url [& path]
(let [url (apply str "http://localhost:8080" path)]
(println (str "[request] " url))
url))
(defrecord NoTokenRefresher
[configuration]
com.stuartsierra.component/Lifecycle
(start [this] this)
(stop [this] this))
(deftest ^:integration integration-test
(with-redefs [api/require-write-authorization (constantly nil)
oauth2/map->OAuth2TokenRefresher map->NoTokenRefresher
oauth2/access-token (constantly "token")
api/from-token (constantly "barfoo")]
(let [system (run {})
request-options {:throw-exceptions false
:content-type :json}
application {:team_id "bar"
:active true
:name "FooBar"}
version {:notes "My new version"
:artifact "docker://stups/foo1:1.0-master"}
version-req (->
request-options
(assoc :body (json/encode version))
(assoc :as :json))]
(against-background [(before :contents (http/put
(api-url "/apps/foo1")
(assoc request-options :body (json/encode application))))
(after :contents (component/stop system))]
(facts "API"
(facts "it validates version numbers correctly"
(fact "1.0-master works"
(http/put
(api-url "/apps/foo1/versions/1.0-master")
version-req) => (contains {:status 200}))
(fact "1.0 works"
(http/put
(api-url "/apps/foo1/versions/1.0")
version-req) => (contains {:status 200}))
(fact "1..-..1 does not work"
(http/put
(api-url "/apps/foo1/versions/1..-..1")
version-req) => (contains {:status 400}))))))))
|
57382
|
(ns org.zalando.stups.kio.integration-test.api-test
(:require [com.stuartsierra.component :as component]
[clojure.test :refer [deftest is testing]]
[midje.sweet :refer :all]
[clj-http.client :as http]
[cheshire.core :as json]
[org.zalando.stups.kio.core :refer [run]]
[org.zalando.stups.kio.api :as api]
[org.zalando.stups.friboo.system.oauth2 :as oauth2]))
(defn api-url [& path]
(let [url (apply str "http://localhost:8080" path)]
(println (str "[request] " url))
url))
(defrecord NoTokenRefresher
[configuration]
com.stuartsierra.component/Lifecycle
(start [this] this)
(stop [this] this))
(deftest ^:integration integration-test
(with-redefs [api/require-write-authorization (constantly nil)
oauth2/map->OAuth2TokenRefresher map->NoTokenRefresher
oauth2/access-token (constantly "token")
api/from-token (constantly "<PASSWORD>")]
(let [system (run {})
request-options {:throw-exceptions false
:content-type :json}
application {:team_id "bar"
:active true
:name "FooBar"}
version {:notes "My new version"
:artifact "docker://stups/foo1:1.0-master"}
version-req (->
request-options
(assoc :body (json/encode version))
(assoc :as :json))]
(against-background [(before :contents (http/put
(api-url "/apps/foo1")
(assoc request-options :body (json/encode application))))
(after :contents (component/stop system))]
(facts "API"
(facts "it validates version numbers correctly"
(fact "1.0-master works"
(http/put
(api-url "/apps/foo1/versions/1.0-master")
version-req) => (contains {:status 200}))
(fact "1.0 works"
(http/put
(api-url "/apps/foo1/versions/1.0")
version-req) => (contains {:status 200}))
(fact "1..-..1 does not work"
(http/put
(api-url "/apps/foo1/versions/1..-..1")
version-req) => (contains {:status 400}))))))))
| true |
(ns org.zalando.stups.kio.integration-test.api-test
(:require [com.stuartsierra.component :as component]
[clojure.test :refer [deftest is testing]]
[midje.sweet :refer :all]
[clj-http.client :as http]
[cheshire.core :as json]
[org.zalando.stups.kio.core :refer [run]]
[org.zalando.stups.kio.api :as api]
[org.zalando.stups.friboo.system.oauth2 :as oauth2]))
(defn api-url [& path]
(let [url (apply str "http://localhost:8080" path)]
(println (str "[request] " url))
url))
(defrecord NoTokenRefresher
[configuration]
com.stuartsierra.component/Lifecycle
(start [this] this)
(stop [this] this))
(deftest ^:integration integration-test
(with-redefs [api/require-write-authorization (constantly nil)
oauth2/map->OAuth2TokenRefresher map->NoTokenRefresher
oauth2/access-token (constantly "token")
api/from-token (constantly "PI:PASSWORD:<PASSWORD>END_PI")]
(let [system (run {})
request-options {:throw-exceptions false
:content-type :json}
application {:team_id "bar"
:active true
:name "FooBar"}
version {:notes "My new version"
:artifact "docker://stups/foo1:1.0-master"}
version-req (->
request-options
(assoc :body (json/encode version))
(assoc :as :json))]
(against-background [(before :contents (http/put
(api-url "/apps/foo1")
(assoc request-options :body (json/encode application))))
(after :contents (component/stop system))]
(facts "API"
(facts "it validates version numbers correctly"
(fact "1.0-master works"
(http/put
(api-url "/apps/foo1/versions/1.0-master")
version-req) => (contains {:status 200}))
(fact "1.0 works"
(http/put
(api-url "/apps/foo1/versions/1.0")
version-req) => (contains {:status 200}))
(fact "1..-..1 does not work"
(http/put
(api-url "/apps/foo1/versions/1..-..1")
version-req) => (contains {:status 400}))))))))
|
[
{
"context": " able to change that -- see\n;; https://github.com/metabase/metabase/issues/3506\n(tx/defdataset tiny-int-ones",
"end": 3187,
"score": 0.9992554187774658,
"start": 3179,
"tag": "USERNAME",
"value": "metabase"
},
{
"context": "riginal bug can be found here: https://github.com/metabase/metabase/issues/8262. The MySQL driver code\n ",
"end": 9913,
"score": 0.9717204570770264,
"start": 9905,
"tag": "USERNAME",
"value": "metabase"
},
{
"context": "localhost\", :port \"3306\", :user \"cam\", :password \"bad-password\"})\n\n(def ^:private sample-jdbc-spec\n {:password ",
"end": 10567,
"score": 0.9994626641273499,
"start": 10555,
"tag": "PASSWORD",
"value": "bad-password"
},
{
"context": "rivate sample-jdbc-spec\n {:password \"bad-password\"\n :characterSetResults \"UTF8\"\n :characterEnc",
"end": 10642,
"score": 0.9994903206825256,
"start": 10630,
"tag": "PASSWORD",
"value": "bad-password"
},
{
"context": "t/with-env-keys-renamed-by #(str/replace-first % \"mb-mysql-ssl-test\" \"mb-mysql-test\")\n (string-extracts-test",
"end": 18435,
"score": 0.5854004621505737,
"start": 18418,
"tag": "KEY",
"value": "mb-mysql-ssl-test"
},
{
"context": "d-by #(str/replace-first % \"mb-mysql-ssl-test\" \"mb-mysql-test\")\n (string-extracts-test/test-breakout))",
"end": 18451,
"score": 0.6640217900276184,
"start": 18441,
"tag": "KEY",
"value": "mysql-test"
}
] |
c#-metabase/test/metabase/driver/mysql_test.clj
|
hanakhry/Crime_Admin
| 0 |
(ns metabase.driver.mysql-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[honeysql.core :as hsql]
[java-time :as t]
[metabase.db.metadata-queries :as metadata-queries]
[metabase.driver :as driver]
[metabase.driver.mysql :as mysql]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.table :refer [Table]]
[metabase.query-processor :as qp]
;; used for one SSL with PEM connectivity test
[metabase.query-processor-test.string-extracts-test :as string-extracts-test]
[metabase.sync :as sync]
[metabase.sync.analyze.fingerprint :as fingerprint]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.honeysql-extensions :as hx]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]
[toucan.util.test :as tt]))
(deftest all-zero-dates-test
(mt/test-driver :mysql
(testing (str "MySQL allows 0000-00-00 dates, but JDBC does not; make sure that MySQL is converting them to NULL "
"when returning them like we asked")
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(try
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS all_zero_dates;"
"CREATE DATABASE all_zero_dates;"]]
(jdbc/execute! spec [sql]))
;; Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "all_zero_dates"})
spec (-> (sql-jdbc.conn/connection-details->spec :mysql details)
;; allow inserting dates where value is '0000-00-00' -- this is disallowed by default on newer
;; versions of MySQL, but we still want to test that we can handle it correctly for older ones
(assoc :sessionVariables "sql_mode='ALLOW_INVALID_DATES'"))]
(doseq [sql ["CREATE TABLE `exciting-moments-in-history` (`id` integer, `moment` timestamp);"
"INSERT INTO `exciting-moments-in-history` (`id`, `moment`) VALUES (1, '0000-00-00');"]]
(jdbc/execute! spec [sql]))
;; create & sync MB DB
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(mt/with-db database
;; run the query
(is (= [[1 nil]]
(mt/rows
(mt/run-mbql-query exciting-moments-in-history))))))))))))
;; Test how TINYINT(1) columns are interpreted. By default, they should be interpreted as integers, but with the
;; correct additional options, we should be able to change that -- see
;; https://github.com/metabase/metabase/issues/3506
(tx/defdataset tiny-int-ones
[["number-of-cans"
[{:field-name "thing", :base-type :type/Text}
{:field-name "number-of-cans", :base-type {:native "tinyint(1)"}, :effective-type :type/Integer}]
[["Six Pack" 6]
["Toucan" 2]
["Empty Vending Machine" 0]]]])
(defn- db->fields [db]
(let [table-ids (db/select-ids 'Table :db_id (u/the-id db))]
(set (map (partial into {}) (db/select [Field :name :base_type :semantic_type] :table_id [:in table-ids])))))
(deftest tiny-int-1-test
(mt/test-driver :mysql
(mt/dataset tiny-int-ones
;; trigger a full sync on this database so fields are categorized correctly
(sync/sync-database! (mt/db))
(testing "By default TINYINT(1) should be a boolean"
(is (= #{{:name "number-of-cans", :base_type :type/Boolean, :semantic_type :type/Category}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields (mt/db)))))
(testing "if someone says specifies `tinyInt1isBit=false`, it should come back as a number instead"
(tt/with-temp Database [db {:engine "mysql"
:details (assoc (:details (mt/db))
:additional-options "tinyInt1isBit=false")}]
(sync/sync-database! db)
(is (= #{{:name "number-of-cans", :base_type :type/Integer, :semantic_type :type/Quantity}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields db))))))))
(tx/defdataset year-db
[["years"
[{:field-name "year_column", :base-type {:native "YEAR"}, :effective-type :type/Date}]
[[2001] [2002] [1999]]]])
(deftest year-test
(mt/test-driver :mysql
(mt/dataset year-db
(testing "By default YEAR"
(is (= #{{:name "year_column", :base_type :type/Date, :semantic_type nil}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}}
(db->fields (mt/db)))))
(let [table (db/select-one Table :db_id (u/id (mt/db)))
fields (db/select Field :table_id (u/id table) :name "year_column")]
(testing "Can select from this table"
(is (= [[#t "2001-01-01"] [#t "2002-01-01"] [#t "1999-01-01"]]
(metadata-queries/table-rows-sample table fields (constantly conj)))))
(testing "We can fingerprint this table"
(is (= 1
(:updated-fingerprints (#'fingerprint/fingerprint-table! table fields)))))))))
(deftest db-timezone-id-test
(mt/test-driver :mysql
(let [timezone (fn [result-row]
(let [db (mt/db)]
(with-redefs [jdbc/query (let [orig jdbc/query]
(fn [spec sql-args & options]
(if (and (string? sql-args)
(str/includes? sql-args "GLOBAL.time_zone"))
[result-row]
(apply orig spec sql-args options))))]
(driver/db-default-timezone driver/*driver* db))))]
(testing "Should use global timezone by default"
(is (= "US/Pacific"
(timezone {:global_tz "US/Pacific", :system_tz "UTC"}))))
(testing "If global timezone is 'SYSTEM', should use system timezone"
(is (= "UTC"
(timezone {:global_tz "SYSTEM", :system_tz "UTC"}))))
(testing "Should fall back to returning `offset` if global/system aren't present"
(is (= "+00:00"
(timezone {:offset "00:00"}))))
(testing "If global timezone is invalid, should fall back to offset"
(is (= "-08:00"
(timezone {:global_tz "PDT", :system_tz "PDT", :offset "-08:00"}))))
(testing "Should add a `+` if needed to offset"
(is (= "+00:00"
(timezone {:global_tz "PDT", :system_tz "UTC", :offset "00:00"})))))
(testing "real timezone query doesn't fail"
(is (nil? (try
(driver/db-default-timezone driver/*driver* (mt/db))
nil
(catch Throwable e
e)))))))
(deftest timezone-date-formatting-test
(mt/test-driver :mysql
;; Most of our tests either deal in UTC (offset 00:00) or America/Los_Angeles timezones (-07:00/-08:00). When dealing
;; with dates, we will often truncate the timestamp to a date. When we only test with negative timezone offsets, in
;; combination with this truncation, means we could have a bug and it's hidden by this negative-only offset. As an
;; example, if we have a datetime like 2018-08-17 00:00:00-08:00, converting to UTC this becomes 2018-08-17
;; 08:00:00+00:00, which when truncated is still 2018-08-17. That same scenario in Hong Kong is 2018-08-17
;; 00:00:00+08:00, which then becomes 2018-08-16 16:00:00+00:00 when converted to UTC, which will truncate to
;; 2018-08-16, instead of 2018-08-17
(mt/with-system-timezone-id "Asia/Hong_Kong"
(letfn [(run-query-with-report-timezone [report-timezone]
(mt/with-temporary-setting-values [report-timezone report-timezone]
(mt/first-row
(qp/process-query
{:database (mt/id)
:type :native
:settings {:report-timezone "UTC"}
:native {:query "SELECT cast({{date}} as date)"
:template-tags {:date {:name "date" :display_name "Date" :type "date"}}}
:parameters [{:type "date/single" :target ["variable" ["template-tag" "date"]] :value "2018-04-18"}]}))))]
(testing "date formatting when system-timezone == report-timezone"
(is (= ["2018-04-18T00:00:00+08:00"]
(run-query-with-report-timezone "Asia/Hong_Kong"))))
;; This tests a similar scenario, but one in which the JVM timezone is in Hong Kong, but the report timezone
;; is in Los Angeles. The Joda Time date parsing functions for the most part default to UTC. Our tests all run
;; with a UTC JVM timezone. This test catches a bug where we are incorrectly assuming a date is in UTC when
;; the JVM timezone is different.
;;
;; The original bug can be found here: https://github.com/metabase/metabase/issues/8262. The MySQL driver code
;; was parsing the date using JodateTime's date parser, which is in UTC. The MySQL driver code was assuming
;; that date was in the system timezone rather than UTC which caused an incorrect conversion and with the
;; trucation, let to it being off by a day
(testing "date formatting when system-timezone != report-timezone"
(is (= ["2018-04-18T00:00:00-07:00"]
(run-query-with-report-timezone "America/Los_Angeles"))))))))
(def ^:private sample-connection-details
{:db "my_db", :host "localhost", :port "3306", :user "cam", :password "bad-password"})
(def ^:private sample-jdbc-spec
{:password "bad-password"
:characterSetResults "UTF8"
:characterEncoding "UTF8"
:classname "org.mariadb.jdbc.Driver"
:subprotocol "mysql"
:zeroDateTimeBehavior "convertToNull"
:user "cam"
:subname "//localhost:3306/my_db"
:useCompression true
:useUnicode true})
(deftest connection-spec-test
(testing "Do `:ssl` connection details give us the connection spec we'd expect?"
(is (= (assoc sample-jdbc-spec :useSSL true :serverSslCert "sslCert")
(sql-jdbc.conn/connection-details->spec :mysql (assoc sample-connection-details :ssl true
:ssl-cert "sslCert")))))
(testing "what about non-SSL connections?"
(is (= (assoc sample-jdbc-spec :useSSL false)
(sql-jdbc.conn/connection-details->spec :mysql sample-connection-details))))
(testing "Connections that are `:ssl false` but with `useSSL` in the additional options should be treated as SSL (see #9629)"
(is (= (assoc sample-jdbc-spec :useSSL true, :subname "//localhost:3306/my_db?useSSL=true&trustServerCertificate=true")
(sql-jdbc.conn/connection-details->spec :mysql
(assoc sample-connection-details
:ssl false
:additional-options "useSSL=true&trustServerCertificate=true"))))))
(deftest read-timediffs-test
(mt/test-driver :mysql
(testing "Make sure negative result of *diff() functions don't cause Exceptions (#10983)"
(doseq [{:keys [interval expected message]}
[{:interval "-1 HOUR"
:expected "-01:00:00"
:message "Negative durations should come back as Strings"}
{:interval "25 HOUR"
:expected "25:00:00"
:message "Durations outside the valid range of `LocalTime` should come back as Strings"}
{:interval "1 HOUR"
:expected #t "01:00:00"
:message "A `timediff()` result within the valid range should still come back as a `LocalTime`"}]]
(testing (str "\n" interval "\n" message)
(is (= [expected]
(mt/first-row
(qp/process-query
(assoc (mt/native-query
{:query (format "SELECT timediff(current_timestamp + INTERVAL %s, current_timestamp)" interval)})
;; disable the middleware that normally converts `LocalTime` to `Strings` so we can verify
;; our driver is actually doing the right thing
:middleware {:format-rows? false}))))))))))
(defn- table-fingerprint
[{:keys [fields name]}]
{:name name
:fields (map #(select-keys % [:name :base_type]) fields)})
(deftest system-versioned-tables-test
(mt/test-driver :mysql
(testing "system versioned tables appear during a sync"
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(try
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS versioned_tables;"
"CREATE DATABASE versioned_tables;"]]
(jdbc/execute! spec [sql]))
;; Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "versioned_tables"})
spec (sql-jdbc.conn/connection-details->spec :mysql details)
compat (try
(doseq [sql ["CREATE TABLE IF NOT EXISTS src1 (id INTEGER, t TEXT);"
"CREATE TABLE IF NOT EXISTS src2 (id INTEGER, t TEXT);"
"ALTER TABLE src2 ADD SYSTEM VERSIONING;"
"INSERT INTO src1 VALUES (1, '2020-03-01 12:20:35');"
"INSERT INTO src2 VALUES (1, '2020-03-01 12:20:35');"]]
(jdbc/execute! spec [sql]))
true
(catch java.sql.SQLSyntaxErrorException se
;; if an error is received with SYSTEM VERSIONING mentioned, the version
;; of mysql or mariadb being tested against does not support system versioning,
;; so do not continue
(if (re-matches #".*VERSIONING'.*" (.getMessage se))
false
(throw se))))]
(when compat
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(is (= [{:name "src1"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}
{:name "src2"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}]
(->> (hydrate (db/select Table :db_id (:id database) {:order-by [:name]}) :fields)
(map table-fingerprint))))))))))))
(deftest group-on-time-column-test
(mt/test-driver :mysql
(testing "can group on TIME columns (#12846)"
(mt/dataset attempted-murders
(let [now-date-str (u.date/format (t/local-date (t/zone-id "UTC")))
add-date-fn (fn [t] [(str now-date-str "T" t)])]
(testing "by minute"
(is (= (map add-date-fn ["00:14:00Z" "00:23:00Z" "00:35:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!minute.time]
:order-by [[:asc !minute.time]]
:limit 3})))))
(testing "by hour"
(is (= (map add-date-fn ["23:00:00Z" "20:00:00Z" "19:00:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!hour.time]
:order-by [[:desc !hour.time]]
:limit 3}))))))))))
(defn- pretty-sql [s]
(str/replace s #"`" ""))
(deftest do-not-cast-to-date-if-column-is-already-a-date-test
(testing "Don't wrap Field in date() if it's already a DATE (#11502)"
(mt/test-driver :mysql
(mt/dataset attempted-murders
(let [query (mt/mbql-query attempts
{:aggregation [[:count]]
:breakout [!day.date]})]
(is (= (str "SELECT attempts.date AS date, count(*) AS count "
"FROM attempts "
"GROUP BY attempts.date "
"ORDER BY attempts.date ASC")
(some-> (qp/query->native query) :query pretty-sql))))))
(testing "trunc-with-format should not cast a field if it is already a DATETIME"
(is (= ["SELECT str_to_date(date_format(CAST(field AS datetime), '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format "%Y" :field)]})))
(is (= ["SELECT str_to_date(date_format(field, '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format
"%Y"
(hx/with-database-type-info :field "datetime"))]}))))))
(deftest mysql-connect-with-ssl-and-pem-cert-test
(mt/test-driver :mysql
(if (System/getenv "MB_MYSQL_SSL_TEST_SSL_CERT")
(testing "MySQL with SSL connectivity using PEM certificate"
(mt/with-env-keys-renamed-by #(str/replace-first % "mb-mysql-ssl-test" "mb-mysql-test")
(string-extracts-test/test-breakout)))
(println (u/format-color 'yellow
"Skipping %s because %s env var is not set"
"mysql-connect-with-ssl-and-pem-cert-test"
"MB_MYSQL_SSL_TEST_SSL_CERT")))))
|
74049
|
(ns metabase.driver.mysql-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[honeysql.core :as hsql]
[java-time :as t]
[metabase.db.metadata-queries :as metadata-queries]
[metabase.driver :as driver]
[metabase.driver.mysql :as mysql]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.table :refer [Table]]
[metabase.query-processor :as qp]
;; used for one SSL with PEM connectivity test
[metabase.query-processor-test.string-extracts-test :as string-extracts-test]
[metabase.sync :as sync]
[metabase.sync.analyze.fingerprint :as fingerprint]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.honeysql-extensions :as hx]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]
[toucan.util.test :as tt]))
(deftest all-zero-dates-test
(mt/test-driver :mysql
(testing (str "MySQL allows 0000-00-00 dates, but JDBC does not; make sure that MySQL is converting them to NULL "
"when returning them like we asked")
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(try
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS all_zero_dates;"
"CREATE DATABASE all_zero_dates;"]]
(jdbc/execute! spec [sql]))
;; Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "all_zero_dates"})
spec (-> (sql-jdbc.conn/connection-details->spec :mysql details)
;; allow inserting dates where value is '0000-00-00' -- this is disallowed by default on newer
;; versions of MySQL, but we still want to test that we can handle it correctly for older ones
(assoc :sessionVariables "sql_mode='ALLOW_INVALID_DATES'"))]
(doseq [sql ["CREATE TABLE `exciting-moments-in-history` (`id` integer, `moment` timestamp);"
"INSERT INTO `exciting-moments-in-history` (`id`, `moment`) VALUES (1, '0000-00-00');"]]
(jdbc/execute! spec [sql]))
;; create & sync MB DB
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(mt/with-db database
;; run the query
(is (= [[1 nil]]
(mt/rows
(mt/run-mbql-query exciting-moments-in-history))))))))))))
;; Test how TINYINT(1) columns are interpreted. By default, they should be interpreted as integers, but with the
;; correct additional options, we should be able to change that -- see
;; https://github.com/metabase/metabase/issues/3506
(tx/defdataset tiny-int-ones
[["number-of-cans"
[{:field-name "thing", :base-type :type/Text}
{:field-name "number-of-cans", :base-type {:native "tinyint(1)"}, :effective-type :type/Integer}]
[["Six Pack" 6]
["Toucan" 2]
["Empty Vending Machine" 0]]]])
(defn- db->fields [db]
(let [table-ids (db/select-ids 'Table :db_id (u/the-id db))]
(set (map (partial into {}) (db/select [Field :name :base_type :semantic_type] :table_id [:in table-ids])))))
(deftest tiny-int-1-test
(mt/test-driver :mysql
(mt/dataset tiny-int-ones
;; trigger a full sync on this database so fields are categorized correctly
(sync/sync-database! (mt/db))
(testing "By default TINYINT(1) should be a boolean"
(is (= #{{:name "number-of-cans", :base_type :type/Boolean, :semantic_type :type/Category}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields (mt/db)))))
(testing "if someone says specifies `tinyInt1isBit=false`, it should come back as a number instead"
(tt/with-temp Database [db {:engine "mysql"
:details (assoc (:details (mt/db))
:additional-options "tinyInt1isBit=false")}]
(sync/sync-database! db)
(is (= #{{:name "number-of-cans", :base_type :type/Integer, :semantic_type :type/Quantity}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields db))))))))
(tx/defdataset year-db
[["years"
[{:field-name "year_column", :base-type {:native "YEAR"}, :effective-type :type/Date}]
[[2001] [2002] [1999]]]])
(deftest year-test
(mt/test-driver :mysql
(mt/dataset year-db
(testing "By default YEAR"
(is (= #{{:name "year_column", :base_type :type/Date, :semantic_type nil}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}}
(db->fields (mt/db)))))
(let [table (db/select-one Table :db_id (u/id (mt/db)))
fields (db/select Field :table_id (u/id table) :name "year_column")]
(testing "Can select from this table"
(is (= [[#t "2001-01-01"] [#t "2002-01-01"] [#t "1999-01-01"]]
(metadata-queries/table-rows-sample table fields (constantly conj)))))
(testing "We can fingerprint this table"
(is (= 1
(:updated-fingerprints (#'fingerprint/fingerprint-table! table fields)))))))))
(deftest db-timezone-id-test
(mt/test-driver :mysql
(let [timezone (fn [result-row]
(let [db (mt/db)]
(with-redefs [jdbc/query (let [orig jdbc/query]
(fn [spec sql-args & options]
(if (and (string? sql-args)
(str/includes? sql-args "GLOBAL.time_zone"))
[result-row]
(apply orig spec sql-args options))))]
(driver/db-default-timezone driver/*driver* db))))]
(testing "Should use global timezone by default"
(is (= "US/Pacific"
(timezone {:global_tz "US/Pacific", :system_tz "UTC"}))))
(testing "If global timezone is 'SYSTEM', should use system timezone"
(is (= "UTC"
(timezone {:global_tz "SYSTEM", :system_tz "UTC"}))))
(testing "Should fall back to returning `offset` if global/system aren't present"
(is (= "+00:00"
(timezone {:offset "00:00"}))))
(testing "If global timezone is invalid, should fall back to offset"
(is (= "-08:00"
(timezone {:global_tz "PDT", :system_tz "PDT", :offset "-08:00"}))))
(testing "Should add a `+` if needed to offset"
(is (= "+00:00"
(timezone {:global_tz "PDT", :system_tz "UTC", :offset "00:00"})))))
(testing "real timezone query doesn't fail"
(is (nil? (try
(driver/db-default-timezone driver/*driver* (mt/db))
nil
(catch Throwable e
e)))))))
(deftest timezone-date-formatting-test
(mt/test-driver :mysql
;; Most of our tests either deal in UTC (offset 00:00) or America/Los_Angeles timezones (-07:00/-08:00). When dealing
;; with dates, we will often truncate the timestamp to a date. When we only test with negative timezone offsets, in
;; combination with this truncation, means we could have a bug and it's hidden by this negative-only offset. As an
;; example, if we have a datetime like 2018-08-17 00:00:00-08:00, converting to UTC this becomes 2018-08-17
;; 08:00:00+00:00, which when truncated is still 2018-08-17. That same scenario in Hong Kong is 2018-08-17
;; 00:00:00+08:00, which then becomes 2018-08-16 16:00:00+00:00 when converted to UTC, which will truncate to
;; 2018-08-16, instead of 2018-08-17
(mt/with-system-timezone-id "Asia/Hong_Kong"
(letfn [(run-query-with-report-timezone [report-timezone]
(mt/with-temporary-setting-values [report-timezone report-timezone]
(mt/first-row
(qp/process-query
{:database (mt/id)
:type :native
:settings {:report-timezone "UTC"}
:native {:query "SELECT cast({{date}} as date)"
:template-tags {:date {:name "date" :display_name "Date" :type "date"}}}
:parameters [{:type "date/single" :target ["variable" ["template-tag" "date"]] :value "2018-04-18"}]}))))]
(testing "date formatting when system-timezone == report-timezone"
(is (= ["2018-04-18T00:00:00+08:00"]
(run-query-with-report-timezone "Asia/Hong_Kong"))))
;; This tests a similar scenario, but one in which the JVM timezone is in Hong Kong, but the report timezone
;; is in Los Angeles. The Joda Time date parsing functions for the most part default to UTC. Our tests all run
;; with a UTC JVM timezone. This test catches a bug where we are incorrectly assuming a date is in UTC when
;; the JVM timezone is different.
;;
;; The original bug can be found here: https://github.com/metabase/metabase/issues/8262. The MySQL driver code
;; was parsing the date using JodateTime's date parser, which is in UTC. The MySQL driver code was assuming
;; that date was in the system timezone rather than UTC which caused an incorrect conversion and with the
;; trucation, let to it being off by a day
(testing "date formatting when system-timezone != report-timezone"
(is (= ["2018-04-18T00:00:00-07:00"]
(run-query-with-report-timezone "America/Los_Angeles"))))))))
(def ^:private sample-connection-details
{:db "my_db", :host "localhost", :port "3306", :user "cam", :password "<PASSWORD>"})
(def ^:private sample-jdbc-spec
{:password "<PASSWORD>"
:characterSetResults "UTF8"
:characterEncoding "UTF8"
:classname "org.mariadb.jdbc.Driver"
:subprotocol "mysql"
:zeroDateTimeBehavior "convertToNull"
:user "cam"
:subname "//localhost:3306/my_db"
:useCompression true
:useUnicode true})
(deftest connection-spec-test
(testing "Do `:ssl` connection details give us the connection spec we'd expect?"
(is (= (assoc sample-jdbc-spec :useSSL true :serverSslCert "sslCert")
(sql-jdbc.conn/connection-details->spec :mysql (assoc sample-connection-details :ssl true
:ssl-cert "sslCert")))))
(testing "what about non-SSL connections?"
(is (= (assoc sample-jdbc-spec :useSSL false)
(sql-jdbc.conn/connection-details->spec :mysql sample-connection-details))))
(testing "Connections that are `:ssl false` but with `useSSL` in the additional options should be treated as SSL (see #9629)"
(is (= (assoc sample-jdbc-spec :useSSL true, :subname "//localhost:3306/my_db?useSSL=true&trustServerCertificate=true")
(sql-jdbc.conn/connection-details->spec :mysql
(assoc sample-connection-details
:ssl false
:additional-options "useSSL=true&trustServerCertificate=true"))))))
(deftest read-timediffs-test
(mt/test-driver :mysql
(testing "Make sure negative result of *diff() functions don't cause Exceptions (#10983)"
(doseq [{:keys [interval expected message]}
[{:interval "-1 HOUR"
:expected "-01:00:00"
:message "Negative durations should come back as Strings"}
{:interval "25 HOUR"
:expected "25:00:00"
:message "Durations outside the valid range of `LocalTime` should come back as Strings"}
{:interval "1 HOUR"
:expected #t "01:00:00"
:message "A `timediff()` result within the valid range should still come back as a `LocalTime`"}]]
(testing (str "\n" interval "\n" message)
(is (= [expected]
(mt/first-row
(qp/process-query
(assoc (mt/native-query
{:query (format "SELECT timediff(current_timestamp + INTERVAL %s, current_timestamp)" interval)})
;; disable the middleware that normally converts `LocalTime` to `Strings` so we can verify
;; our driver is actually doing the right thing
:middleware {:format-rows? false}))))))))))
(defn- table-fingerprint
[{:keys [fields name]}]
{:name name
:fields (map #(select-keys % [:name :base_type]) fields)})
(deftest system-versioned-tables-test
(mt/test-driver :mysql
(testing "system versioned tables appear during a sync"
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(try
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS versioned_tables;"
"CREATE DATABASE versioned_tables;"]]
(jdbc/execute! spec [sql]))
;; Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "versioned_tables"})
spec (sql-jdbc.conn/connection-details->spec :mysql details)
compat (try
(doseq [sql ["CREATE TABLE IF NOT EXISTS src1 (id INTEGER, t TEXT);"
"CREATE TABLE IF NOT EXISTS src2 (id INTEGER, t TEXT);"
"ALTER TABLE src2 ADD SYSTEM VERSIONING;"
"INSERT INTO src1 VALUES (1, '2020-03-01 12:20:35');"
"INSERT INTO src2 VALUES (1, '2020-03-01 12:20:35');"]]
(jdbc/execute! spec [sql]))
true
(catch java.sql.SQLSyntaxErrorException se
;; if an error is received with SYSTEM VERSIONING mentioned, the version
;; of mysql or mariadb being tested against does not support system versioning,
;; so do not continue
(if (re-matches #".*VERSIONING'.*" (.getMessage se))
false
(throw se))))]
(when compat
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(is (= [{:name "src1"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}
{:name "src2"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}]
(->> (hydrate (db/select Table :db_id (:id database) {:order-by [:name]}) :fields)
(map table-fingerprint))))))))))))
(deftest group-on-time-column-test
(mt/test-driver :mysql
(testing "can group on TIME columns (#12846)"
(mt/dataset attempted-murders
(let [now-date-str (u.date/format (t/local-date (t/zone-id "UTC")))
add-date-fn (fn [t] [(str now-date-str "T" t)])]
(testing "by minute"
(is (= (map add-date-fn ["00:14:00Z" "00:23:00Z" "00:35:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!minute.time]
:order-by [[:asc !minute.time]]
:limit 3})))))
(testing "by hour"
(is (= (map add-date-fn ["23:00:00Z" "20:00:00Z" "19:00:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!hour.time]
:order-by [[:desc !hour.time]]
:limit 3}))))))))))
(defn- pretty-sql [s]
(str/replace s #"`" ""))
(deftest do-not-cast-to-date-if-column-is-already-a-date-test
(testing "Don't wrap Field in date() if it's already a DATE (#11502)"
(mt/test-driver :mysql
(mt/dataset attempted-murders
(let [query (mt/mbql-query attempts
{:aggregation [[:count]]
:breakout [!day.date]})]
(is (= (str "SELECT attempts.date AS date, count(*) AS count "
"FROM attempts "
"GROUP BY attempts.date "
"ORDER BY attempts.date ASC")
(some-> (qp/query->native query) :query pretty-sql))))))
(testing "trunc-with-format should not cast a field if it is already a DATETIME"
(is (= ["SELECT str_to_date(date_format(CAST(field AS datetime), '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format "%Y" :field)]})))
(is (= ["SELECT str_to_date(date_format(field, '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format
"%Y"
(hx/with-database-type-info :field "datetime"))]}))))))
(deftest mysql-connect-with-ssl-and-pem-cert-test
(mt/test-driver :mysql
(if (System/getenv "MB_MYSQL_SSL_TEST_SSL_CERT")
(testing "MySQL with SSL connectivity using PEM certificate"
(mt/with-env-keys-renamed-by #(str/replace-first % "<KEY>" "mb-<KEY>")
(string-extracts-test/test-breakout)))
(println (u/format-color 'yellow
"Skipping %s because %s env var is not set"
"mysql-connect-with-ssl-and-pem-cert-test"
"MB_MYSQL_SSL_TEST_SSL_CERT")))))
| true |
(ns metabase.driver.mysql-test
(:require [clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.test :refer :all]
[honeysql.core :as hsql]
[java-time :as t]
[metabase.db.metadata-queries :as metadata-queries]
[metabase.driver :as driver]
[metabase.driver.mysql :as mysql]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.models.database :refer [Database]]
[metabase.models.field :refer [Field]]
[metabase.models.table :refer [Table]]
[metabase.query-processor :as qp]
;; used for one SSL with PEM connectivity test
[metabase.query-processor-test.string-extracts-test :as string-extracts-test]
[metabase.sync :as sync]
[metabase.sync.analyze.fingerprint :as fingerprint]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.honeysql-extensions :as hx]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]
[toucan.util.test :as tt]))
(deftest all-zero-dates-test
(mt/test-driver :mysql
(testing (str "MySQL allows 0000-00-00 dates, but JDBC does not; make sure that MySQL is converting them to NULL "
"when returning them like we asked")
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(try
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS all_zero_dates;"
"CREATE DATABASE all_zero_dates;"]]
(jdbc/execute! spec [sql]))
;; Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "all_zero_dates"})
spec (-> (sql-jdbc.conn/connection-details->spec :mysql details)
;; allow inserting dates where value is '0000-00-00' -- this is disallowed by default on newer
;; versions of MySQL, but we still want to test that we can handle it correctly for older ones
(assoc :sessionVariables "sql_mode='ALLOW_INVALID_DATES'"))]
(doseq [sql ["CREATE TABLE `exciting-moments-in-history` (`id` integer, `moment` timestamp);"
"INSERT INTO `exciting-moments-in-history` (`id`, `moment`) VALUES (1, '0000-00-00');"]]
(jdbc/execute! spec [sql]))
;; create & sync MB DB
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(mt/with-db database
;; run the query
(is (= [[1 nil]]
(mt/rows
(mt/run-mbql-query exciting-moments-in-history))))))))))))
;; Test how TINYINT(1) columns are interpreted. By default, they should be interpreted as integers, but with the
;; correct additional options, we should be able to change that -- see
;; https://github.com/metabase/metabase/issues/3506
(tx/defdataset tiny-int-ones
[["number-of-cans"
[{:field-name "thing", :base-type :type/Text}
{:field-name "number-of-cans", :base-type {:native "tinyint(1)"}, :effective-type :type/Integer}]
[["Six Pack" 6]
["Toucan" 2]
["Empty Vending Machine" 0]]]])
(defn- db->fields [db]
(let [table-ids (db/select-ids 'Table :db_id (u/the-id db))]
(set (map (partial into {}) (db/select [Field :name :base_type :semantic_type] :table_id [:in table-ids])))))
(deftest tiny-int-1-test
(mt/test-driver :mysql
(mt/dataset tiny-int-ones
;; trigger a full sync on this database so fields are categorized correctly
(sync/sync-database! (mt/db))
(testing "By default TINYINT(1) should be a boolean"
(is (= #{{:name "number-of-cans", :base_type :type/Boolean, :semantic_type :type/Category}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields (mt/db)))))
(testing "if someone says specifies `tinyInt1isBit=false`, it should come back as a number instead"
(tt/with-temp Database [db {:engine "mysql"
:details (assoc (:details (mt/db))
:additional-options "tinyInt1isBit=false")}]
(sync/sync-database! db)
(is (= #{{:name "number-of-cans", :base_type :type/Integer, :semantic_type :type/Quantity}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}
{:name "thing", :base_type :type/Text, :semantic_type :type/Category}}
(db->fields db))))))))
(tx/defdataset year-db
[["years"
[{:field-name "year_column", :base-type {:native "YEAR"}, :effective-type :type/Date}]
[[2001] [2002] [1999]]]])
(deftest year-test
(mt/test-driver :mysql
(mt/dataset year-db
(testing "By default YEAR"
(is (= #{{:name "year_column", :base_type :type/Date, :semantic_type nil}
{:name "id", :base_type :type/Integer, :semantic_type :type/PK}}
(db->fields (mt/db)))))
(let [table (db/select-one Table :db_id (u/id (mt/db)))
fields (db/select Field :table_id (u/id table) :name "year_column")]
(testing "Can select from this table"
(is (= [[#t "2001-01-01"] [#t "2002-01-01"] [#t "1999-01-01"]]
(metadata-queries/table-rows-sample table fields (constantly conj)))))
(testing "We can fingerprint this table"
(is (= 1
(:updated-fingerprints (#'fingerprint/fingerprint-table! table fields)))))))))
(deftest db-timezone-id-test
(mt/test-driver :mysql
(let [timezone (fn [result-row]
(let [db (mt/db)]
(with-redefs [jdbc/query (let [orig jdbc/query]
(fn [spec sql-args & options]
(if (and (string? sql-args)
(str/includes? sql-args "GLOBAL.time_zone"))
[result-row]
(apply orig spec sql-args options))))]
(driver/db-default-timezone driver/*driver* db))))]
(testing "Should use global timezone by default"
(is (= "US/Pacific"
(timezone {:global_tz "US/Pacific", :system_tz "UTC"}))))
(testing "If global timezone is 'SYSTEM', should use system timezone"
(is (= "UTC"
(timezone {:global_tz "SYSTEM", :system_tz "UTC"}))))
(testing "Should fall back to returning `offset` if global/system aren't present"
(is (= "+00:00"
(timezone {:offset "00:00"}))))
(testing "If global timezone is invalid, should fall back to offset"
(is (= "-08:00"
(timezone {:global_tz "PDT", :system_tz "PDT", :offset "-08:00"}))))
(testing "Should add a `+` if needed to offset"
(is (= "+00:00"
(timezone {:global_tz "PDT", :system_tz "UTC", :offset "00:00"})))))
(testing "real timezone query doesn't fail"
(is (nil? (try
(driver/db-default-timezone driver/*driver* (mt/db))
nil
(catch Throwable e
e)))))))
(deftest timezone-date-formatting-test
(mt/test-driver :mysql
;; Most of our tests either deal in UTC (offset 00:00) or America/Los_Angeles timezones (-07:00/-08:00). When dealing
;; with dates, we will often truncate the timestamp to a date. When we only test with negative timezone offsets, in
;; combination with this truncation, means we could have a bug and it's hidden by this negative-only offset. As an
;; example, if we have a datetime like 2018-08-17 00:00:00-08:00, converting to UTC this becomes 2018-08-17
;; 08:00:00+00:00, which when truncated is still 2018-08-17. That same scenario in Hong Kong is 2018-08-17
;; 00:00:00+08:00, which then becomes 2018-08-16 16:00:00+00:00 when converted to UTC, which will truncate to
;; 2018-08-16, instead of 2018-08-17
(mt/with-system-timezone-id "Asia/Hong_Kong"
(letfn [(run-query-with-report-timezone [report-timezone]
(mt/with-temporary-setting-values [report-timezone report-timezone]
(mt/first-row
(qp/process-query
{:database (mt/id)
:type :native
:settings {:report-timezone "UTC"}
:native {:query "SELECT cast({{date}} as date)"
:template-tags {:date {:name "date" :display_name "Date" :type "date"}}}
:parameters [{:type "date/single" :target ["variable" ["template-tag" "date"]] :value "2018-04-18"}]}))))]
(testing "date formatting when system-timezone == report-timezone"
(is (= ["2018-04-18T00:00:00+08:00"]
(run-query-with-report-timezone "Asia/Hong_Kong"))))
;; This tests a similar scenario, but one in which the JVM timezone is in Hong Kong, but the report timezone
;; is in Los Angeles. The Joda Time date parsing functions for the most part default to UTC. Our tests all run
;; with a UTC JVM timezone. This test catches a bug where we are incorrectly assuming a date is in UTC when
;; the JVM timezone is different.
;;
;; The original bug can be found here: https://github.com/metabase/metabase/issues/8262. The MySQL driver code
;; was parsing the date using JodateTime's date parser, which is in UTC. The MySQL driver code was assuming
;; that date was in the system timezone rather than UTC which caused an incorrect conversion and with the
;; trucation, let to it being off by a day
(testing "date formatting when system-timezone != report-timezone"
(is (= ["2018-04-18T00:00:00-07:00"]
(run-query-with-report-timezone "America/Los_Angeles"))))))))
(def ^:private sample-connection-details
{:db "my_db", :host "localhost", :port "3306", :user "cam", :password "PI:PASSWORD:<PASSWORD>END_PI"})
(def ^:private sample-jdbc-spec
{:password "PI:PASSWORD:<PASSWORD>END_PI"
:characterSetResults "UTF8"
:characterEncoding "UTF8"
:classname "org.mariadb.jdbc.Driver"
:subprotocol "mysql"
:zeroDateTimeBehavior "convertToNull"
:user "cam"
:subname "//localhost:3306/my_db"
:useCompression true
:useUnicode true})
(deftest connection-spec-test
(testing "Do `:ssl` connection details give us the connection spec we'd expect?"
(is (= (assoc sample-jdbc-spec :useSSL true :serverSslCert "sslCert")
(sql-jdbc.conn/connection-details->spec :mysql (assoc sample-connection-details :ssl true
:ssl-cert "sslCert")))))
(testing "what about non-SSL connections?"
(is (= (assoc sample-jdbc-spec :useSSL false)
(sql-jdbc.conn/connection-details->spec :mysql sample-connection-details))))
(testing "Connections that are `:ssl false` but with `useSSL` in the additional options should be treated as SSL (see #9629)"
(is (= (assoc sample-jdbc-spec :useSSL true, :subname "//localhost:3306/my_db?useSSL=true&trustServerCertificate=true")
(sql-jdbc.conn/connection-details->spec :mysql
(assoc sample-connection-details
:ssl false
:additional-options "useSSL=true&trustServerCertificate=true"))))))
(deftest read-timediffs-test
(mt/test-driver :mysql
(testing "Make sure negative result of *diff() functions don't cause Exceptions (#10983)"
(doseq [{:keys [interval expected message]}
[{:interval "-1 HOUR"
:expected "-01:00:00"
:message "Negative durations should come back as Strings"}
{:interval "25 HOUR"
:expected "25:00:00"
:message "Durations outside the valid range of `LocalTime` should come back as Strings"}
{:interval "1 HOUR"
:expected #t "01:00:00"
:message "A `timediff()` result within the valid range should still come back as a `LocalTime`"}]]
(testing (str "\n" interval "\n" message)
(is (= [expected]
(mt/first-row
(qp/process-query
(assoc (mt/native-query
{:query (format "SELECT timediff(current_timestamp + INTERVAL %s, current_timestamp)" interval)})
;; disable the middleware that normally converts `LocalTime` to `Strings` so we can verify
;; our driver is actually doing the right thing
:middleware {:format-rows? false}))))))))))
(defn- table-fingerprint
[{:keys [fields name]}]
{:name name
:fields (map #(select-keys % [:name :base_type]) fields)})
(deftest system-versioned-tables-test
(mt/test-driver :mysql
(testing "system versioned tables appear during a sync"
(let [spec (sql-jdbc.conn/connection-details->spec :mysql (tx/dbdef->connection-details :mysql :server nil))]
(try
;; Create the DB
(doseq [sql ["DROP DATABASE IF EXISTS versioned_tables;"
"CREATE DATABASE versioned_tables;"]]
(jdbc/execute! spec [sql]))
;; Create Table & add data
(let [details (tx/dbdef->connection-details :mysql :db {:database-name "versioned_tables"})
spec (sql-jdbc.conn/connection-details->spec :mysql details)
compat (try
(doseq [sql ["CREATE TABLE IF NOT EXISTS src1 (id INTEGER, t TEXT);"
"CREATE TABLE IF NOT EXISTS src2 (id INTEGER, t TEXT);"
"ALTER TABLE src2 ADD SYSTEM VERSIONING;"
"INSERT INTO src1 VALUES (1, '2020-03-01 12:20:35');"
"INSERT INTO src2 VALUES (1, '2020-03-01 12:20:35');"]]
(jdbc/execute! spec [sql]))
true
(catch java.sql.SQLSyntaxErrorException se
;; if an error is received with SYSTEM VERSIONING mentioned, the version
;; of mysql or mariadb being tested against does not support system versioning,
;; so do not continue
(if (re-matches #".*VERSIONING'.*" (.getMessage se))
false
(throw se))))]
(when compat
(tt/with-temp Database [database {:engine "mysql", :details details}]
(sync/sync-database! database)
(is (= [{:name "src1"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}
{:name "src2"
:fields [{:name "id"
:base_type :type/Integer}
{:name "t"
:base_type :type/Text}]}]
(->> (hydrate (db/select Table :db_id (:id database) {:order-by [:name]}) :fields)
(map table-fingerprint))))))))))))
(deftest group-on-time-column-test
(mt/test-driver :mysql
(testing "can group on TIME columns (#12846)"
(mt/dataset attempted-murders
(let [now-date-str (u.date/format (t/local-date (t/zone-id "UTC")))
add-date-fn (fn [t] [(str now-date-str "T" t)])]
(testing "by minute"
(is (= (map add-date-fn ["00:14:00Z" "00:23:00Z" "00:35:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!minute.time]
:order-by [[:asc !minute.time]]
:limit 3})))))
(testing "by hour"
(is (= (map add-date-fn ["23:00:00Z" "20:00:00Z" "19:00:00Z"])
(mt/rows
(mt/run-mbql-query attempts
{:breakout [!hour.time]
:order-by [[:desc !hour.time]]
:limit 3}))))))))))
(defn- pretty-sql [s]
(str/replace s #"`" ""))
(deftest do-not-cast-to-date-if-column-is-already-a-date-test
(testing "Don't wrap Field in date() if it's already a DATE (#11502)"
(mt/test-driver :mysql
(mt/dataset attempted-murders
(let [query (mt/mbql-query attempts
{:aggregation [[:count]]
:breakout [!day.date]})]
(is (= (str "SELECT attempts.date AS date, count(*) AS count "
"FROM attempts "
"GROUP BY attempts.date "
"ORDER BY attempts.date ASC")
(some-> (qp/query->native query) :query pretty-sql))))))
(testing "trunc-with-format should not cast a field if it is already a DATETIME"
(is (= ["SELECT str_to_date(date_format(CAST(field AS datetime), '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format "%Y" :field)]})))
(is (= ["SELECT str_to_date(date_format(field, '%Y'), '%Y')"]
(hsql/format {:select [(#'mysql/trunc-with-format
"%Y"
(hx/with-database-type-info :field "datetime"))]}))))))
(deftest mysql-connect-with-ssl-and-pem-cert-test
(mt/test-driver :mysql
(if (System/getenv "MB_MYSQL_SSL_TEST_SSL_CERT")
(testing "MySQL with SSL connectivity using PEM certificate"
(mt/with-env-keys-renamed-by #(str/replace-first % "PI:KEY:<KEY>END_PI" "mb-PI:KEY:<KEY>END_PI")
(string-extracts-test/test-breakout)))
(println (u/format-color 'yellow
"Skipping %s because %s env var is not set"
"mysql-connect-with-ssl-and-pem-cert-test"
"MB_MYSQL_SSL_TEST_SSL_CERT")))))
|
[
{
"context": " {:TABLE {1 {:ui/active? false :name \"Joe\"\n :other-widgets []\n ",
"end": 2553,
"score": 0.9987133741378784,
"start": 2550,
"tag": "NAME",
"value": "Joe"
},
{
"context": "\n 2 {:ui/active? true :name \"Jane\"\n :other-widgets []\n ",
"end": 2706,
"score": 0.998523473739624,
"start": 2702,
"tag": "NAME",
"value": "Jane"
},
{
"context": "rs to\"\n (uism/alias-value env :username) => \"Joe\"))\n\n (specification \"set-aliased-value\"\n (ass",
"end": 6251,
"score": 0.999478816986084,
"start": 6248,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "(uism/set-aliased-value :title \"Hello\" :username \"Joe\")\n (uism/alias-value :title)) => \"Hello\"\n ",
"end": 6550,
"score": 0.99961256980896,
"start": 6547,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "(uism/set-aliased-value :title \"Hello\" :username \"Joe\")\n (uism/alias-value :username)) => \"Joe\"\n",
"end": 6674,
"score": 0.9996336698532104,
"start": 6671,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": " \"Joe\")\n (uism/alias-value :username)) => \"Joe\"\n \"Can set more than 2 values\"\n (-> env",
"end": 6722,
"score": 0.9995945692062378,
"start": 6719,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "(uism/set-aliased-value :title \"Hello\" :username \"Joe\" :visible? :booga)\n (uism/alias-value :vis",
"end": 6834,
"score": 0.9996053576469421,
"start": 6831,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "t valid\"\n (uism/set-aliased-value env :name \"Sam\") => env\n \"Sets the value in the fulro state",
"end": 7020,
"score": 0.9976828098297119,
"start": 7017,
"tag": "NAME",
"value": "Sam"
},
{
"context": "-> env\n (uism/set-aliased-value :username \"Sam\")\n ::uism/state-map\n :TABLE\n ",
"end": 7157,
"score": 0.804283857345581,
"start": 7154,
"tag": "NAME",
"value": "Sam"
},
{
"context": " :TABLE\n (get 1)\n :name) => \"Sam\"))\n\n (specification \"reset-actor-ident\"\n (let",
"end": 7238,
"score": 0.9969741702079773,
"start": 7235,
"tag": "NAME",
"value": "Sam"
},
{
"context": "t valid\"\n (uism/set-aliased-value env :name \"Sam\") => env\n \"Sets the value in the fulro state",
"end": 7829,
"score": 0.9921595454216003,
"start": 7826,
"tag": "NAME",
"value": "Sam"
},
{
"context": " (-> env\n (uism/assoc-aliased :username \"Sam\")\n ::uism/state-map\n :TABLE\n ",
"end": 7962,
"score": 0.633742094039917,
"start": 7959,
"tag": "NAME",
"value": "Sam"
},
{
"context": " :TABLE\n (get 1)\n :name) => \"Sam\"))\n\n (specification \"assoc-aliased\"\n (asserti",
"end": 8043,
"score": 0.9965652227401733,
"start": 8040,
"tag": "NAME",
"value": "Sam"
},
{
"context": " (uism/assoc-aliased :title \"Hello\" :username \"Joe\")\n (uism/alias-value :title)) => \"Hello\"\n ",
"end": 8330,
"score": 0.9995895624160767,
"start": 8327,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": " (uism/assoc-aliased :title \"Hello\" :username \"Joe\")\n (uism/alias-value :username)) => \"Joe\"\n",
"end": 8450,
"score": 0.9995125532150269,
"start": 8447,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": " \"Joe\")\n (uism/alias-value :username)) => \"Joe\"\n \"Can set more than 2 values\"\n (-> env",
"end": 8498,
"score": 0.9994412660598755,
"start": 8495,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": " (uism/assoc-aliased :title \"Hello\" :username \"Joe\" :visible? :booga)\n (uism/alias-value :vis",
"end": 8606,
"score": 0.999526858329773,
"start": 8603,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "t valid\"\n (uism/set-aliased-value env :name \"Sam\") => env\n \"Sets the value in the fulro state",
"end": 8792,
"score": 0.9280657768249512,
"start": 8789,
"tag": "NAME",
"value": "Sam"
},
{
"context": " (-> env\n (uism/assoc-aliased :username \"Sam\")\n ::uism/state-map\n :TABLE\n ",
"end": 8925,
"score": 0.5483124256134033,
"start": 8922,
"tag": "NAME",
"value": "Sam"
},
{
"context": " :TABLE\n (get 1)\n :name) => \"Sam\"))\n\n (specification \"update-aliased\"\n (assert",
"end": 9006,
"score": 0.9374979734420776,
"start": 9003,
"tag": "NAME",
"value": "Sam"
},
{
"context": "(uism/assoc-aliased env :title \"Hello\" :username \"Joe\")]\n (let [entries (-> env\n ",
"end": 9564,
"score": 0.9864426851272583,
"start": 9561,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "[]\n :username \"Joe\"}))\n\n (specification \"run\"\n (assertions\n ",
"end": 12298,
"score": 0.9830247759819031,
"start": 12295,
"tag": "USERNAME",
"value": "Joe"
},
{
"context": "value :visible? true)\n (uism/run :f?)) => \"Joe\"\n\n \"Can be passed extra data that can overwr",
"end": 12474,
"score": 0.7080001831054688,
"start": 12471,
"tag": "NAME",
"value": "Joe"
},
{
"context": " (::uism/alias params) => :username\n ",
"end": 30484,
"score": 0.9762091040611267,
"start": 30476,
"tag": "USERNAME",
"value": "username"
}
] |
src/test/com/fulcrologic/fulcro/ui_state_machines_spec.cljc
|
mruzekw/fulcro
| 0 |
(ns com.fulcrologic.fulcro.ui-state-machines-spec
(:require
[clojure.spec.alpha :as s]
[com.fulcrologic.guardrails.core :refer [>defn]]
[com.fulcrologic.fulcro.algorithms.data-targeting :as targeting]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.specs]
[edn-query-language.core :as eql]
[fulcro-spec.core :refer [specification provided provided! when-mocking when-mocking! behavior assertions component]]))
(declare => =1x=>)
(def mock-app (app/fulcro-app))
(defn mutation-env [state-atom tx extra-env]
(-> mock-app
(assoc ::app/state-atom state-atom)
(txn/build-env (txn/tx-node tx) extra-env)
(assoc :ast (eql/query->ast1 tx))))
(defsc AClass [_ _] {:query ['*] :ident (fn [] [:A 1])})
(defn A-handler [env] env)
(uism/defstatemachine test-machine
{::uism/actor-names #{:dialog}
::uism/aliases {:visible? [:dialog :ui/active?]
:title [:dialog :title]
:widgets [:dialog :linked-widgets]
:uberwidgets [:dialog :other-widgets]
:username [:dialog :name]}
::uism/plugins {:f? (fn [{:keys [visible? username]}]
(when visible? username))}
::uism/states {:initial {::uism/handler (fn [env]
(with-meta env {:handler-ran true}))}
:B {::uism/events {:bang! {::uism/handler (fn [env] (uism/store env :handler-ran? true))
::uism/target-state :A
::uism/event-predicate (fn [env] (uism/retrieve env :enabled? false))}}}
:C {::uism/events {:bang! {::uism/handler (fn [env] (uism/store env :handler-ran? true))
::uism/target-state :A}}}
:D {::uism/events {:bang! {::uism/handler (fn [env] (uism/activate env :A))
::uism/target-state :B}}}
:A {::uism/handler A-handler}}})
(def base-fulcro-state
{:TABLE {1 {:ui/active? false :name "Joe"
:other-widgets []
:linked-widgets [[:widget/by-id 1]]}
2 {:ui/active? true :name "Jane"
:other-widgets []
:linked-widgets [[:widget/by-id 2]]}}
:widget/by-id {1 {:id 1}
2 {:id 2}
3 {:id 3}}
::uism/asm-id {:fake (uism/new-asm
{::uism/state-machine-id `test-machine
::uism/asm-id :fake
::uism/actor->component-name {:dialog (uism/any->actor-component-registry-key AClass)}
::uism/actor->ident {:dialog [:TABLE 1]}})}})
(defn test-env [event-id event-data]
(uism/state-machine-env base-fulcro-state [:TABLE 1] :fake event-id event-data))
(specification "State Machine Registry"
(assertions
"Registers the FQ symbol of the state machine"
(map? (uism/get-state-machine `test-machine)) => true
"Stores the definition at that symbol"
(::uism/actor-names (uism/get-state-machine `test-machine)) => #{:dialog}
"Allows lookup of a value via an active env and a machine key"
(uism/lookup-state-machine-field (test-env :event nil) ::uism/actor-names) => #{:dialog}))
(specification "state-machine-env"
(assertions
"produces a spec-compliant result"
(s/valid? ::uism/env (uism/state-machine-env {} [:a 1] :x :evt {})) => true))
(let [env (test-env nil nil)]
(specification "asm-value"
(assertions "Finds things in the active state machine"
(uism/asm-value env ::uism/asm-id) => :fake))
(specification "activate"
(assertions
"Sets the given active state in the env"
(-> env
(uism/activate :A)
(uism/asm-value ::uism/active-state)) => :A)
(assertions
"Ignores a requst to move to an invalid state (logs an error)"
(-> env
(uism/activate :crap)
(uism/asm-value ::uism/active-state)) => :initial))
(specification "store/retrieve"
(assertions
"Allows for the local storage or asm-local values"
(-> env (uism/store :x true) (uism/retrieve :x)) => true
(-> env (uism/store :x 0) (uism/retrieve :x)) => 0
(-> env (uism/store :x {}) (uism/retrieve :x)) => {}
(-> env (uism/store :v 1) (uism/retrieve :v)) => 1))
(specification "resolve-alias"
(assertions
"Returns the Fulcro state path for a given data alias"
(uism/resolve-alias env :username) => [:TABLE 1 :name])
(assertions
"Returns nil if it is an invalid alias"
(uism/resolve-alias env :crap) => nil))
(specification "actor-path"
(assertions
"Returns the Fulcro ident of an actor"
(uism/actor-path env :dialog) => [:TABLE 1]
"Returns the Fulcro path to data in an actor if a field is included"
(uism/actor-path env :dialog :boo) => [:TABLE 1 :boo]))
(specification "actor-class"
(assertions
"Returns the Fulcro class of an actor"
(uism/actor-class env :dialog) => AClass))
(specification "set-actor-value"
(assertions
"Sets a raw (non-aliased) attribute in Fulcro state on an actor"
(-> env
(uism/set-actor-value :dialog :boo 42)
::uism/state-map
:TABLE
(get 1)
:boo) => 42
"Which can be read by actor-value"
(-> env
(uism/set-actor-value :dialog :boo 42)
(uism/actor-value :dialog :boo)) => 42))
(specification "alias-value"
(assertions
"Returns nil if the alias isn't valid"
(uism/alias-value env :name) => nil
"Gets the value of the fulro state that the alias refers to"
(uism/alias-value env :username) => "Joe"))
(specification "set-aliased-value"
(assertions
"Can set a single value"
(-> env
(uism/set-aliased-value :title "Hello")
(uism/alias-value :title)) => "Hello"
"Can set two values"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe")
(uism/alias-value :title)) => "Hello"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe")
(uism/alias-value :username)) => "Joe"
"Can set more than 2 values"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe" :visible? :booga)
(uism/alias-value :visible?)) => :booga)
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "Sam") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/set-aliased-value :username "Sam")
::uism/state-map
:TABLE
(get 1)
:name) => "Sam"))
(specification "reset-actor-ident"
(let [env (uism/reset-actor-ident env :dialog [:TABLE 2])]
(assertions
"Can update actor/ident indexes"
(uism/asm-value env ::uism/actor->ident) => {:dialog [:TABLE 2]}
(uism/asm-value env ::uism/ident->actor) => {[:TABLE 2] :dialog}
"Class index is correct"
(uism/actor-class env :dialog) => AClass
(uism/asm-value env ::uism/actor->component-name) => {:dialog ::AClass}))
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "Sam") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/assoc-aliased :username "Sam")
::uism/state-map
:TABLE
(get 1)
:name) => "Sam"))
(specification "assoc-aliased"
(assertions
"Can set a single value"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/alias-value :title)) => "Hello"
"Can set two values"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe")
(uism/alias-value :title)) => "Hello"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe")
(uism/alias-value :username)) => "Joe"
"Can set more than 2 values"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe" :visible? :booga)
(uism/alias-value :visible?)) => :booga)
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "Sam") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/assoc-aliased :username "Sam")
::uism/state-map
:TABLE
(get 1)
:name) => "Sam"))
(specification "update-aliased"
(assertions
"Can update a value"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/update-aliased :title #(str % "-suffix"))
(uism/alias-value :title)) => "Hello-suffix"
"Can update a value with arguments"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/update-aliased :title #(str %1 %2 %3) 1 2)
(uism/alias-value :title)) => "Hello12"))
(specification "dissoc-aliased"
(let [env (uism/assoc-aliased env :title "Hello" :username "Joe")]
(let [entries (-> env
(uism/dissoc-aliased :title)
(get-in [::uism/state-map :TABLE 1])
(-> keys set))]
(assertions
"Can dissoc a single alias"
(contains? entries :title) => false))
(let [entries (-> env
(uism/dissoc-aliased :title :username)
(get-in [::uism/state-map :TABLE 1])
(-> keys set))]
(assertions
"Can dissoc multiple aliases"
(contains? entries :title) => false
(contains? entries :name) => false))))
(specification "integrate-ident"
(assertions
"Accepts a list of operations"
(let [nenv (uism/integrate-ident env [:widget/by-id 2] :prepend :widgets
:append :uberwidgets)]
(select-keys (get-in nenv [::uism/state-map :TABLE 1]) #{:other-widgets :linked-widgets}))
=> {:linked-widgets [[:widget/by-id 2] [:widget/by-id 1]]
:other-widgets [[:widget/by-id 2]]}
"Can prepend an ident"
(-> env
(uism/integrate-ident [:widget/by-id 2] :prepend :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 2] [:widget/by-id 1]]
"Can append an ident"
(-> env
(uism/integrate-ident [:widget/by-id 3] :append :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1] [:widget/by-id 3]]
"Integrating an already present ident has no effect"
(-> env
(uism/integrate-ident [:widget/by-id 1] :prepend :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]
(-> env
(uism/integrate-ident [:widget/by-id 1] :append :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]))
(specification "remove-ident"
(assertions
"Can remove an ident"
(-> env
(uism/remove-ident [:widget/by-id 1] :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => []
"Removing a non-present ident has no effect"
(-> env
(uism/remove-ident [:widget/by-id 2] :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]))
(specification "aliased-data"
(assertions
"Builds a map of all of the current values of aliased data"
(-> env
(uism/aliased-data)) => {:visible? false
:title nil
:widgets [[:widget/by-id 1]]
:uberwidgets []
:username "Joe"}))
(specification "run"
(assertions
"Runs a plugin against the env"
(-> env
(uism/set-aliased-value :visible? true)
(uism/run :f?)) => "Joe"
"Can be passed extra data that can overwrite aliased values"
(-> env
(uism/set-aliased-value :visible? true)
(uism/run :f? {:visible? false})) => nil))
(specification "active-state-handler"
(provided! "The state machine definition is missing or the active state has no handler"
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:boo)
(assertions
"returns core identity"
(uism/active-state-handler env) => identity))
(let [env (-> (test-env :bang! nil) (uism/activate :B) (uism/store :enabled? true))
handler (fn geh* [e] e)]
(provided! "The state machine definition has event definitions"
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:boo)
(uism/generic-event-handler e) => handler
(assertions
"returns a generic-event-handler"
(uism/active-state-handler env) => handler)))
(provided! "The state machine definition exists and there is an active state."
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:A)
(assertions
"returns the correct handler"
(uism/active-state-handler env) => A-handler)))
(specification "generic-event-handler"
(let [disabled-env (-> (test-env :bang! nil) (uism/activate :B) (uism/store :enabled? false))
enabled-env (-> disabled-env (uism/store :enabled? true))
non-event-env (-> (test-env :boo nil) (uism/activate :A))
missing-handler (uism/generic-event-handler non-event-env)
disabled-handler (uism/generic-event-handler disabled-env)
enabled-handler (uism/generic-event-handler enabled-env)
no-predicate-env (-> enabled-env (uism/activate :C))
no-predicate-handler (uism/generic-event-handler no-predicate-env)
overriding-handler-env (-> disabled-env (uism/activate :D))
overriding-handler (uism/generic-event-handler overriding-handler-env)
actual-disabled-result (disabled-handler disabled-env)
actual-enabled-result (enabled-handler enabled-env)
no-predicate-result (no-predicate-handler no-predicate-env)
overriding-handler-result (overriding-handler overriding-handler-env)]
(behavior "when the event definition is missing"
(assertions
"Returns nil"
missing-handler => nil))
(behavior "When there is no predicate"
(assertions
"Runs the handler"
(-> no-predicate-result (uism/retrieve :handler-ran? false)) => true
"Follows the transition, if defined"
(-> no-predicate-result (uism/asm-value ::uism/active-state)) => :A))
(behavior "when the predicate is false"
(assertions
"Does not runs the handler"
(-> actual-disabled-result (uism/retrieve :handler-ran? false)) => false
"Stays in the same state"
(-> actual-disabled-result (uism/asm-value ::uism/active-state)) => :B))
(behavior "when the predicate is true"
(assertions
"Runs the handler"
(-> actual-enabled-result (uism/retrieve :handler-ran? false)) => true
"Follows the transition, if defined"
(-> actual-enabled-result (uism/asm-value ::uism/active-state)) => :A))
(behavior "when the handler activates a target state different from the *declared* target state"
(assertions
"The handler wins"
(-> overriding-handler-result (uism/asm-value ::uism/active-state)) => :A))))
(specification "apply-event-value"
(assertions
"returns an unmodified env for other events"
(uism/apply-event-value env {::uism/event-id :random-event}) => env
"applies a change to fulcro state based on the ::value-changed event"
(-> env
(uism/apply-event-value {::uism/event-id ::uism/value-changed
::uism/event-data {::uism/alias :visible?
:value :new-value}})
(uism/alias-value :visible?)) => :new-value))
(specification "queue-mutations!"
(let [mutation-1-descriptor {::uism/mutation-context :dialog
::uism/ok-event :pow!
::uism/mutation `a}
mutation-2-descriptor {::uism/mutation-context :dialog
::uism/ok-event :bam!
::uism/mutation `b}
menv1 (assoc env ::uism/queued-mutations [mutation-1-descriptor])
menv (assoc env ::uism/queued-mutations [mutation-1-descriptor
mutation-2-descriptor])]
(behavior "Walks the list of queued mutations in env"
(when-mocking!
(comp/transact! comp tx options)
=1x=> (assertions
"Calls transact with the (1st) mutation delegate and the mutation descriptor "
tx => `[(uism/mutation-delegate ~mutation-1-descriptor)])
(comp/transact! comp tx options)
=1x=> (assertions
"Calls transact with the (2nd) mutation delegate and the mutation descriptor "
tx => `[(uism/mutation-delegate ~mutation-2-descriptor)])
(uism/queue-mutations! mock-app menv)))))
(specification "convert-load-options"
(let [load-options (uism/convert-load-options env {::comp/component-class AClass ::uism/ok-event :blah})]
(assertions
"always sets a fallback function (that will send a default load-error event)"
(:fallback load-options) => `uism/handle-load-error
"removes any of the UISM-specific options from the map"
(contains? load-options ::comp/component-class) => false
(contains? load-options ::uism/ok-event) => false
"defaults load markers to an explicit false"
(false? (:marker load-options)) => true))
(let [load-options (uism/convert-load-options env {::uism/ok-event :blah})]
(assertions
"Sets the post event handler and post event if there is a post-event"
(-> load-options :post-mutation-params ::uism/event-id) => :blah
(:post-mutation load-options) => `uism/trigger-state-machine-event))
(let [load-options (uism/convert-load-options env {::uism/error-event :foo
::uism/error-data {:y 1}})]
(assertions
"Sets fallback event and params if present"
(-> load-options :post-mutation-params ::uism/error-event) => :foo
(-> load-options :post-mutation-params ::uism/error-data) => {:y 1})))
(specification "handle-load-error*"
(behavior "When there is an error event in the original load request (post mutation params)"
(when-mocking
(comp/transact! r tx) => (let [{:keys [params]} (-> tx eql/query->ast1)
{::uism/keys [event-id event-data asm-id]} params]
(assertions
"it triggers that event with the error data"
event-id => :foo
event-data => {:y 1}
asm-id => :fake))
(uism/handle-load-error* (app/fulcro-app {}) {:post-mutation-params {::uism/asm-id :fake
::uism/error-event :foo
::uism/error-data {:y 1}}})))
(behavior "When the error event is not present in the original load request (post mutation params)"
(when-mocking
(comp/transact! r tx) => (let [{:keys [params]} (-> tx eql/query->ast1)
{::uism/keys [event-id event-data asm-id]} params]
(assertions
"it triggers ::uism/load-error"
event-id => ::uism/load-error
asm-id => :fake))
(uism/handle-load-error* (app/fulcro-app {}) {:post-mutation-params {::uism/asm-id :fake}}))))
(specification "queue-actor-load!"
(let [app (app/fulcro-app {})
env (assoc env ::uism/queued-loads [])
load-called? (atom false)]
(when-mocking!
(uism/actor->ident e actor) =1x=> [:actor 1]
(df/load! r ident class params) =1x=> (do
(reset! load-called? true)
(assertions
"Sends a real load to fulcro containing: the proper actor ident"
ident => [:actor 1]
"the correct component class"
class => AClass
"The params with specified load options"
params => {:marker false})
true)
(uism/queue-actor-load! app env :dialog AClass {:marker false}))))
#?(:cljs
(let [fulcro-state (atom {})
mutation-env (mutation-env fulcro-state [] {:ref [:TABLE 1]})
event {::uism/event-id :boggle ::uism/asm-id :fake}]
(specification "trigger-state-machine-event!"
(let [handler (fn [env] (assoc env :handler-ran true))
final-env? (fn [env]
(assertions
"Receives the final env"
(:looked-up-env env) => true
(:applied-event-values env) => true
(:handler-ran env) => true))]
(when-mocking!
(uism/state-machine-env s r a e d) => (assoc env :looked-up-env true)
(uism/clear-timeouts-on-event! env event) => (do
(assertions
"Clears any auto-cleared timeouts"
true => true)
(assoc env :cleared-timeouts event))
(uism/active-state-handler e) => handler
(uism/apply-event-value env evt) => (assoc env :applied-event-values true)
;; not calling the mocks on these will cause fail. our assertion is just
;; for pos output
(uism/queue-mutations! r e) => (do (final-env? e)
(assertions
"Tries to queue mutations using the final env"
true => true)
nil)
(uism/queue-loads! r env) => (do (final-env? env)
(assertions
"Tries to queue loads using the final env"
true => true)
nil)
(uism/update-fulcro-state! env satom) => (do (final-env? env)
(assertions
"Tries to update fulcro state"
satom => fulcro-state)
nil)
(uism/ui-refresh-list env) => [[:x :y]]
(uism/trigger-queued-events! menv triggers list) =1x=> (do
(assertions
"processes events that handlers queued."
(count triggers) => 0)
list)
;; ACTION UNDER TEST
(let [actual (uism/trigger-state-machine-event! mutation-env event)]
(assertions
"returns the list of things to refresh in the UI"
actual => [[:x :y]])))))))
(specification "trigger-queued-events!"
(let [mutation-env (mutation-env (atom {}) [:fake] {:ref [:TABLE 1]})
event-1 {::uism/asm-id :a ::uism/event-id :event-1 ::uism/event-data {:a 1}}
event-2 {::uism/asm-id :b ::uism/event-id :event-2 ::uism/event-data {:a 2}}
triggers [event-1 event-2]]
(when-mocking!
(uism/trigger-state-machine-event! menv event) =1x=> (do
(assertions
"Triggers the queued event"
event => event-1
"with the mutation env"
(= menv mutation-env) => true)
[[:b 2]])
(uism/trigger-state-machine-event! menv event) =1x=> (do
(assertions
"Triggers the queued event"
event => event-2
"with the mutation env"
(= mutation-env menv) => true)
[[:c 3]])
(let [actual (uism/trigger-queued-events! mutation-env triggers [[:A 1]])]
(assertions
"Accumulates and returns the actors to refresh"
actual => [[:A 1] [:b 2] [:c 3]])))))
(specification "trigger-state-machine-event mutation"
(let [trigger {::uism/asm-id :a ::uism/event-id :x}
menv (mutation-env (atom {}) [(uism/trigger-state-machine-event trigger)] {})
{:keys [action]} (m/mutate menv)]
(when-mocking!
(uism/trigger-state-machine-event! mutation-env p) => (do
(assertions
"runs the state machine event"
(= mutation-env menv) => true
p => trigger)
[[:table 1]])
(app/schedule-render! app options) => (assertions
"Queues the actors for UI refresh"
(nil? app) => false)
(action menv))))
(specification "set-string!"
(provided! "The user supplies a string"
(uism/trigger! this smid event params) => (do
(assertions
"Triggers a value-changed event"
event => ::uism/value-changed
"on a named state machine"
smid => :fake
"whose parameters specify the new value"
(::uism/alias params) => :username
(:value params) => "hello")
nil)
(uism/set-string! {} :fake :username "hello"))
#?(:cljs
(provided! "The user supplies a js DOM onChange event"
(uism/trigger! this smid event params) => (do
(assertions
"Triggers a value-changed event"
event => ::uism/value-changed
"on a named state machine"
smid => :fake
"with the extracted string value"
(::uism/alias params) => :username
(:value params) => "hi")
nil)
(uism/set-string! {} :fake :username #js {:target #js {:value "hi"}}))))
(specification "derive-actor-components"
(let [actual (uism/derive-actor-components {:a [:x 1]
:b AClass
:d (uism/with-actor-class [:A 1] AClass)})]
(assertions
"allows a bare ident (no mapping)"
(:a actual) => nil
"accepts a singleton classes"
(:b actual) => ::AClass
;; Need enzyme configured consistently for this test
;"accepts a react instance"
;(:c actual) => ::AClass
"finds class on metadata"
(:d actual) => ::AClass)))
(specification "derive-actor-idents"
(let [actual (uism/derive-actor-idents {:a [:x 1]
:b AClass
:d (uism/with-actor-class [:A 1] AClass)})]
(assertions
"allows a bare ident"
(:a actual) => [:x 1]
"finds the ident on singleton classes"
(:b actual) => [:A 1]
"remembers the singleton class as metadata"
(:b actual) => [:A 1]
;; Need enzyme configured consistently for this test
;"remembers the class of a react instance"
;(:c actual) => [:A 1]
"records explicit idents that use with-actor-class"
(:d actual) => [:A 1])))
(specification "set-timeout"
(let [new-env (uism/set-timeout env :timer/my-timer :event/bam! {} 100)
descriptor (some-> new-env ::uism/queued-timeouts first)]
(assertions
"Adds a timeout descriptor to the queued timeouts"
(s/valid? ::uism/timeout-descriptor descriptor) => true
"whose default auto-cancel is constantly false"
(some-> descriptor ::uism/cancel-on meta :cancel-on (apply [:x])) => false)))
(let [prior-timer {::uism/timeout 100
::uism/timer-id :timer/id
::uism/js-timer (with-meta {} {:timer :mock-js-timer})
::uism/event-id :bam!
::uism/cancel-on (with-meta {} {:cancel-on (constantly true)})}
env-with-active-timer (assoc-in env (uism/asm-path env [::uism/active-timers :timer/id]) prior-timer)]
(specification "schedule-timeouts!"
(provided! "There isn't already a timer under that ID"
(uism/get-js-timer e t) =1x=> nil
(uism/set-js-timeout! f t) =1x=> (assertions
"sets the low-level timer with the correct time"
t => 100)
(let [prepped-env (uism/set-timeout env :timer/id :bam! {} 100)
new-env (uism/schedule-timeouts! (app/fulcro-app {}) prepped-env)]
(assertions
"Adds a timeout descriptor to active timers"
(s/valid? ::uism/timeout-descriptor
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])))
=> true)))
(provided! "There IS a timer under that ID"
(uism/get-js-timer e t) =1x=> :low-level-js-timer
(uism/clear-js-timeout! t) =1x=> (assertions
"Clears the old timer"
t => :low-level-js-timer)
(uism/set-js-timeout! f t) =1x=> (assertions
"sets the low-level timer with the correct time"
t => 300)
(let [prepped-env (uism/set-timeout env-with-active-timer :timer/id :bam! {} 300)
new-env (uism/schedule-timeouts! (app/fulcro-app {}) prepped-env)]
(assertions
"Adds a timeout descriptor to active timers"
(s/valid? ::uism/timeout-descriptor
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])))
=> true))))
(specification "clear-timeout!"
(provided! "The timer exists"
(uism/clear-js-timeout! t) => (assertions
"clears the timer"
t => :mock-js-timer)
(let [new-env (uism/clear-timeout! env-with-active-timer :timer/id)]
(assertions
"Removes the timer from the active timers table"
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])) => nil))))
(specification "clear-timeouts-on-event!"
(provided! "clear-timeout! works correctly"
(uism/clear-timeout! e t) => (assoc e :cleared? true)
(let [new-env (uism/clear-timeouts-on-event! env-with-active-timer :bam!)]
(assertions
"Clears and removes the timer"
(:cleared? new-env) => true))))))
;; not usable from clj
(specification "begin!"
(let [fulcro-state (atom {})]
(component "(the begin mutation)"
(let [creation-args {::uism/state-machine-id `test-machine
::uism/asm-id :fake
::uism/actor->ident {:dialog [:table 1]}}
mutation-env (mutation-env fulcro-state [(uism/begin creation-args)] {:ref [:TABLE 1]})
{:keys [action]} (m/mutate mutation-env)
real-new-asm uism/new-asm]
(when-mocking!
(uism/new-asm p) =1x=> (do
(assertions
"creates a new asm with the provided params"
p => creation-args)
(real-new-asm p))
(uism/trigger-state-machine-event! e p) =1x=> (do
(assertions
"triggers the ::started event"
(::uism/event-id p) => ::uism/started
(::uism/asm-id p) => :fake)
[[:A 1]])
(app/schedule-render! app) => (assertions
"Updates the UI"
(nil? app) => false)
(action mutation-env)
(assertions
"and stores it in fulcro state"
(contains? (::uism/asm-id @fulcro-state) :fake) => true))))
#?(:cljs
(component "(the wrapper function begin!)"
(when-mocking
(comp/transact! t tx) => (assertions
"runs fulcro transact on the begin mutation"
(ffirst tx) => `uism/begin)
(uism/begin! mock-app test-machine :fake {:dialog [:table 1]}))))))
(uism/defstatemachine ctm {::uism/aliases {:x [:dialog :foo]}
::uism/actor-names #{:dialog}
::uism/states {:initial {::uism/handler (fn [env] env)}}})
(specification "compute-target"
(let [asm (uism/new-asm {::uism/state-machine-id `ctm ::uism/asm-id :fake
::uism/actor->ident {:dialog [:dialog 1]}})
test-env (uism/state-machine-env {::uism/asm-id {:fake asm}} nil :fake :do {})]
(behavior "accepts (and returns) any kind of raw fulcro target"
(assertions
"(normal target)"
(uism/compute-target test-env {::targeting/target [:a 1]}) => [:a 1]
"(special target)"
(uism/compute-target test-env {::targeting/target (targeting/append-to [:a 1])}) => [:a 1]
(targeting/special-target? (uism/compute-target test-env {::targeting/target (targeting/append-to [:a 1])})) => true))
(behavior "Resolves actors"
(assertions
(uism/compute-target test-env {::uism/target-actor :dialog}) => [:dialog 1]
"can combine plain targets with actor targets"
(uism/compute-target test-env {::targeting/target [:a 1] ::uism/target-actor :dialog}) => [[:a 1] [:dialog 1]]
(targeting/multiple-targets? (uism/compute-target test-env {::targeting/target [:a 1]
::uism/target-actor :dialog}))
=> true
"can combine actor targets with a multiple-target"
(uism/compute-target test-env {::targeting/target (targeting/multiple-targets [:a 1] [:b 2])
::uism/target-actor :dialog})
=> [[:a 1] [:b 2] [:dialog 1]]))
(behavior "Resolves aliases"
(assertions
(uism/compute-target test-env {::uism/target-alias :x}) => [:dialog 1 :foo]
"can combine plain targets with alias targets"
(uism/compute-target test-env {::targeting/target [:a 1] ::uism/target-alias :x}) => [[:a 1] [:dialog 1 :foo]]
(targeting/multiple-targets? (uism/compute-target test-env {::targeting/target [:a 1]
::uism/target-alias :x}))
=> true
"can combine alias targets with a multiple-target"
(uism/compute-target test-env {::targeting/target (targeting/multiple-targets [:a 1] [:b 2])
::uism/target-alias :x})
=> [[:a 1] [:b 2] [:dialog 1 :foo]]))))
|
68491
|
(ns com.fulcrologic.fulcro.ui-state-machines-spec
(:require
[clojure.spec.alpha :as s]
[com.fulcrologic.guardrails.core :refer [>defn]]
[com.fulcrologic.fulcro.algorithms.data-targeting :as targeting]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.specs]
[edn-query-language.core :as eql]
[fulcro-spec.core :refer [specification provided provided! when-mocking when-mocking! behavior assertions component]]))
(declare => =1x=>)
(def mock-app (app/fulcro-app))
(defn mutation-env [state-atom tx extra-env]
(-> mock-app
(assoc ::app/state-atom state-atom)
(txn/build-env (txn/tx-node tx) extra-env)
(assoc :ast (eql/query->ast1 tx))))
(defsc AClass [_ _] {:query ['*] :ident (fn [] [:A 1])})
(defn A-handler [env] env)
(uism/defstatemachine test-machine
{::uism/actor-names #{:dialog}
::uism/aliases {:visible? [:dialog :ui/active?]
:title [:dialog :title]
:widgets [:dialog :linked-widgets]
:uberwidgets [:dialog :other-widgets]
:username [:dialog :name]}
::uism/plugins {:f? (fn [{:keys [visible? username]}]
(when visible? username))}
::uism/states {:initial {::uism/handler (fn [env]
(with-meta env {:handler-ran true}))}
:B {::uism/events {:bang! {::uism/handler (fn [env] (uism/store env :handler-ran? true))
::uism/target-state :A
::uism/event-predicate (fn [env] (uism/retrieve env :enabled? false))}}}
:C {::uism/events {:bang! {::uism/handler (fn [env] (uism/store env :handler-ran? true))
::uism/target-state :A}}}
:D {::uism/events {:bang! {::uism/handler (fn [env] (uism/activate env :A))
::uism/target-state :B}}}
:A {::uism/handler A-handler}}})
(def base-fulcro-state
{:TABLE {1 {:ui/active? false :name "<NAME>"
:other-widgets []
:linked-widgets [[:widget/by-id 1]]}
2 {:ui/active? true :name "<NAME>"
:other-widgets []
:linked-widgets [[:widget/by-id 2]]}}
:widget/by-id {1 {:id 1}
2 {:id 2}
3 {:id 3}}
::uism/asm-id {:fake (uism/new-asm
{::uism/state-machine-id `test-machine
::uism/asm-id :fake
::uism/actor->component-name {:dialog (uism/any->actor-component-registry-key AClass)}
::uism/actor->ident {:dialog [:TABLE 1]}})}})
(defn test-env [event-id event-data]
(uism/state-machine-env base-fulcro-state [:TABLE 1] :fake event-id event-data))
(specification "State Machine Registry"
(assertions
"Registers the FQ symbol of the state machine"
(map? (uism/get-state-machine `test-machine)) => true
"Stores the definition at that symbol"
(::uism/actor-names (uism/get-state-machine `test-machine)) => #{:dialog}
"Allows lookup of a value via an active env and a machine key"
(uism/lookup-state-machine-field (test-env :event nil) ::uism/actor-names) => #{:dialog}))
(specification "state-machine-env"
(assertions
"produces a spec-compliant result"
(s/valid? ::uism/env (uism/state-machine-env {} [:a 1] :x :evt {})) => true))
(let [env (test-env nil nil)]
(specification "asm-value"
(assertions "Finds things in the active state machine"
(uism/asm-value env ::uism/asm-id) => :fake))
(specification "activate"
(assertions
"Sets the given active state in the env"
(-> env
(uism/activate :A)
(uism/asm-value ::uism/active-state)) => :A)
(assertions
"Ignores a requst to move to an invalid state (logs an error)"
(-> env
(uism/activate :crap)
(uism/asm-value ::uism/active-state)) => :initial))
(specification "store/retrieve"
(assertions
"Allows for the local storage or asm-local values"
(-> env (uism/store :x true) (uism/retrieve :x)) => true
(-> env (uism/store :x 0) (uism/retrieve :x)) => 0
(-> env (uism/store :x {}) (uism/retrieve :x)) => {}
(-> env (uism/store :v 1) (uism/retrieve :v)) => 1))
(specification "resolve-alias"
(assertions
"Returns the Fulcro state path for a given data alias"
(uism/resolve-alias env :username) => [:TABLE 1 :name])
(assertions
"Returns nil if it is an invalid alias"
(uism/resolve-alias env :crap) => nil))
(specification "actor-path"
(assertions
"Returns the Fulcro ident of an actor"
(uism/actor-path env :dialog) => [:TABLE 1]
"Returns the Fulcro path to data in an actor if a field is included"
(uism/actor-path env :dialog :boo) => [:TABLE 1 :boo]))
(specification "actor-class"
(assertions
"Returns the Fulcro class of an actor"
(uism/actor-class env :dialog) => AClass))
(specification "set-actor-value"
(assertions
"Sets a raw (non-aliased) attribute in Fulcro state on an actor"
(-> env
(uism/set-actor-value :dialog :boo 42)
::uism/state-map
:TABLE
(get 1)
:boo) => 42
"Which can be read by actor-value"
(-> env
(uism/set-actor-value :dialog :boo 42)
(uism/actor-value :dialog :boo)) => 42))
(specification "alias-value"
(assertions
"Returns nil if the alias isn't valid"
(uism/alias-value env :name) => nil
"Gets the value of the fulro state that the alias refers to"
(uism/alias-value env :username) => "Joe"))
(specification "set-aliased-value"
(assertions
"Can set a single value"
(-> env
(uism/set-aliased-value :title "Hello")
(uism/alias-value :title)) => "Hello"
"Can set two values"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe")
(uism/alias-value :title)) => "Hello"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe")
(uism/alias-value :username)) => "Joe"
"Can set more than 2 values"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe" :visible? :booga)
(uism/alias-value :visible?)) => :booga)
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "<NAME>") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/set-aliased-value :username "<NAME>")
::uism/state-map
:TABLE
(get 1)
:name) => "<NAME>"))
(specification "reset-actor-ident"
(let [env (uism/reset-actor-ident env :dialog [:TABLE 2])]
(assertions
"Can update actor/ident indexes"
(uism/asm-value env ::uism/actor->ident) => {:dialog [:TABLE 2]}
(uism/asm-value env ::uism/ident->actor) => {[:TABLE 2] :dialog}
"Class index is correct"
(uism/actor-class env :dialog) => AClass
(uism/asm-value env ::uism/actor->component-name) => {:dialog ::AClass}))
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "<NAME>") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/assoc-aliased :username "<NAME>")
::uism/state-map
:TABLE
(get 1)
:name) => "<NAME>"))
(specification "assoc-aliased"
(assertions
"Can set a single value"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/alias-value :title)) => "Hello"
"Can set two values"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe")
(uism/alias-value :title)) => "Hello"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe")
(uism/alias-value :username)) => "Joe"
"Can set more than 2 values"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe" :visible? :booga)
(uism/alias-value :visible?)) => :booga)
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "<NAME>") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/assoc-aliased :username "<NAME>")
::uism/state-map
:TABLE
(get 1)
:name) => "<NAME>"))
(specification "update-aliased"
(assertions
"Can update a value"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/update-aliased :title #(str % "-suffix"))
(uism/alias-value :title)) => "Hello-suffix"
"Can update a value with arguments"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/update-aliased :title #(str %1 %2 %3) 1 2)
(uism/alias-value :title)) => "Hello12"))
(specification "dissoc-aliased"
(let [env (uism/assoc-aliased env :title "Hello" :username "Joe")]
(let [entries (-> env
(uism/dissoc-aliased :title)
(get-in [::uism/state-map :TABLE 1])
(-> keys set))]
(assertions
"Can dissoc a single alias"
(contains? entries :title) => false))
(let [entries (-> env
(uism/dissoc-aliased :title :username)
(get-in [::uism/state-map :TABLE 1])
(-> keys set))]
(assertions
"Can dissoc multiple aliases"
(contains? entries :title) => false
(contains? entries :name) => false))))
(specification "integrate-ident"
(assertions
"Accepts a list of operations"
(let [nenv (uism/integrate-ident env [:widget/by-id 2] :prepend :widgets
:append :uberwidgets)]
(select-keys (get-in nenv [::uism/state-map :TABLE 1]) #{:other-widgets :linked-widgets}))
=> {:linked-widgets [[:widget/by-id 2] [:widget/by-id 1]]
:other-widgets [[:widget/by-id 2]]}
"Can prepend an ident"
(-> env
(uism/integrate-ident [:widget/by-id 2] :prepend :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 2] [:widget/by-id 1]]
"Can append an ident"
(-> env
(uism/integrate-ident [:widget/by-id 3] :append :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1] [:widget/by-id 3]]
"Integrating an already present ident has no effect"
(-> env
(uism/integrate-ident [:widget/by-id 1] :prepend :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]
(-> env
(uism/integrate-ident [:widget/by-id 1] :append :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]))
(specification "remove-ident"
(assertions
"Can remove an ident"
(-> env
(uism/remove-ident [:widget/by-id 1] :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => []
"Removing a non-present ident has no effect"
(-> env
(uism/remove-ident [:widget/by-id 2] :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]))
(specification "aliased-data"
(assertions
"Builds a map of all of the current values of aliased data"
(-> env
(uism/aliased-data)) => {:visible? false
:title nil
:widgets [[:widget/by-id 1]]
:uberwidgets []
:username "Joe"}))
(specification "run"
(assertions
"Runs a plugin against the env"
(-> env
(uism/set-aliased-value :visible? true)
(uism/run :f?)) => "<NAME>"
"Can be passed extra data that can overwrite aliased values"
(-> env
(uism/set-aliased-value :visible? true)
(uism/run :f? {:visible? false})) => nil))
(specification "active-state-handler"
(provided! "The state machine definition is missing or the active state has no handler"
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:boo)
(assertions
"returns core identity"
(uism/active-state-handler env) => identity))
(let [env (-> (test-env :bang! nil) (uism/activate :B) (uism/store :enabled? true))
handler (fn geh* [e] e)]
(provided! "The state machine definition has event definitions"
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:boo)
(uism/generic-event-handler e) => handler
(assertions
"returns a generic-event-handler"
(uism/active-state-handler env) => handler)))
(provided! "The state machine definition exists and there is an active state."
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:A)
(assertions
"returns the correct handler"
(uism/active-state-handler env) => A-handler)))
(specification "generic-event-handler"
(let [disabled-env (-> (test-env :bang! nil) (uism/activate :B) (uism/store :enabled? false))
enabled-env (-> disabled-env (uism/store :enabled? true))
non-event-env (-> (test-env :boo nil) (uism/activate :A))
missing-handler (uism/generic-event-handler non-event-env)
disabled-handler (uism/generic-event-handler disabled-env)
enabled-handler (uism/generic-event-handler enabled-env)
no-predicate-env (-> enabled-env (uism/activate :C))
no-predicate-handler (uism/generic-event-handler no-predicate-env)
overriding-handler-env (-> disabled-env (uism/activate :D))
overriding-handler (uism/generic-event-handler overriding-handler-env)
actual-disabled-result (disabled-handler disabled-env)
actual-enabled-result (enabled-handler enabled-env)
no-predicate-result (no-predicate-handler no-predicate-env)
overriding-handler-result (overriding-handler overriding-handler-env)]
(behavior "when the event definition is missing"
(assertions
"Returns nil"
missing-handler => nil))
(behavior "When there is no predicate"
(assertions
"Runs the handler"
(-> no-predicate-result (uism/retrieve :handler-ran? false)) => true
"Follows the transition, if defined"
(-> no-predicate-result (uism/asm-value ::uism/active-state)) => :A))
(behavior "when the predicate is false"
(assertions
"Does not runs the handler"
(-> actual-disabled-result (uism/retrieve :handler-ran? false)) => false
"Stays in the same state"
(-> actual-disabled-result (uism/asm-value ::uism/active-state)) => :B))
(behavior "when the predicate is true"
(assertions
"Runs the handler"
(-> actual-enabled-result (uism/retrieve :handler-ran? false)) => true
"Follows the transition, if defined"
(-> actual-enabled-result (uism/asm-value ::uism/active-state)) => :A))
(behavior "when the handler activates a target state different from the *declared* target state"
(assertions
"The handler wins"
(-> overriding-handler-result (uism/asm-value ::uism/active-state)) => :A))))
(specification "apply-event-value"
(assertions
"returns an unmodified env for other events"
(uism/apply-event-value env {::uism/event-id :random-event}) => env
"applies a change to fulcro state based on the ::value-changed event"
(-> env
(uism/apply-event-value {::uism/event-id ::uism/value-changed
::uism/event-data {::uism/alias :visible?
:value :new-value}})
(uism/alias-value :visible?)) => :new-value))
(specification "queue-mutations!"
(let [mutation-1-descriptor {::uism/mutation-context :dialog
::uism/ok-event :pow!
::uism/mutation `a}
mutation-2-descriptor {::uism/mutation-context :dialog
::uism/ok-event :bam!
::uism/mutation `b}
menv1 (assoc env ::uism/queued-mutations [mutation-1-descriptor])
menv (assoc env ::uism/queued-mutations [mutation-1-descriptor
mutation-2-descriptor])]
(behavior "Walks the list of queued mutations in env"
(when-mocking!
(comp/transact! comp tx options)
=1x=> (assertions
"Calls transact with the (1st) mutation delegate and the mutation descriptor "
tx => `[(uism/mutation-delegate ~mutation-1-descriptor)])
(comp/transact! comp tx options)
=1x=> (assertions
"Calls transact with the (2nd) mutation delegate and the mutation descriptor "
tx => `[(uism/mutation-delegate ~mutation-2-descriptor)])
(uism/queue-mutations! mock-app menv)))))
(specification "convert-load-options"
(let [load-options (uism/convert-load-options env {::comp/component-class AClass ::uism/ok-event :blah})]
(assertions
"always sets a fallback function (that will send a default load-error event)"
(:fallback load-options) => `uism/handle-load-error
"removes any of the UISM-specific options from the map"
(contains? load-options ::comp/component-class) => false
(contains? load-options ::uism/ok-event) => false
"defaults load markers to an explicit false"
(false? (:marker load-options)) => true))
(let [load-options (uism/convert-load-options env {::uism/ok-event :blah})]
(assertions
"Sets the post event handler and post event if there is a post-event"
(-> load-options :post-mutation-params ::uism/event-id) => :blah
(:post-mutation load-options) => `uism/trigger-state-machine-event))
(let [load-options (uism/convert-load-options env {::uism/error-event :foo
::uism/error-data {:y 1}})]
(assertions
"Sets fallback event and params if present"
(-> load-options :post-mutation-params ::uism/error-event) => :foo
(-> load-options :post-mutation-params ::uism/error-data) => {:y 1})))
(specification "handle-load-error*"
(behavior "When there is an error event in the original load request (post mutation params)"
(when-mocking
(comp/transact! r tx) => (let [{:keys [params]} (-> tx eql/query->ast1)
{::uism/keys [event-id event-data asm-id]} params]
(assertions
"it triggers that event with the error data"
event-id => :foo
event-data => {:y 1}
asm-id => :fake))
(uism/handle-load-error* (app/fulcro-app {}) {:post-mutation-params {::uism/asm-id :fake
::uism/error-event :foo
::uism/error-data {:y 1}}})))
(behavior "When the error event is not present in the original load request (post mutation params)"
(when-mocking
(comp/transact! r tx) => (let [{:keys [params]} (-> tx eql/query->ast1)
{::uism/keys [event-id event-data asm-id]} params]
(assertions
"it triggers ::uism/load-error"
event-id => ::uism/load-error
asm-id => :fake))
(uism/handle-load-error* (app/fulcro-app {}) {:post-mutation-params {::uism/asm-id :fake}}))))
(specification "queue-actor-load!"
(let [app (app/fulcro-app {})
env (assoc env ::uism/queued-loads [])
load-called? (atom false)]
(when-mocking!
(uism/actor->ident e actor) =1x=> [:actor 1]
(df/load! r ident class params) =1x=> (do
(reset! load-called? true)
(assertions
"Sends a real load to fulcro containing: the proper actor ident"
ident => [:actor 1]
"the correct component class"
class => AClass
"The params with specified load options"
params => {:marker false})
true)
(uism/queue-actor-load! app env :dialog AClass {:marker false}))))
#?(:cljs
(let [fulcro-state (atom {})
mutation-env (mutation-env fulcro-state [] {:ref [:TABLE 1]})
event {::uism/event-id :boggle ::uism/asm-id :fake}]
(specification "trigger-state-machine-event!"
(let [handler (fn [env] (assoc env :handler-ran true))
final-env? (fn [env]
(assertions
"Receives the final env"
(:looked-up-env env) => true
(:applied-event-values env) => true
(:handler-ran env) => true))]
(when-mocking!
(uism/state-machine-env s r a e d) => (assoc env :looked-up-env true)
(uism/clear-timeouts-on-event! env event) => (do
(assertions
"Clears any auto-cleared timeouts"
true => true)
(assoc env :cleared-timeouts event))
(uism/active-state-handler e) => handler
(uism/apply-event-value env evt) => (assoc env :applied-event-values true)
;; not calling the mocks on these will cause fail. our assertion is just
;; for pos output
(uism/queue-mutations! r e) => (do (final-env? e)
(assertions
"Tries to queue mutations using the final env"
true => true)
nil)
(uism/queue-loads! r env) => (do (final-env? env)
(assertions
"Tries to queue loads using the final env"
true => true)
nil)
(uism/update-fulcro-state! env satom) => (do (final-env? env)
(assertions
"Tries to update fulcro state"
satom => fulcro-state)
nil)
(uism/ui-refresh-list env) => [[:x :y]]
(uism/trigger-queued-events! menv triggers list) =1x=> (do
(assertions
"processes events that handlers queued."
(count triggers) => 0)
list)
;; ACTION UNDER TEST
(let [actual (uism/trigger-state-machine-event! mutation-env event)]
(assertions
"returns the list of things to refresh in the UI"
actual => [[:x :y]])))))))
(specification "trigger-queued-events!"
(let [mutation-env (mutation-env (atom {}) [:fake] {:ref [:TABLE 1]})
event-1 {::uism/asm-id :a ::uism/event-id :event-1 ::uism/event-data {:a 1}}
event-2 {::uism/asm-id :b ::uism/event-id :event-2 ::uism/event-data {:a 2}}
triggers [event-1 event-2]]
(when-mocking!
(uism/trigger-state-machine-event! menv event) =1x=> (do
(assertions
"Triggers the queued event"
event => event-1
"with the mutation env"
(= menv mutation-env) => true)
[[:b 2]])
(uism/trigger-state-machine-event! menv event) =1x=> (do
(assertions
"Triggers the queued event"
event => event-2
"with the mutation env"
(= mutation-env menv) => true)
[[:c 3]])
(let [actual (uism/trigger-queued-events! mutation-env triggers [[:A 1]])]
(assertions
"Accumulates and returns the actors to refresh"
actual => [[:A 1] [:b 2] [:c 3]])))))
(specification "trigger-state-machine-event mutation"
(let [trigger {::uism/asm-id :a ::uism/event-id :x}
menv (mutation-env (atom {}) [(uism/trigger-state-machine-event trigger)] {})
{:keys [action]} (m/mutate menv)]
(when-mocking!
(uism/trigger-state-machine-event! mutation-env p) => (do
(assertions
"runs the state machine event"
(= mutation-env menv) => true
p => trigger)
[[:table 1]])
(app/schedule-render! app options) => (assertions
"Queues the actors for UI refresh"
(nil? app) => false)
(action menv))))
(specification "set-string!"
(provided! "The user supplies a string"
(uism/trigger! this smid event params) => (do
(assertions
"Triggers a value-changed event"
event => ::uism/value-changed
"on a named state machine"
smid => :fake
"whose parameters specify the new value"
(::uism/alias params) => :username
(:value params) => "hello")
nil)
(uism/set-string! {} :fake :username "hello"))
#?(:cljs
(provided! "The user supplies a js DOM onChange event"
(uism/trigger! this smid event params) => (do
(assertions
"Triggers a value-changed event"
event => ::uism/value-changed
"on a named state machine"
smid => :fake
"with the extracted string value"
(::uism/alias params) => :username
(:value params) => "hi")
nil)
(uism/set-string! {} :fake :username #js {:target #js {:value "hi"}}))))
(specification "derive-actor-components"
(let [actual (uism/derive-actor-components {:a [:x 1]
:b AClass
:d (uism/with-actor-class [:A 1] AClass)})]
(assertions
"allows a bare ident (no mapping)"
(:a actual) => nil
"accepts a singleton classes"
(:b actual) => ::AClass
;; Need enzyme configured consistently for this test
;"accepts a react instance"
;(:c actual) => ::AClass
"finds class on metadata"
(:d actual) => ::AClass)))
(specification "derive-actor-idents"
(let [actual (uism/derive-actor-idents {:a [:x 1]
:b AClass
:d (uism/with-actor-class [:A 1] AClass)})]
(assertions
"allows a bare ident"
(:a actual) => [:x 1]
"finds the ident on singleton classes"
(:b actual) => [:A 1]
"remembers the singleton class as metadata"
(:b actual) => [:A 1]
;; Need enzyme configured consistently for this test
;"remembers the class of a react instance"
;(:c actual) => [:A 1]
"records explicit idents that use with-actor-class"
(:d actual) => [:A 1])))
(specification "set-timeout"
(let [new-env (uism/set-timeout env :timer/my-timer :event/bam! {} 100)
descriptor (some-> new-env ::uism/queued-timeouts first)]
(assertions
"Adds a timeout descriptor to the queued timeouts"
(s/valid? ::uism/timeout-descriptor descriptor) => true
"whose default auto-cancel is constantly false"
(some-> descriptor ::uism/cancel-on meta :cancel-on (apply [:x])) => false)))
(let [prior-timer {::uism/timeout 100
::uism/timer-id :timer/id
::uism/js-timer (with-meta {} {:timer :mock-js-timer})
::uism/event-id :bam!
::uism/cancel-on (with-meta {} {:cancel-on (constantly true)})}
env-with-active-timer (assoc-in env (uism/asm-path env [::uism/active-timers :timer/id]) prior-timer)]
(specification "schedule-timeouts!"
(provided! "There isn't already a timer under that ID"
(uism/get-js-timer e t) =1x=> nil
(uism/set-js-timeout! f t) =1x=> (assertions
"sets the low-level timer with the correct time"
t => 100)
(let [prepped-env (uism/set-timeout env :timer/id :bam! {} 100)
new-env (uism/schedule-timeouts! (app/fulcro-app {}) prepped-env)]
(assertions
"Adds a timeout descriptor to active timers"
(s/valid? ::uism/timeout-descriptor
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])))
=> true)))
(provided! "There IS a timer under that ID"
(uism/get-js-timer e t) =1x=> :low-level-js-timer
(uism/clear-js-timeout! t) =1x=> (assertions
"Clears the old timer"
t => :low-level-js-timer)
(uism/set-js-timeout! f t) =1x=> (assertions
"sets the low-level timer with the correct time"
t => 300)
(let [prepped-env (uism/set-timeout env-with-active-timer :timer/id :bam! {} 300)
new-env (uism/schedule-timeouts! (app/fulcro-app {}) prepped-env)]
(assertions
"Adds a timeout descriptor to active timers"
(s/valid? ::uism/timeout-descriptor
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])))
=> true))))
(specification "clear-timeout!"
(provided! "The timer exists"
(uism/clear-js-timeout! t) => (assertions
"clears the timer"
t => :mock-js-timer)
(let [new-env (uism/clear-timeout! env-with-active-timer :timer/id)]
(assertions
"Removes the timer from the active timers table"
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])) => nil))))
(specification "clear-timeouts-on-event!"
(provided! "clear-timeout! works correctly"
(uism/clear-timeout! e t) => (assoc e :cleared? true)
(let [new-env (uism/clear-timeouts-on-event! env-with-active-timer :bam!)]
(assertions
"Clears and removes the timer"
(:cleared? new-env) => true))))))
;; not usable from clj
(specification "begin!"
(let [fulcro-state (atom {})]
(component "(the begin mutation)"
(let [creation-args {::uism/state-machine-id `test-machine
::uism/asm-id :fake
::uism/actor->ident {:dialog [:table 1]}}
mutation-env (mutation-env fulcro-state [(uism/begin creation-args)] {:ref [:TABLE 1]})
{:keys [action]} (m/mutate mutation-env)
real-new-asm uism/new-asm]
(when-mocking!
(uism/new-asm p) =1x=> (do
(assertions
"creates a new asm with the provided params"
p => creation-args)
(real-new-asm p))
(uism/trigger-state-machine-event! e p) =1x=> (do
(assertions
"triggers the ::started event"
(::uism/event-id p) => ::uism/started
(::uism/asm-id p) => :fake)
[[:A 1]])
(app/schedule-render! app) => (assertions
"Updates the UI"
(nil? app) => false)
(action mutation-env)
(assertions
"and stores it in fulcro state"
(contains? (::uism/asm-id @fulcro-state) :fake) => true))))
#?(:cljs
(component "(the wrapper function begin!)"
(when-mocking
(comp/transact! t tx) => (assertions
"runs fulcro transact on the begin mutation"
(ffirst tx) => `uism/begin)
(uism/begin! mock-app test-machine :fake {:dialog [:table 1]}))))))
(uism/defstatemachine ctm {::uism/aliases {:x [:dialog :foo]}
::uism/actor-names #{:dialog}
::uism/states {:initial {::uism/handler (fn [env] env)}}})
(specification "compute-target"
(let [asm (uism/new-asm {::uism/state-machine-id `ctm ::uism/asm-id :fake
::uism/actor->ident {:dialog [:dialog 1]}})
test-env (uism/state-machine-env {::uism/asm-id {:fake asm}} nil :fake :do {})]
(behavior "accepts (and returns) any kind of raw fulcro target"
(assertions
"(normal target)"
(uism/compute-target test-env {::targeting/target [:a 1]}) => [:a 1]
"(special target)"
(uism/compute-target test-env {::targeting/target (targeting/append-to [:a 1])}) => [:a 1]
(targeting/special-target? (uism/compute-target test-env {::targeting/target (targeting/append-to [:a 1])})) => true))
(behavior "Resolves actors"
(assertions
(uism/compute-target test-env {::uism/target-actor :dialog}) => [:dialog 1]
"can combine plain targets with actor targets"
(uism/compute-target test-env {::targeting/target [:a 1] ::uism/target-actor :dialog}) => [[:a 1] [:dialog 1]]
(targeting/multiple-targets? (uism/compute-target test-env {::targeting/target [:a 1]
::uism/target-actor :dialog}))
=> true
"can combine actor targets with a multiple-target"
(uism/compute-target test-env {::targeting/target (targeting/multiple-targets [:a 1] [:b 2])
::uism/target-actor :dialog})
=> [[:a 1] [:b 2] [:dialog 1]]))
(behavior "Resolves aliases"
(assertions
(uism/compute-target test-env {::uism/target-alias :x}) => [:dialog 1 :foo]
"can combine plain targets with alias targets"
(uism/compute-target test-env {::targeting/target [:a 1] ::uism/target-alias :x}) => [[:a 1] [:dialog 1 :foo]]
(targeting/multiple-targets? (uism/compute-target test-env {::targeting/target [:a 1]
::uism/target-alias :x}))
=> true
"can combine alias targets with a multiple-target"
(uism/compute-target test-env {::targeting/target (targeting/multiple-targets [:a 1] [:b 2])
::uism/target-alias :x})
=> [[:a 1] [:b 2] [:dialog 1 :foo]]))))
| true |
(ns com.fulcrologic.fulcro.ui-state-machines-spec
(:require
[clojure.spec.alpha :as s]
[com.fulcrologic.guardrails.core :refer [>defn]]
[com.fulcrologic.fulcro.algorithms.data-targeting :as targeting]
[com.fulcrologic.fulcro.algorithms.tx-processing :as txn]
[com.fulcrologic.fulcro.application :as app]
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro.data-fetch :as df]
[com.fulcrologic.fulcro.mutations :as m]
[com.fulcrologic.fulcro.ui-state-machines :as uism]
[com.fulcrologic.fulcro.specs]
[edn-query-language.core :as eql]
[fulcro-spec.core :refer [specification provided provided! when-mocking when-mocking! behavior assertions component]]))
(declare => =1x=>)
(def mock-app (app/fulcro-app))
(defn mutation-env [state-atom tx extra-env]
(-> mock-app
(assoc ::app/state-atom state-atom)
(txn/build-env (txn/tx-node tx) extra-env)
(assoc :ast (eql/query->ast1 tx))))
(defsc AClass [_ _] {:query ['*] :ident (fn [] [:A 1])})
(defn A-handler [env] env)
(uism/defstatemachine test-machine
{::uism/actor-names #{:dialog}
::uism/aliases {:visible? [:dialog :ui/active?]
:title [:dialog :title]
:widgets [:dialog :linked-widgets]
:uberwidgets [:dialog :other-widgets]
:username [:dialog :name]}
::uism/plugins {:f? (fn [{:keys [visible? username]}]
(when visible? username))}
::uism/states {:initial {::uism/handler (fn [env]
(with-meta env {:handler-ran true}))}
:B {::uism/events {:bang! {::uism/handler (fn [env] (uism/store env :handler-ran? true))
::uism/target-state :A
::uism/event-predicate (fn [env] (uism/retrieve env :enabled? false))}}}
:C {::uism/events {:bang! {::uism/handler (fn [env] (uism/store env :handler-ran? true))
::uism/target-state :A}}}
:D {::uism/events {:bang! {::uism/handler (fn [env] (uism/activate env :A))
::uism/target-state :B}}}
:A {::uism/handler A-handler}}})
(def base-fulcro-state
{:TABLE {1 {:ui/active? false :name "PI:NAME:<NAME>END_PI"
:other-widgets []
:linked-widgets [[:widget/by-id 1]]}
2 {:ui/active? true :name "PI:NAME:<NAME>END_PI"
:other-widgets []
:linked-widgets [[:widget/by-id 2]]}}
:widget/by-id {1 {:id 1}
2 {:id 2}
3 {:id 3}}
::uism/asm-id {:fake (uism/new-asm
{::uism/state-machine-id `test-machine
::uism/asm-id :fake
::uism/actor->component-name {:dialog (uism/any->actor-component-registry-key AClass)}
::uism/actor->ident {:dialog [:TABLE 1]}})}})
(defn test-env [event-id event-data]
(uism/state-machine-env base-fulcro-state [:TABLE 1] :fake event-id event-data))
(specification "State Machine Registry"
(assertions
"Registers the FQ symbol of the state machine"
(map? (uism/get-state-machine `test-machine)) => true
"Stores the definition at that symbol"
(::uism/actor-names (uism/get-state-machine `test-machine)) => #{:dialog}
"Allows lookup of a value via an active env and a machine key"
(uism/lookup-state-machine-field (test-env :event nil) ::uism/actor-names) => #{:dialog}))
(specification "state-machine-env"
(assertions
"produces a spec-compliant result"
(s/valid? ::uism/env (uism/state-machine-env {} [:a 1] :x :evt {})) => true))
(let [env (test-env nil nil)]
(specification "asm-value"
(assertions "Finds things in the active state machine"
(uism/asm-value env ::uism/asm-id) => :fake))
(specification "activate"
(assertions
"Sets the given active state in the env"
(-> env
(uism/activate :A)
(uism/asm-value ::uism/active-state)) => :A)
(assertions
"Ignores a requst to move to an invalid state (logs an error)"
(-> env
(uism/activate :crap)
(uism/asm-value ::uism/active-state)) => :initial))
(specification "store/retrieve"
(assertions
"Allows for the local storage or asm-local values"
(-> env (uism/store :x true) (uism/retrieve :x)) => true
(-> env (uism/store :x 0) (uism/retrieve :x)) => 0
(-> env (uism/store :x {}) (uism/retrieve :x)) => {}
(-> env (uism/store :v 1) (uism/retrieve :v)) => 1))
(specification "resolve-alias"
(assertions
"Returns the Fulcro state path for a given data alias"
(uism/resolve-alias env :username) => [:TABLE 1 :name])
(assertions
"Returns nil if it is an invalid alias"
(uism/resolve-alias env :crap) => nil))
(specification "actor-path"
(assertions
"Returns the Fulcro ident of an actor"
(uism/actor-path env :dialog) => [:TABLE 1]
"Returns the Fulcro path to data in an actor if a field is included"
(uism/actor-path env :dialog :boo) => [:TABLE 1 :boo]))
(specification "actor-class"
(assertions
"Returns the Fulcro class of an actor"
(uism/actor-class env :dialog) => AClass))
(specification "set-actor-value"
(assertions
"Sets a raw (non-aliased) attribute in Fulcro state on an actor"
(-> env
(uism/set-actor-value :dialog :boo 42)
::uism/state-map
:TABLE
(get 1)
:boo) => 42
"Which can be read by actor-value"
(-> env
(uism/set-actor-value :dialog :boo 42)
(uism/actor-value :dialog :boo)) => 42))
(specification "alias-value"
(assertions
"Returns nil if the alias isn't valid"
(uism/alias-value env :name) => nil
"Gets the value of the fulro state that the alias refers to"
(uism/alias-value env :username) => "Joe"))
(specification "set-aliased-value"
(assertions
"Can set a single value"
(-> env
(uism/set-aliased-value :title "Hello")
(uism/alias-value :title)) => "Hello"
"Can set two values"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe")
(uism/alias-value :title)) => "Hello"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe")
(uism/alias-value :username)) => "Joe"
"Can set more than 2 values"
(-> env
(uism/set-aliased-value :title "Hello" :username "Joe" :visible? :booga)
(uism/alias-value :visible?)) => :booga)
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "PI:NAME:<NAME>END_PI") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/set-aliased-value :username "PI:NAME:<NAME>END_PI")
::uism/state-map
:TABLE
(get 1)
:name) => "PI:NAME:<NAME>END_PI"))
(specification "reset-actor-ident"
(let [env (uism/reset-actor-ident env :dialog [:TABLE 2])]
(assertions
"Can update actor/ident indexes"
(uism/asm-value env ::uism/actor->ident) => {:dialog [:TABLE 2]}
(uism/asm-value env ::uism/ident->actor) => {[:TABLE 2] :dialog}
"Class index is correct"
(uism/actor-class env :dialog) => AClass
(uism/asm-value env ::uism/actor->component-name) => {:dialog ::AClass}))
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "PI:NAME:<NAME>END_PI") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/assoc-aliased :username "PI:NAME:<NAME>END_PI")
::uism/state-map
:TABLE
(get 1)
:name) => "PI:NAME:<NAME>END_PI"))
(specification "assoc-aliased"
(assertions
"Can set a single value"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/alias-value :title)) => "Hello"
"Can set two values"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe")
(uism/alias-value :title)) => "Hello"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe")
(uism/alias-value :username)) => "Joe"
"Can set more than 2 values"
(-> env
(uism/assoc-aliased :title "Hello" :username "Joe" :visible? :booga)
(uism/alias-value :visible?)) => :booga)
(assertions
"Returns unmodified env if the alias isn't valid"
(uism/set-aliased-value env :name "PI:NAME:<NAME>END_PI") => env
"Sets the value in the fulro state that the alias refers to"
(-> env
(uism/assoc-aliased :username "PI:NAME:<NAME>END_PI")
::uism/state-map
:TABLE
(get 1)
:name) => "PI:NAME:<NAME>END_PI"))
(specification "update-aliased"
(assertions
"Can update a value"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/update-aliased :title #(str % "-suffix"))
(uism/alias-value :title)) => "Hello-suffix"
"Can update a value with arguments"
(-> env
(uism/assoc-aliased :title "Hello")
(uism/update-aliased :title #(str %1 %2 %3) 1 2)
(uism/alias-value :title)) => "Hello12"))
(specification "dissoc-aliased"
(let [env (uism/assoc-aliased env :title "Hello" :username "Joe")]
(let [entries (-> env
(uism/dissoc-aliased :title)
(get-in [::uism/state-map :TABLE 1])
(-> keys set))]
(assertions
"Can dissoc a single alias"
(contains? entries :title) => false))
(let [entries (-> env
(uism/dissoc-aliased :title :username)
(get-in [::uism/state-map :TABLE 1])
(-> keys set))]
(assertions
"Can dissoc multiple aliases"
(contains? entries :title) => false
(contains? entries :name) => false))))
(specification "integrate-ident"
(assertions
"Accepts a list of operations"
(let [nenv (uism/integrate-ident env [:widget/by-id 2] :prepend :widgets
:append :uberwidgets)]
(select-keys (get-in nenv [::uism/state-map :TABLE 1]) #{:other-widgets :linked-widgets}))
=> {:linked-widgets [[:widget/by-id 2] [:widget/by-id 1]]
:other-widgets [[:widget/by-id 2]]}
"Can prepend an ident"
(-> env
(uism/integrate-ident [:widget/by-id 2] :prepend :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 2] [:widget/by-id 1]]
"Can append an ident"
(-> env
(uism/integrate-ident [:widget/by-id 3] :append :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1] [:widget/by-id 3]]
"Integrating an already present ident has no effect"
(-> env
(uism/integrate-ident [:widget/by-id 1] :prepend :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]
(-> env
(uism/integrate-ident [:widget/by-id 1] :append :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]))
(specification "remove-ident"
(assertions
"Can remove an ident"
(-> env
(uism/remove-ident [:widget/by-id 1] :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => []
"Removing a non-present ident has no effect"
(-> env
(uism/remove-ident [:widget/by-id 2] :widgets)
(get-in [::uism/state-map :TABLE 1 :linked-widgets])
) => [[:widget/by-id 1]]))
(specification "aliased-data"
(assertions
"Builds a map of all of the current values of aliased data"
(-> env
(uism/aliased-data)) => {:visible? false
:title nil
:widgets [[:widget/by-id 1]]
:uberwidgets []
:username "Joe"}))
(specification "run"
(assertions
"Runs a plugin against the env"
(-> env
(uism/set-aliased-value :visible? true)
(uism/run :f?)) => "PI:NAME:<NAME>END_PI"
"Can be passed extra data that can overwrite aliased values"
(-> env
(uism/set-aliased-value :visible? true)
(uism/run :f? {:visible? false})) => nil))
(specification "active-state-handler"
(provided! "The state machine definition is missing or the active state has no handler"
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:boo)
(assertions
"returns core identity"
(uism/active-state-handler env) => identity))
(let [env (-> (test-env :bang! nil) (uism/activate :B) (uism/store :enabled? true))
handler (fn geh* [e] e)]
(provided! "The state machine definition has event definitions"
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:boo)
(uism/generic-event-handler e) => handler
(assertions
"returns a generic-event-handler"
(uism/active-state-handler env) => handler)))
(provided! "The state machine definition exists and there is an active state."
(uism/lookup-state-machine e) => (do
(assertions
e => env)
test-machine)
(uism/asm-value e k) => (do
(assertions
e => env
k => ::uism/active-state)
:A)
(assertions
"returns the correct handler"
(uism/active-state-handler env) => A-handler)))
(specification "generic-event-handler"
(let [disabled-env (-> (test-env :bang! nil) (uism/activate :B) (uism/store :enabled? false))
enabled-env (-> disabled-env (uism/store :enabled? true))
non-event-env (-> (test-env :boo nil) (uism/activate :A))
missing-handler (uism/generic-event-handler non-event-env)
disabled-handler (uism/generic-event-handler disabled-env)
enabled-handler (uism/generic-event-handler enabled-env)
no-predicate-env (-> enabled-env (uism/activate :C))
no-predicate-handler (uism/generic-event-handler no-predicate-env)
overriding-handler-env (-> disabled-env (uism/activate :D))
overriding-handler (uism/generic-event-handler overriding-handler-env)
actual-disabled-result (disabled-handler disabled-env)
actual-enabled-result (enabled-handler enabled-env)
no-predicate-result (no-predicate-handler no-predicate-env)
overriding-handler-result (overriding-handler overriding-handler-env)]
(behavior "when the event definition is missing"
(assertions
"Returns nil"
missing-handler => nil))
(behavior "When there is no predicate"
(assertions
"Runs the handler"
(-> no-predicate-result (uism/retrieve :handler-ran? false)) => true
"Follows the transition, if defined"
(-> no-predicate-result (uism/asm-value ::uism/active-state)) => :A))
(behavior "when the predicate is false"
(assertions
"Does not runs the handler"
(-> actual-disabled-result (uism/retrieve :handler-ran? false)) => false
"Stays in the same state"
(-> actual-disabled-result (uism/asm-value ::uism/active-state)) => :B))
(behavior "when the predicate is true"
(assertions
"Runs the handler"
(-> actual-enabled-result (uism/retrieve :handler-ran? false)) => true
"Follows the transition, if defined"
(-> actual-enabled-result (uism/asm-value ::uism/active-state)) => :A))
(behavior "when the handler activates a target state different from the *declared* target state"
(assertions
"The handler wins"
(-> overriding-handler-result (uism/asm-value ::uism/active-state)) => :A))))
(specification "apply-event-value"
(assertions
"returns an unmodified env for other events"
(uism/apply-event-value env {::uism/event-id :random-event}) => env
"applies a change to fulcro state based on the ::value-changed event"
(-> env
(uism/apply-event-value {::uism/event-id ::uism/value-changed
::uism/event-data {::uism/alias :visible?
:value :new-value}})
(uism/alias-value :visible?)) => :new-value))
(specification "queue-mutations!"
(let [mutation-1-descriptor {::uism/mutation-context :dialog
::uism/ok-event :pow!
::uism/mutation `a}
mutation-2-descriptor {::uism/mutation-context :dialog
::uism/ok-event :bam!
::uism/mutation `b}
menv1 (assoc env ::uism/queued-mutations [mutation-1-descriptor])
menv (assoc env ::uism/queued-mutations [mutation-1-descriptor
mutation-2-descriptor])]
(behavior "Walks the list of queued mutations in env"
(when-mocking!
(comp/transact! comp tx options)
=1x=> (assertions
"Calls transact with the (1st) mutation delegate and the mutation descriptor "
tx => `[(uism/mutation-delegate ~mutation-1-descriptor)])
(comp/transact! comp tx options)
=1x=> (assertions
"Calls transact with the (2nd) mutation delegate and the mutation descriptor "
tx => `[(uism/mutation-delegate ~mutation-2-descriptor)])
(uism/queue-mutations! mock-app menv)))))
(specification "convert-load-options"
(let [load-options (uism/convert-load-options env {::comp/component-class AClass ::uism/ok-event :blah})]
(assertions
"always sets a fallback function (that will send a default load-error event)"
(:fallback load-options) => `uism/handle-load-error
"removes any of the UISM-specific options from the map"
(contains? load-options ::comp/component-class) => false
(contains? load-options ::uism/ok-event) => false
"defaults load markers to an explicit false"
(false? (:marker load-options)) => true))
(let [load-options (uism/convert-load-options env {::uism/ok-event :blah})]
(assertions
"Sets the post event handler and post event if there is a post-event"
(-> load-options :post-mutation-params ::uism/event-id) => :blah
(:post-mutation load-options) => `uism/trigger-state-machine-event))
(let [load-options (uism/convert-load-options env {::uism/error-event :foo
::uism/error-data {:y 1}})]
(assertions
"Sets fallback event and params if present"
(-> load-options :post-mutation-params ::uism/error-event) => :foo
(-> load-options :post-mutation-params ::uism/error-data) => {:y 1})))
(specification "handle-load-error*"
(behavior "When there is an error event in the original load request (post mutation params)"
(when-mocking
(comp/transact! r tx) => (let [{:keys [params]} (-> tx eql/query->ast1)
{::uism/keys [event-id event-data asm-id]} params]
(assertions
"it triggers that event with the error data"
event-id => :foo
event-data => {:y 1}
asm-id => :fake))
(uism/handle-load-error* (app/fulcro-app {}) {:post-mutation-params {::uism/asm-id :fake
::uism/error-event :foo
::uism/error-data {:y 1}}})))
(behavior "When the error event is not present in the original load request (post mutation params)"
(when-mocking
(comp/transact! r tx) => (let [{:keys [params]} (-> tx eql/query->ast1)
{::uism/keys [event-id event-data asm-id]} params]
(assertions
"it triggers ::uism/load-error"
event-id => ::uism/load-error
asm-id => :fake))
(uism/handle-load-error* (app/fulcro-app {}) {:post-mutation-params {::uism/asm-id :fake}}))))
(specification "queue-actor-load!"
(let [app (app/fulcro-app {})
env (assoc env ::uism/queued-loads [])
load-called? (atom false)]
(when-mocking!
(uism/actor->ident e actor) =1x=> [:actor 1]
(df/load! r ident class params) =1x=> (do
(reset! load-called? true)
(assertions
"Sends a real load to fulcro containing: the proper actor ident"
ident => [:actor 1]
"the correct component class"
class => AClass
"The params with specified load options"
params => {:marker false})
true)
(uism/queue-actor-load! app env :dialog AClass {:marker false}))))
#?(:cljs
(let [fulcro-state (atom {})
mutation-env (mutation-env fulcro-state [] {:ref [:TABLE 1]})
event {::uism/event-id :boggle ::uism/asm-id :fake}]
(specification "trigger-state-machine-event!"
(let [handler (fn [env] (assoc env :handler-ran true))
final-env? (fn [env]
(assertions
"Receives the final env"
(:looked-up-env env) => true
(:applied-event-values env) => true
(:handler-ran env) => true))]
(when-mocking!
(uism/state-machine-env s r a e d) => (assoc env :looked-up-env true)
(uism/clear-timeouts-on-event! env event) => (do
(assertions
"Clears any auto-cleared timeouts"
true => true)
(assoc env :cleared-timeouts event))
(uism/active-state-handler e) => handler
(uism/apply-event-value env evt) => (assoc env :applied-event-values true)
;; not calling the mocks on these will cause fail. our assertion is just
;; for pos output
(uism/queue-mutations! r e) => (do (final-env? e)
(assertions
"Tries to queue mutations using the final env"
true => true)
nil)
(uism/queue-loads! r env) => (do (final-env? env)
(assertions
"Tries to queue loads using the final env"
true => true)
nil)
(uism/update-fulcro-state! env satom) => (do (final-env? env)
(assertions
"Tries to update fulcro state"
satom => fulcro-state)
nil)
(uism/ui-refresh-list env) => [[:x :y]]
(uism/trigger-queued-events! menv triggers list) =1x=> (do
(assertions
"processes events that handlers queued."
(count triggers) => 0)
list)
;; ACTION UNDER TEST
(let [actual (uism/trigger-state-machine-event! mutation-env event)]
(assertions
"returns the list of things to refresh in the UI"
actual => [[:x :y]])))))))
(specification "trigger-queued-events!"
(let [mutation-env (mutation-env (atom {}) [:fake] {:ref [:TABLE 1]})
event-1 {::uism/asm-id :a ::uism/event-id :event-1 ::uism/event-data {:a 1}}
event-2 {::uism/asm-id :b ::uism/event-id :event-2 ::uism/event-data {:a 2}}
triggers [event-1 event-2]]
(when-mocking!
(uism/trigger-state-machine-event! menv event) =1x=> (do
(assertions
"Triggers the queued event"
event => event-1
"with the mutation env"
(= menv mutation-env) => true)
[[:b 2]])
(uism/trigger-state-machine-event! menv event) =1x=> (do
(assertions
"Triggers the queued event"
event => event-2
"with the mutation env"
(= mutation-env menv) => true)
[[:c 3]])
(let [actual (uism/trigger-queued-events! mutation-env triggers [[:A 1]])]
(assertions
"Accumulates and returns the actors to refresh"
actual => [[:A 1] [:b 2] [:c 3]])))))
(specification "trigger-state-machine-event mutation"
(let [trigger {::uism/asm-id :a ::uism/event-id :x}
menv (mutation-env (atom {}) [(uism/trigger-state-machine-event trigger)] {})
{:keys [action]} (m/mutate menv)]
(when-mocking!
(uism/trigger-state-machine-event! mutation-env p) => (do
(assertions
"runs the state machine event"
(= mutation-env menv) => true
p => trigger)
[[:table 1]])
(app/schedule-render! app options) => (assertions
"Queues the actors for UI refresh"
(nil? app) => false)
(action menv))))
(specification "set-string!"
(provided! "The user supplies a string"
(uism/trigger! this smid event params) => (do
(assertions
"Triggers a value-changed event"
event => ::uism/value-changed
"on a named state machine"
smid => :fake
"whose parameters specify the new value"
(::uism/alias params) => :username
(:value params) => "hello")
nil)
(uism/set-string! {} :fake :username "hello"))
#?(:cljs
(provided! "The user supplies a js DOM onChange event"
(uism/trigger! this smid event params) => (do
(assertions
"Triggers a value-changed event"
event => ::uism/value-changed
"on a named state machine"
smid => :fake
"with the extracted string value"
(::uism/alias params) => :username
(:value params) => "hi")
nil)
(uism/set-string! {} :fake :username #js {:target #js {:value "hi"}}))))
(specification "derive-actor-components"
(let [actual (uism/derive-actor-components {:a [:x 1]
:b AClass
:d (uism/with-actor-class [:A 1] AClass)})]
(assertions
"allows a bare ident (no mapping)"
(:a actual) => nil
"accepts a singleton classes"
(:b actual) => ::AClass
;; Need enzyme configured consistently for this test
;"accepts a react instance"
;(:c actual) => ::AClass
"finds class on metadata"
(:d actual) => ::AClass)))
(specification "derive-actor-idents"
(let [actual (uism/derive-actor-idents {:a [:x 1]
:b AClass
:d (uism/with-actor-class [:A 1] AClass)})]
(assertions
"allows a bare ident"
(:a actual) => [:x 1]
"finds the ident on singleton classes"
(:b actual) => [:A 1]
"remembers the singleton class as metadata"
(:b actual) => [:A 1]
;; Need enzyme configured consistently for this test
;"remembers the class of a react instance"
;(:c actual) => [:A 1]
"records explicit idents that use with-actor-class"
(:d actual) => [:A 1])))
(specification "set-timeout"
(let [new-env (uism/set-timeout env :timer/my-timer :event/bam! {} 100)
descriptor (some-> new-env ::uism/queued-timeouts first)]
(assertions
"Adds a timeout descriptor to the queued timeouts"
(s/valid? ::uism/timeout-descriptor descriptor) => true
"whose default auto-cancel is constantly false"
(some-> descriptor ::uism/cancel-on meta :cancel-on (apply [:x])) => false)))
(let [prior-timer {::uism/timeout 100
::uism/timer-id :timer/id
::uism/js-timer (with-meta {} {:timer :mock-js-timer})
::uism/event-id :bam!
::uism/cancel-on (with-meta {} {:cancel-on (constantly true)})}
env-with-active-timer (assoc-in env (uism/asm-path env [::uism/active-timers :timer/id]) prior-timer)]
(specification "schedule-timeouts!"
(provided! "There isn't already a timer under that ID"
(uism/get-js-timer e t) =1x=> nil
(uism/set-js-timeout! f t) =1x=> (assertions
"sets the low-level timer with the correct time"
t => 100)
(let [prepped-env (uism/set-timeout env :timer/id :bam! {} 100)
new-env (uism/schedule-timeouts! (app/fulcro-app {}) prepped-env)]
(assertions
"Adds a timeout descriptor to active timers"
(s/valid? ::uism/timeout-descriptor
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])))
=> true)))
(provided! "There IS a timer under that ID"
(uism/get-js-timer e t) =1x=> :low-level-js-timer
(uism/clear-js-timeout! t) =1x=> (assertions
"Clears the old timer"
t => :low-level-js-timer)
(uism/set-js-timeout! f t) =1x=> (assertions
"sets the low-level timer with the correct time"
t => 300)
(let [prepped-env (uism/set-timeout env-with-active-timer :timer/id :bam! {} 300)
new-env (uism/schedule-timeouts! (app/fulcro-app {}) prepped-env)]
(assertions
"Adds a timeout descriptor to active timers"
(s/valid? ::uism/timeout-descriptor
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])))
=> true))))
(specification "clear-timeout!"
(provided! "The timer exists"
(uism/clear-js-timeout! t) => (assertions
"clears the timer"
t => :mock-js-timer)
(let [new-env (uism/clear-timeout! env-with-active-timer :timer/id)]
(assertions
"Removes the timer from the active timers table"
(get-in new-env (uism/asm-path new-env [::uism/active-timers :timer/id])) => nil))))
(specification "clear-timeouts-on-event!"
(provided! "clear-timeout! works correctly"
(uism/clear-timeout! e t) => (assoc e :cleared? true)
(let [new-env (uism/clear-timeouts-on-event! env-with-active-timer :bam!)]
(assertions
"Clears and removes the timer"
(:cleared? new-env) => true))))))
;; not usable from clj
(specification "begin!"
(let [fulcro-state (atom {})]
(component "(the begin mutation)"
(let [creation-args {::uism/state-machine-id `test-machine
::uism/asm-id :fake
::uism/actor->ident {:dialog [:table 1]}}
mutation-env (mutation-env fulcro-state [(uism/begin creation-args)] {:ref [:TABLE 1]})
{:keys [action]} (m/mutate mutation-env)
real-new-asm uism/new-asm]
(when-mocking!
(uism/new-asm p) =1x=> (do
(assertions
"creates a new asm with the provided params"
p => creation-args)
(real-new-asm p))
(uism/trigger-state-machine-event! e p) =1x=> (do
(assertions
"triggers the ::started event"
(::uism/event-id p) => ::uism/started
(::uism/asm-id p) => :fake)
[[:A 1]])
(app/schedule-render! app) => (assertions
"Updates the UI"
(nil? app) => false)
(action mutation-env)
(assertions
"and stores it in fulcro state"
(contains? (::uism/asm-id @fulcro-state) :fake) => true))))
#?(:cljs
(component "(the wrapper function begin!)"
(when-mocking
(comp/transact! t tx) => (assertions
"runs fulcro transact on the begin mutation"
(ffirst tx) => `uism/begin)
(uism/begin! mock-app test-machine :fake {:dialog [:table 1]}))))))
(uism/defstatemachine ctm {::uism/aliases {:x [:dialog :foo]}
::uism/actor-names #{:dialog}
::uism/states {:initial {::uism/handler (fn [env] env)}}})
(specification "compute-target"
(let [asm (uism/new-asm {::uism/state-machine-id `ctm ::uism/asm-id :fake
::uism/actor->ident {:dialog [:dialog 1]}})
test-env (uism/state-machine-env {::uism/asm-id {:fake asm}} nil :fake :do {})]
(behavior "accepts (and returns) any kind of raw fulcro target"
(assertions
"(normal target)"
(uism/compute-target test-env {::targeting/target [:a 1]}) => [:a 1]
"(special target)"
(uism/compute-target test-env {::targeting/target (targeting/append-to [:a 1])}) => [:a 1]
(targeting/special-target? (uism/compute-target test-env {::targeting/target (targeting/append-to [:a 1])})) => true))
(behavior "Resolves actors"
(assertions
(uism/compute-target test-env {::uism/target-actor :dialog}) => [:dialog 1]
"can combine plain targets with actor targets"
(uism/compute-target test-env {::targeting/target [:a 1] ::uism/target-actor :dialog}) => [[:a 1] [:dialog 1]]
(targeting/multiple-targets? (uism/compute-target test-env {::targeting/target [:a 1]
::uism/target-actor :dialog}))
=> true
"can combine actor targets with a multiple-target"
(uism/compute-target test-env {::targeting/target (targeting/multiple-targets [:a 1] [:b 2])
::uism/target-actor :dialog})
=> [[:a 1] [:b 2] [:dialog 1]]))
(behavior "Resolves aliases"
(assertions
(uism/compute-target test-env {::uism/target-alias :x}) => [:dialog 1 :foo]
"can combine plain targets with alias targets"
(uism/compute-target test-env {::targeting/target [:a 1] ::uism/target-alias :x}) => [[:a 1] [:dialog 1 :foo]]
(targeting/multiple-targets? (uism/compute-target test-env {::targeting/target [:a 1]
::uism/target-alias :x}))
=> true
"can combine alias targets with a multiple-target"
(uism/compute-target test-env {::targeting/target (targeting/multiple-targets [:a 1] [:b 2])
::uism/target-alias :x})
=> [[:a 1] [:b 2] [:dialog 1 :foo]]))))
|
[
{
"context": ")\n (:import (java.util LinkedList)))\n\n;--- Day 9: Marble Mania ---\n; The Elves play this game by taking turns ar",
"end": 158,
"score": 0.9985932111740112,
"start": 146,
"tag": "NAME",
"value": "Marble Mania"
}
] |
src/aoc2018/day09.clj
|
Sorceror/aoc2018
| 1 |
(ns aoc2018.day09
(require [aoc2018.utils :as u]
[clojure.data.finger-tree :as ft])
(:import (java.util LinkedList)))
;--- Day 9: Marble Mania ---
; The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number.
; First, the marble numbered 0 is placed in the circle. At this point, while it contains only a single marble, it is still a circle: the marble is both clockwise from itself and counter-clockwise from itself. This marble is designated the current marble.
; Then, each Elf takes a turn placing the lowest-numbered remaining marble into the circle between the marbles that are 1 and 2 marbles clockwise of the current marble. (When the circle is large enough, this means that there is one marble between the marble that was just placed and the current marble.) The marble that was just placed then becomes the current marble.
; However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble.
; What is the winning Elf's score? <- part 1
; What would the new winning Elf's score be if the number of the last marble were 100 times larger? <- part 2
(def input
(->>
(u/resource->strings "day09.txt")
(first)
(re-find #"(\d+).*worth.(\d+).*")
(rest)
(map u/s->i)))
; -------- PURE CLOJURE VEC APPROACH --------
(defn clockwise [current total circle]
(mod (+ current total) (count circle)))
(defn counter-clockwise [current total circle]
(mod (- current total) (count circle)))
(defn place-after [pos value circle]
(apply conj (vec (take (inc pos) circle)) value (vec (drop (inc pos) circle))))
(defn extract-on [pos circle]
[(first (drop pos circle))
(apply conj (vec (take pos circle)) (vec (drop (inc pos) circle)))])
(defn run-game [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle [0]
player-id 0
players (vec (repeat num-players 0))]
(if (zero? (mod current-marble 5000)) (println current-marble))
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise current-idx 7 circle)
[value new-circle] (extract-on new-idx circle)]
(recur new-idx (inc current-marble) new-circle (clockwise player-id 1 players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise current-idx 1 circle)
new-circle (place-after pos current-marble circle)]
(if (> current-marble last-marble-worth)
players
(recur (inc pos) (inc current-marble) new-circle (clockwise player-id 1 players) players))))))
(comment
(time (apply max (run-game 30 5807)))
;"Elapsed time: 1400.539339 msecs"
;=> 37305
(time (apply max (run-game (first input) (second input)))))
; "Elapsed time: 211587.404153 msecs" ~ 3.5 min
; => 394486)
; -------- CONSTANT ARRAY SIZE APPROACH --------
(defn clockwise-array [current total size]
(mod (+ current total) size))
(defn counter-clockwise-array [current total size]
(mod (- current total) size))
(defn place-after-array [pos value circle size]
(->
(reduce (fn [new-circle idx] (assoc new-circle idx (get new-circle (dec idx)))) circle (range size pos -1))
(assoc (inc pos) value)))
(defn extract-on-array [pos circle size]
[(nth circle pos)
(assoc (reduce (fn [new-circle idx] (assoc new-circle idx (get new-circle (inc idx)))) circle (range pos size)) (dec size) -1)])
(defn run-game-array [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle (assoc (vec (repeat last-marble-worth -1)) 0 0)
size 1
player-id 0
players (vec (repeat num-players 0))]
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-array current-idx 7 size)
[value new-circle] (extract-on-array new-idx circle size)]
(recur
new-idx (inc current-marble)
new-circle (dec size)
(clockwise-array player-id 1 num-players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-array current-idx 1 size)
new-circle (place-after-array pos current-marble circle size)]
(if (> current-marble last-marble-worth)
players
(recur
(inc pos) (inc current-marble)
new-circle (inc size)
(clockwise-array player-id 1 num-players) players))))))
(comment
(time (apply max (run-game-array 30 5807)))
; "Elapsed time: 1189.956176 msecs"
; => 37305
; takes forever to compute
(time (apply max (run-game-array (first input) (second input)))))
; "Elapsed time: 171458.652593 msecs" ~ 3 min
; => 394486
; -------- JAVA LINKED LIST APPROACH --------
(defn clockwise-list [^long current ^long total ^LinkedList circle-list]
(mod (+ current total) (.size circle-list)))
(defn counter-clockwise-list [^long current ^long total ^LinkedList circle-list]
(mod (- current total) (.size circle-list)))
(defn place-after-list [^long pos ^long value ^LinkedList circle-list]
(.add circle-list (inc pos) value))
(defn extract-on-list [^long pos ^LinkedList circle-list]
(.remove circle-list pos))
(defn run-game-list
([num-players last-marble-worth] (let [list (LinkedList.) _ (.add list 0)] (run-game-list num-players last-marble-worth list)))
([num-players last-marble-worth circle-list]
(loop [current-idx 0
current-marble 1
circle ^LinkedList circle-list
player-id 0
players (vec (repeat num-players 0))]
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-list current-idx 7 circle)
value (extract-on-list new-idx circle)]
(recur new-idx (inc current-marble) circle (mod (inc player-id) num-players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-list current-idx 1 circle)
_ (place-after-list pos current-marble circle)]
(if (> current-marble last-marble-worth)
players
(recur (inc pos) (inc current-marble) circle (mod (inc player-id) num-players) players)))))))
(comment
(time (apply max (run-game-list 30 5807)))
; "Elapsed time: 17.24249 msecs"
; => 37305
(time (apply max (run-game-list (first input) (second input))))
; "Elapsed time: 6042.217532 msecs" ~ 6 sec
; => 394486
(time (apply max (run-game-list (first input) (* (second input) 100)))))
; Wasn't done after 40 minutes :(
; -------- FINGER TREES - COUNTED-DOUBLE-LIST APPROACH --------
(defn clockwise-tree [current total circle]
(mod (+ current total) (count circle)))
(defn counter-clockwise-tree [current total circle]
(mod (- current total) (count circle)))
(defn place-after-tree [pos value circle]
(let [[l v r] (ft/ft-split-at circle pos)]
(ft/ft-concat (conj l v value) r)))
(defn run-game-tree [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle (ft/counted-double-list 0)
player-id 0
players (vec (repeat num-players 0))]
(if (< current-marble last-marble-worth)
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-tree current-idx 7 circle)
[left value right] (ft/ft-split-at circle new-idx)]
(recur
new-idx
(inc current-marble)
(ft/ft-concat left right)
(clockwise-tree player-id 1 players)
(assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-tree current-idx 1 circle)]
(recur
(inc pos)
(inc current-marble)
(place-after-tree pos current-marble circle)
(clockwise-tree player-id 1 players)
players)))
players)))
(comment
(time (apply max (run-game-tree 30 5807)))
; "Elapsed time: 182.845056 msecs"
; => 37305
(time (apply max (run-game-tree (first input) (second input))))
; "Elapsed time: 2385.809445 msecs" ~ 3 sec
; => 394486
(time (apply max (run-game-tree (first input) (* (second input) 100)))))
; "Elapsed time: 393548.41902 msecs" ~ 6.5 min
; => 3276488008
|
51299
|
(ns aoc2018.day09
(require [aoc2018.utils :as u]
[clojure.data.finger-tree :as ft])
(:import (java.util LinkedList)))
;--- Day 9: <NAME> ---
; The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number.
; First, the marble numbered 0 is placed in the circle. At this point, while it contains only a single marble, it is still a circle: the marble is both clockwise from itself and counter-clockwise from itself. This marble is designated the current marble.
; Then, each Elf takes a turn placing the lowest-numbered remaining marble into the circle between the marbles that are 1 and 2 marbles clockwise of the current marble. (When the circle is large enough, this means that there is one marble between the marble that was just placed and the current marble.) The marble that was just placed then becomes the current marble.
; However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble.
; What is the winning Elf's score? <- part 1
; What would the new winning Elf's score be if the number of the last marble were 100 times larger? <- part 2
(def input
(->>
(u/resource->strings "day09.txt")
(first)
(re-find #"(\d+).*worth.(\d+).*")
(rest)
(map u/s->i)))
; -------- PURE CLOJURE VEC APPROACH --------
(defn clockwise [current total circle]
(mod (+ current total) (count circle)))
(defn counter-clockwise [current total circle]
(mod (- current total) (count circle)))
(defn place-after [pos value circle]
(apply conj (vec (take (inc pos) circle)) value (vec (drop (inc pos) circle))))
(defn extract-on [pos circle]
[(first (drop pos circle))
(apply conj (vec (take pos circle)) (vec (drop (inc pos) circle)))])
(defn run-game [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle [0]
player-id 0
players (vec (repeat num-players 0))]
(if (zero? (mod current-marble 5000)) (println current-marble))
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise current-idx 7 circle)
[value new-circle] (extract-on new-idx circle)]
(recur new-idx (inc current-marble) new-circle (clockwise player-id 1 players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise current-idx 1 circle)
new-circle (place-after pos current-marble circle)]
(if (> current-marble last-marble-worth)
players
(recur (inc pos) (inc current-marble) new-circle (clockwise player-id 1 players) players))))))
(comment
(time (apply max (run-game 30 5807)))
;"Elapsed time: 1400.539339 msecs"
;=> 37305
(time (apply max (run-game (first input) (second input)))))
; "Elapsed time: 211587.404153 msecs" ~ 3.5 min
; => 394486)
; -------- CONSTANT ARRAY SIZE APPROACH --------
(defn clockwise-array [current total size]
(mod (+ current total) size))
(defn counter-clockwise-array [current total size]
(mod (- current total) size))
(defn place-after-array [pos value circle size]
(->
(reduce (fn [new-circle idx] (assoc new-circle idx (get new-circle (dec idx)))) circle (range size pos -1))
(assoc (inc pos) value)))
(defn extract-on-array [pos circle size]
[(nth circle pos)
(assoc (reduce (fn [new-circle idx] (assoc new-circle idx (get new-circle (inc idx)))) circle (range pos size)) (dec size) -1)])
(defn run-game-array [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle (assoc (vec (repeat last-marble-worth -1)) 0 0)
size 1
player-id 0
players (vec (repeat num-players 0))]
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-array current-idx 7 size)
[value new-circle] (extract-on-array new-idx circle size)]
(recur
new-idx (inc current-marble)
new-circle (dec size)
(clockwise-array player-id 1 num-players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-array current-idx 1 size)
new-circle (place-after-array pos current-marble circle size)]
(if (> current-marble last-marble-worth)
players
(recur
(inc pos) (inc current-marble)
new-circle (inc size)
(clockwise-array player-id 1 num-players) players))))))
(comment
(time (apply max (run-game-array 30 5807)))
; "Elapsed time: 1189.956176 msecs"
; => 37305
; takes forever to compute
(time (apply max (run-game-array (first input) (second input)))))
; "Elapsed time: 171458.652593 msecs" ~ 3 min
; => 394486
; -------- JAVA LINKED LIST APPROACH --------
(defn clockwise-list [^long current ^long total ^LinkedList circle-list]
(mod (+ current total) (.size circle-list)))
(defn counter-clockwise-list [^long current ^long total ^LinkedList circle-list]
(mod (- current total) (.size circle-list)))
(defn place-after-list [^long pos ^long value ^LinkedList circle-list]
(.add circle-list (inc pos) value))
(defn extract-on-list [^long pos ^LinkedList circle-list]
(.remove circle-list pos))
(defn run-game-list
([num-players last-marble-worth] (let [list (LinkedList.) _ (.add list 0)] (run-game-list num-players last-marble-worth list)))
([num-players last-marble-worth circle-list]
(loop [current-idx 0
current-marble 1
circle ^LinkedList circle-list
player-id 0
players (vec (repeat num-players 0))]
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-list current-idx 7 circle)
value (extract-on-list new-idx circle)]
(recur new-idx (inc current-marble) circle (mod (inc player-id) num-players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-list current-idx 1 circle)
_ (place-after-list pos current-marble circle)]
(if (> current-marble last-marble-worth)
players
(recur (inc pos) (inc current-marble) circle (mod (inc player-id) num-players) players)))))))
(comment
(time (apply max (run-game-list 30 5807)))
; "Elapsed time: 17.24249 msecs"
; => 37305
(time (apply max (run-game-list (first input) (second input))))
; "Elapsed time: 6042.217532 msecs" ~ 6 sec
; => 394486
(time (apply max (run-game-list (first input) (* (second input) 100)))))
; Wasn't done after 40 minutes :(
; -------- FINGER TREES - COUNTED-DOUBLE-LIST APPROACH --------
(defn clockwise-tree [current total circle]
(mod (+ current total) (count circle)))
(defn counter-clockwise-tree [current total circle]
(mod (- current total) (count circle)))
(defn place-after-tree [pos value circle]
(let [[l v r] (ft/ft-split-at circle pos)]
(ft/ft-concat (conj l v value) r)))
(defn run-game-tree [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle (ft/counted-double-list 0)
player-id 0
players (vec (repeat num-players 0))]
(if (< current-marble last-marble-worth)
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-tree current-idx 7 circle)
[left value right] (ft/ft-split-at circle new-idx)]
(recur
new-idx
(inc current-marble)
(ft/ft-concat left right)
(clockwise-tree player-id 1 players)
(assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-tree current-idx 1 circle)]
(recur
(inc pos)
(inc current-marble)
(place-after-tree pos current-marble circle)
(clockwise-tree player-id 1 players)
players)))
players)))
(comment
(time (apply max (run-game-tree 30 5807)))
; "Elapsed time: 182.845056 msecs"
; => 37305
(time (apply max (run-game-tree (first input) (second input))))
; "Elapsed time: 2385.809445 msecs" ~ 3 sec
; => 394486
(time (apply max (run-game-tree (first input) (* (second input) 100)))))
; "Elapsed time: 393548.41902 msecs" ~ 6.5 min
; => 3276488008
| true |
(ns aoc2018.day09
(require [aoc2018.utils :as u]
[clojure.data.finger-tree :as ft])
(:import (java.util LinkedList)))
;--- Day 9: PI:NAME:<NAME>END_PI ---
; The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 and increasing by 1 until every marble has a number.
; First, the marble numbered 0 is placed in the circle. At this point, while it contains only a single marble, it is still a circle: the marble is both clockwise from itself and counter-clockwise from itself. This marble is designated the current marble.
; Then, each Elf takes a turn placing the lowest-numbered remaining marble into the circle between the marbles that are 1 and 2 marbles clockwise of the current marble. (When the circle is large enough, this means that there is one marble between the marble that was just placed and the current marble.) The marble that was just placed then becomes the current marble.
; However, if the marble that is about to be placed has a number which is a multiple of 23, something entirely different happens. First, the current player keeps the marble they would have placed, adding it to their score. In addition, the marble 7 marbles counter-clockwise from the current marble is removed from the circle and also added to the current player's score. The marble located immediately clockwise of the marble that was removed becomes the new current marble.
; What is the winning Elf's score? <- part 1
; What would the new winning Elf's score be if the number of the last marble were 100 times larger? <- part 2
(def input
(->>
(u/resource->strings "day09.txt")
(first)
(re-find #"(\d+).*worth.(\d+).*")
(rest)
(map u/s->i)))
; -------- PURE CLOJURE VEC APPROACH --------
(defn clockwise [current total circle]
(mod (+ current total) (count circle)))
(defn counter-clockwise [current total circle]
(mod (- current total) (count circle)))
(defn place-after [pos value circle]
(apply conj (vec (take (inc pos) circle)) value (vec (drop (inc pos) circle))))
(defn extract-on [pos circle]
[(first (drop pos circle))
(apply conj (vec (take pos circle)) (vec (drop (inc pos) circle)))])
(defn run-game [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle [0]
player-id 0
players (vec (repeat num-players 0))]
(if (zero? (mod current-marble 5000)) (println current-marble))
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise current-idx 7 circle)
[value new-circle] (extract-on new-idx circle)]
(recur new-idx (inc current-marble) new-circle (clockwise player-id 1 players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise current-idx 1 circle)
new-circle (place-after pos current-marble circle)]
(if (> current-marble last-marble-worth)
players
(recur (inc pos) (inc current-marble) new-circle (clockwise player-id 1 players) players))))))
(comment
(time (apply max (run-game 30 5807)))
;"Elapsed time: 1400.539339 msecs"
;=> 37305
(time (apply max (run-game (first input) (second input)))))
; "Elapsed time: 211587.404153 msecs" ~ 3.5 min
; => 394486)
; -------- CONSTANT ARRAY SIZE APPROACH --------
(defn clockwise-array [current total size]
(mod (+ current total) size))
(defn counter-clockwise-array [current total size]
(mod (- current total) size))
(defn place-after-array [pos value circle size]
(->
(reduce (fn [new-circle idx] (assoc new-circle idx (get new-circle (dec idx)))) circle (range size pos -1))
(assoc (inc pos) value)))
(defn extract-on-array [pos circle size]
[(nth circle pos)
(assoc (reduce (fn [new-circle idx] (assoc new-circle idx (get new-circle (inc idx)))) circle (range pos size)) (dec size) -1)])
(defn run-game-array [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle (assoc (vec (repeat last-marble-worth -1)) 0 0)
size 1
player-id 0
players (vec (repeat num-players 0))]
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-array current-idx 7 size)
[value new-circle] (extract-on-array new-idx circle size)]
(recur
new-idx (inc current-marble)
new-circle (dec size)
(clockwise-array player-id 1 num-players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-array current-idx 1 size)
new-circle (place-after-array pos current-marble circle size)]
(if (> current-marble last-marble-worth)
players
(recur
(inc pos) (inc current-marble)
new-circle (inc size)
(clockwise-array player-id 1 num-players) players))))))
(comment
(time (apply max (run-game-array 30 5807)))
; "Elapsed time: 1189.956176 msecs"
; => 37305
; takes forever to compute
(time (apply max (run-game-array (first input) (second input)))))
; "Elapsed time: 171458.652593 msecs" ~ 3 min
; => 394486
; -------- JAVA LINKED LIST APPROACH --------
(defn clockwise-list [^long current ^long total ^LinkedList circle-list]
(mod (+ current total) (.size circle-list)))
(defn counter-clockwise-list [^long current ^long total ^LinkedList circle-list]
(mod (- current total) (.size circle-list)))
(defn place-after-list [^long pos ^long value ^LinkedList circle-list]
(.add circle-list (inc pos) value))
(defn extract-on-list [^long pos ^LinkedList circle-list]
(.remove circle-list pos))
(defn run-game-list
([num-players last-marble-worth] (let [list (LinkedList.) _ (.add list 0)] (run-game-list num-players last-marble-worth list)))
([num-players last-marble-worth circle-list]
(loop [current-idx 0
current-marble 1
circle ^LinkedList circle-list
player-id 0
players (vec (repeat num-players 0))]
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-list current-idx 7 circle)
value (extract-on-list new-idx circle)]
(recur new-idx (inc current-marble) circle (mod (inc player-id) num-players) (assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-list current-idx 1 circle)
_ (place-after-list pos current-marble circle)]
(if (> current-marble last-marble-worth)
players
(recur (inc pos) (inc current-marble) circle (mod (inc player-id) num-players) players)))))))
(comment
(time (apply max (run-game-list 30 5807)))
; "Elapsed time: 17.24249 msecs"
; => 37305
(time (apply max (run-game-list (first input) (second input))))
; "Elapsed time: 6042.217532 msecs" ~ 6 sec
; => 394486
(time (apply max (run-game-list (first input) (* (second input) 100)))))
; Wasn't done after 40 minutes :(
; -------- FINGER TREES - COUNTED-DOUBLE-LIST APPROACH --------
(defn clockwise-tree [current total circle]
(mod (+ current total) (count circle)))
(defn counter-clockwise-tree [current total circle]
(mod (- current total) (count circle)))
(defn place-after-tree [pos value circle]
(let [[l v r] (ft/ft-split-at circle pos)]
(ft/ft-concat (conj l v value) r)))
(defn run-game-tree [num-players last-marble-worth]
(loop [current-idx 0
current-marble 1
circle (ft/counted-double-list 0)
player-id 0
players (vec (repeat num-players 0))]
(if (< current-marble last-marble-worth)
(if (= (mod current-marble 23) 0)
(let [new-idx (counter-clockwise-tree current-idx 7 circle)
[left value right] (ft/ft-split-at circle new-idx)]
(recur
new-idx
(inc current-marble)
(ft/ft-concat left right)
(clockwise-tree player-id 1 players)
(assoc players player-id (+ (get players player-id) value current-marble))))
(let [pos (clockwise-tree current-idx 1 circle)]
(recur
(inc pos)
(inc current-marble)
(place-after-tree pos current-marble circle)
(clockwise-tree player-id 1 players)
players)))
players)))
(comment
(time (apply max (run-game-tree 30 5807)))
; "Elapsed time: 182.845056 msecs"
; => 37305
(time (apply max (run-game-tree (first input) (second input))))
; "Elapsed time: 2385.809445 msecs" ~ 3 sec
; => 394486
(time (apply max (run-game-tree (first input) (* (second input) 100)))))
; "Elapsed time: 393548.41902 msecs" ~ 6.5 min
; => 3276488008
|
[
{
"context": ":author [{\"@type\" \"Person\"\n :name \"Dawn Marie Hayes\"\n :honorificSuffix \"Ph.D.\"\n ",
"end": 2052,
"score": 0.9999009370803833,
"start": 2036,
"tag": "NAME",
"value": "Dawn Marie Hayes"
},
{
"context": "ificSuffix \"Ph.D.\"\n :email \"mailto:[email protected]\"\n :jobTitle \"Associate Professor o",
"end": 2150,
"score": 0.999929666519165,
"start": 2126,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " \"https://montclair.academia.edu/DawnMarieHayes\",\n \"https://www.linkedin.",
"end": 2427,
"score": 0.9925106167793274,
"start": 2413,
"tag": "USERNAME",
"value": "DawnMarieHayes"
},
{
"context": " \"https://www.linkedin.com/in/dawn-marie-hayes-49b05414/\",\n \"http://viaf.org/viaf",
"end": 2509,
"score": 0.9991162419319153,
"start": 2484,
"tag": "USERNAME",
"value": "dawn-marie-hayes-49b05414"
},
{
"context": "tclair.edu/profilepages/view_profile.php?username=hayesd\"]}\n {\"@type\" \"Person\"\n ",
"end": 2745,
"score": 0.9991598129272461,
"start": 2739,
"tag": "USERNAME",
"value": "hayesd"
},
{
"context": " {\"@type\" \"Person\"\n :name \"Joseph Hayes\"\n :email \"mailto:[email protected]",
"end": 2817,
"score": 0.9998939037322998,
"start": 2805,
"tag": "NAME",
"value": "Joseph Hayes"
},
{
"context": "ame \"Joseph Hayes\"\n :email \"mailto:[email protected]\"\n :url \"https://www.linkedin.com/i",
"end": 2869,
"score": 0.999933660030365,
"start": 2850,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :url \"https://www.linkedin.com/in/joephayes/\"\n :sameAs [\"https://github.com/jo",
"end": 2930,
"score": 0.998282253742218,
"start": 2921,
"tag": "USERNAME",
"value": "joephayes"
},
{
"context": "es/\"\n :sameAs [\"https://github.com/joephayes\"]}]\n :sameAs [\"https://www.facebook.com/TheN",
"end": 2987,
"score": 0.9984153509140015,
"start": 2978,
"tag": "USERNAME",
"value": "joephayes"
},
{
"context": "ayes\"]}]\n :sameAs [\"https://www.facebook.com/TheNormanSicilyProject/\"\n \"https://twitter.com/Norman_Sici",
"end": 3055,
"score": 0.877620279788971,
"start": 3033,
"tag": "USERNAME",
"value": "TheNormanSicilyProject"
},
{
"context": "cilyProject/\"\n \"https://twitter.com/Norman_Sicily\"\n \"https://www.instagram.com/thenor",
"end": 3107,
"score": 0.9762290120124817,
"start": 3094,
"tag": "USERNAME",
"value": "Norman_Sicily"
},
{
"context": "Sicily\"\n \"https://www.instagram.com/thenormansicilyproject/\"\n \"https://github.com/the-norman-s",
"end": 3173,
"score": 0.9545457363128662,
"start": 3151,
"tag": "USERNAME",
"value": "thenormansicilyproject"
},
{
"context": "icilyproject/\"\n \"https://github.com/the-norman-sicily-project\"\n \"http://www.worldcat.org/oclc/100",
"end": 3236,
"score": 0.8864625096321106,
"start": 3211,
"tag": "USERNAME",
"value": "the-norman-sicily-project"
},
{
"context": " :url \"http://www.normansicily.org/\"\n :name \"The Norman Sicily Project\"\n :logo \"http://www.normansicily.org/images/",
"end": 3604,
"score": 0.8431364893913269,
"start": 3579,
"tag": "NAME",
"value": "The Norman Sicily Project"
},
{
"context": "ock\"}\n [:a {:href \"https://www.facebook.com/TheNormanSicilyProject/\" :class \"side-padded\" :target \"_blank\"} [:i {:cl",
"end": 3931,
"score": 0.9990301728248596,
"start": 3909,
"tag": "USERNAME",
"value": "TheNormanSicilyProject"
},
{
"context": "cebook\"}]]\n [:a {:href \"https://twitter.com/Norman_Sicily\" :class \"side-padded\" :target \"_blank\"} [:i {:cla",
"end": 4101,
"score": 0.9994282126426697,
"start": 4088,
"tag": "USERNAME",
"value": "Norman_Sicily"
},
{
"context": "\"}]]\n [:a {:href \"https://www.instagram.com/thenormansicilyproject/?hl=en\" :class \"side-padded\" :target \"_blank\"} [:",
"end": 4283,
"score": 0.9991388320922852,
"start": 4261,
"tag": "USERNAME",
"value": "thenormansicilyproject"
},
{
"context": "stagram\"}]]\n [:a {:href \"https://github.com/the-norman-sicily-project\" :class \"side-padded\" :target \"_blank\"} [:i {:cla",
"end": 4472,
"score": 0.9992408752441406,
"start": 4447,
"tag": "USERNAME",
"value": "the-norman-sicily-project"
},
{
"context": "-links\"}\n [:p\n \"© 2015 - 2019 by Dawn Marie Hayes and Joseph Hayes. All Rights Reserved.\"\n\n ",
"end": 4739,
"score": 0.9998940229415894,
"start": 4723,
"tag": "NAME",
"value": "Dawn Marie Hayes"
},
{
"context": " \"© 2015 - 2019 by Dawn Marie Hayes and Joseph Hayes. All Rights Reserved.\"\n\n [:div {:id \"licen",
"end": 4756,
"score": 0.9998801946640015,
"start": 4744,
"tag": "NAME",
"value": "Joseph Hayes"
},
{
"context": "y \"cc:attributionName\" :rel \"cc:attributionURL\"} \"Dawn Marie Hayes, Ph.D. and Joseph Hayes \"] \"is licensed under a\" ",
"end": 5329,
"score": 0.9998524785041809,
"start": 5313,
"tag": "NAME",
"value": "Dawn Marie Hayes"
},
{
"context": " \"cc:attributionURL\"} \"Dawn Marie Hayes, Ph.D. and Joseph Hayes \"] \"is licensed under a\" [:a {:rel \"license\" :hre",
"end": 5353,
"score": 0.9998770952224731,
"start": 5341,
"tag": "NAME",
"value": "Joseph Hayes"
}
] |
src/norman_sicily_static/partials.clj
|
joephayes/norman_sicily_static
| 0 |
(ns norman-sicily-static.partials
(:require [cheshire.core :as json]))
(defn render-navbar
[]
[:nav {:class "navbar navbar-default navbar-static-top"}
[:div {:class "container"}
[:div {:id "navbar-button-bar" :class "navbar-header"}
[:a {:href "/about/" :class "btn btn-default navbar-btn image-button about-button navbar-right"} [:div {:class "overlay-text" :data-hover "About"}]]
[:a {:href "/resources/" :class "btn btn-default navbar-btn image-button resources-button navbar-right"} [:div {:class "overlay-text" :data-hover "Resources"}]]
[:a {:href "/analytics/" :class "btn btn-default navbar-btn image-button analytics-button navbar-right"} [:div {:class "overlay-text" :data-hover "Analytics"}]]
[:a {:href "/essays/" :class "btn btn-default navbar-btn image-button essays-button navbar-right"} [:div {:class "overlay-text" :data-hover "Essays"}]]
[:a {:href "/chattels/" :class "btn btn-default navbar-btn image-button chattels-button navbar-right"} [:div {:class "overlay-text" :data-hover "Chattels"}]]
[:a {:href "/places/" :class "btn btn-default navbar-btn image-button places-button navbar-right"} [:div {:class "overlay-text" :data-hover "Places"}]]
[:a {:href "/people/" :class "btn btn-default navbar-btn image-button people-button navbar-right"} [:div {:class "overlay-text" :data-hover"People"}]]
[:a {:href "/" :class"btn btn-default navbar-btn image-button home-button navbar-right"} [:div { :class "overlay-text" :data-hover "Home"}]]
[:a {:href "/" :class "navbar-left"} [:img {:class "logo" :src "/images/title_bar.png"}]]]]])
(defn render-site-data
[]
[:script {:type "application/ld+json"}
(json/generate-string
{"@context" "http://schema.org"
"@type" "WebSite"
:url "http://www.normansicily.org/"
:name "The Norman Sicily Project"
:description
"The Norman Sicily Project is an effort to document the cultural heritage of Sicily from c. 1061 - 1194."
:author [{"@type" "Person"
:name "Dawn Marie Hayes"
:honorificSuffix "Ph.D."
:email "mailto:[email protected]"
:jobTitle "Associate Professor of Medieval History"
:url "http://www.thehayesweb.org/dhayes/"
:sameAs ["https://worldcat.org/identities/lccn-n2002112933/",
"https://montclair.academia.edu/DawnMarieHayes",
"https://www.linkedin.com/in/dawn-marie-hayes-49b05414/",
"http://viaf.org/viaf/76568635",
"https://www.researchgate.net/profile/Dawn_Hayes3",
"https://www.montclair.edu/profilepages/view_profile.php?username=hayesd"]}
{"@type" "Person"
:name "Joseph Hayes"
:email "mailto:[email protected]"
:url "https://www.linkedin.com/in/joephayes/"
:sameAs ["https://github.com/joephayes"]}]
:sameAs ["https://www.facebook.com/TheNormanSicilyProject/"
"https://twitter.com/Norman_Sicily"
"https://www.instagram.com/thenormansicilyproject/"
"https://github.com/the-norman-sicily-project"
"http://www.worldcat.org/oclc/1003325014"]
:license "http://creativecommons.org/licenses/by-sa/4.0/"})])
(defn render-org-data
[]
[:script {:type "application/ld+json"}
(json/generate-string
{"@context" "http://schema.org"
"@type" "Organization"
:url "http://www.normansicily.org/"
:name "The Norman Sicily Project"
:logo "http://www.normansicily.org/images/favicon-128.png"})])
(defn render-footer
[]
[:div {:class "footer"}
[:div {:class "container"}
[:div {:class "row bottom-padding"}
[:div {:class "col-12-xs"}
[:div {:class "center-block"}
[:a {:href "https://www.facebook.com/TheNormanSicilyProject/" :class "side-padded" :target "_blank"} [:i {:class "fa fa-facebook fa-1x rounded-corner-icon" :title "Facebook"}]]
[:a {:href "https://twitter.com/Norman_Sicily" :class "side-padded" :target "_blank"} [:i {:class "fa fa-twitter fa-1x rounded-corner-icon" :title "Twitter"}]]
[:a {:href "https://www.instagram.com/thenormansicilyproject/?hl=en" :class "side-padded" :target "_blank"} [:i {:class "fa fa-instagram fa-1x rounded-corner-icon" :title "Instagram"}]]
[:a {:href "https://github.com/the-norman-sicily-project" :class "side-padded" :target "_blank"} [:i {:class "fa fa-github fa-1x rounded-corner-icon" :title "GitHub"}]]]]]
[:div {:class "row"}
[:div {:class="col-12-xs"}
[:div {:class "footer-links"}
[:p
"© 2015 - 2019 by Dawn Marie Hayes and Joseph Hayes. All Rights Reserved."
[:div {:id "license"}
[:a {:rel "license" :href "http://creativecommons.org/licenses/by-sa/4.0/"} [:img {:alt "Creative Commons License" :style "border-width:0;padding-bottom:10px" :src "https://i.creativecommons.org/l/by-sa/4.0/88x31.png"}]] [:br ] "This " [:span {:xmlns:dct "http://purl.org/dc/terms/" :href "http://purl.org/dc/dcmitype/StillImage" :rel "dct:type"} "work"] " by " [:a {:xmlns:cc "http://creativecommons.org/ns#" :href "normansicily.org" :property "cc:attributionName" :rel "cc:attributionURL"} "Dawn Marie Hayes, Ph.D. and Joseph Hayes "] "is licensed under a" [:a {:rel "license" :href "http://creativecommons.org/licenses/by-sa/4.0/"} " Creative Commons Attribution-ShareAlike 4.0 International License"]]]]]]]])
|
120254
|
(ns norman-sicily-static.partials
(:require [cheshire.core :as json]))
(defn render-navbar
[]
[:nav {:class "navbar navbar-default navbar-static-top"}
[:div {:class "container"}
[:div {:id "navbar-button-bar" :class "navbar-header"}
[:a {:href "/about/" :class "btn btn-default navbar-btn image-button about-button navbar-right"} [:div {:class "overlay-text" :data-hover "About"}]]
[:a {:href "/resources/" :class "btn btn-default navbar-btn image-button resources-button navbar-right"} [:div {:class "overlay-text" :data-hover "Resources"}]]
[:a {:href "/analytics/" :class "btn btn-default navbar-btn image-button analytics-button navbar-right"} [:div {:class "overlay-text" :data-hover "Analytics"}]]
[:a {:href "/essays/" :class "btn btn-default navbar-btn image-button essays-button navbar-right"} [:div {:class "overlay-text" :data-hover "Essays"}]]
[:a {:href "/chattels/" :class "btn btn-default navbar-btn image-button chattels-button navbar-right"} [:div {:class "overlay-text" :data-hover "Chattels"}]]
[:a {:href "/places/" :class "btn btn-default navbar-btn image-button places-button navbar-right"} [:div {:class "overlay-text" :data-hover "Places"}]]
[:a {:href "/people/" :class "btn btn-default navbar-btn image-button people-button navbar-right"} [:div {:class "overlay-text" :data-hover"People"}]]
[:a {:href "/" :class"btn btn-default navbar-btn image-button home-button navbar-right"} [:div { :class "overlay-text" :data-hover "Home"}]]
[:a {:href "/" :class "navbar-left"} [:img {:class "logo" :src "/images/title_bar.png"}]]]]])
(defn render-site-data
[]
[:script {:type "application/ld+json"}
(json/generate-string
{"@context" "http://schema.org"
"@type" "WebSite"
:url "http://www.normansicily.org/"
:name "The Norman Sicily Project"
:description
"The Norman Sicily Project is an effort to document the cultural heritage of Sicily from c. 1061 - 1194."
:author [{"@type" "Person"
:name "<NAME>"
:honorificSuffix "Ph.D."
:email "mailto:<EMAIL>"
:jobTitle "Associate Professor of Medieval History"
:url "http://www.thehayesweb.org/dhayes/"
:sameAs ["https://worldcat.org/identities/lccn-n2002112933/",
"https://montclair.academia.edu/DawnMarieHayes",
"https://www.linkedin.com/in/dawn-marie-hayes-49b05414/",
"http://viaf.org/viaf/76568635",
"https://www.researchgate.net/profile/Dawn_Hayes3",
"https://www.montclair.edu/profilepages/view_profile.php?username=hayesd"]}
{"@type" "Person"
:name "<NAME>"
:email "mailto:<EMAIL>"
:url "https://www.linkedin.com/in/joephayes/"
:sameAs ["https://github.com/joephayes"]}]
:sameAs ["https://www.facebook.com/TheNormanSicilyProject/"
"https://twitter.com/Norman_Sicily"
"https://www.instagram.com/thenormansicilyproject/"
"https://github.com/the-norman-sicily-project"
"http://www.worldcat.org/oclc/1003325014"]
:license "http://creativecommons.org/licenses/by-sa/4.0/"})])
(defn render-org-data
[]
[:script {:type "application/ld+json"}
(json/generate-string
{"@context" "http://schema.org"
"@type" "Organization"
:url "http://www.normansicily.org/"
:name "<NAME>"
:logo "http://www.normansicily.org/images/favicon-128.png"})])
(defn render-footer
[]
[:div {:class "footer"}
[:div {:class "container"}
[:div {:class "row bottom-padding"}
[:div {:class "col-12-xs"}
[:div {:class "center-block"}
[:a {:href "https://www.facebook.com/TheNormanSicilyProject/" :class "side-padded" :target "_blank"} [:i {:class "fa fa-facebook fa-1x rounded-corner-icon" :title "Facebook"}]]
[:a {:href "https://twitter.com/Norman_Sicily" :class "side-padded" :target "_blank"} [:i {:class "fa fa-twitter fa-1x rounded-corner-icon" :title "Twitter"}]]
[:a {:href "https://www.instagram.com/thenormansicilyproject/?hl=en" :class "side-padded" :target "_blank"} [:i {:class "fa fa-instagram fa-1x rounded-corner-icon" :title "Instagram"}]]
[:a {:href "https://github.com/the-norman-sicily-project" :class "side-padded" :target "_blank"} [:i {:class "fa fa-github fa-1x rounded-corner-icon" :title "GitHub"}]]]]]
[:div {:class "row"}
[:div {:class="col-12-xs"}
[:div {:class "footer-links"}
[:p
"© 2015 - 2019 by <NAME> and <NAME>. All Rights Reserved."
[:div {:id "license"}
[:a {:rel "license" :href "http://creativecommons.org/licenses/by-sa/4.0/"} [:img {:alt "Creative Commons License" :style "border-width:0;padding-bottom:10px" :src "https://i.creativecommons.org/l/by-sa/4.0/88x31.png"}]] [:br ] "This " [:span {:xmlns:dct "http://purl.org/dc/terms/" :href "http://purl.org/dc/dcmitype/StillImage" :rel "dct:type"} "work"] " by " [:a {:xmlns:cc "http://creativecommons.org/ns#" :href "normansicily.org" :property "cc:attributionName" :rel "cc:attributionURL"} "<NAME>, Ph.D. and <NAME> "] "is licensed under a" [:a {:rel "license" :href "http://creativecommons.org/licenses/by-sa/4.0/"} " Creative Commons Attribution-ShareAlike 4.0 International License"]]]]]]]])
| true |
(ns norman-sicily-static.partials
(:require [cheshire.core :as json]))
(defn render-navbar
[]
[:nav {:class "navbar navbar-default navbar-static-top"}
[:div {:class "container"}
[:div {:id "navbar-button-bar" :class "navbar-header"}
[:a {:href "/about/" :class "btn btn-default navbar-btn image-button about-button navbar-right"} [:div {:class "overlay-text" :data-hover "About"}]]
[:a {:href "/resources/" :class "btn btn-default navbar-btn image-button resources-button navbar-right"} [:div {:class "overlay-text" :data-hover "Resources"}]]
[:a {:href "/analytics/" :class "btn btn-default navbar-btn image-button analytics-button navbar-right"} [:div {:class "overlay-text" :data-hover "Analytics"}]]
[:a {:href "/essays/" :class "btn btn-default navbar-btn image-button essays-button navbar-right"} [:div {:class "overlay-text" :data-hover "Essays"}]]
[:a {:href "/chattels/" :class "btn btn-default navbar-btn image-button chattels-button navbar-right"} [:div {:class "overlay-text" :data-hover "Chattels"}]]
[:a {:href "/places/" :class "btn btn-default navbar-btn image-button places-button navbar-right"} [:div {:class "overlay-text" :data-hover "Places"}]]
[:a {:href "/people/" :class "btn btn-default navbar-btn image-button people-button navbar-right"} [:div {:class "overlay-text" :data-hover"People"}]]
[:a {:href "/" :class"btn btn-default navbar-btn image-button home-button navbar-right"} [:div { :class "overlay-text" :data-hover "Home"}]]
[:a {:href "/" :class "navbar-left"} [:img {:class "logo" :src "/images/title_bar.png"}]]]]])
(defn render-site-data
[]
[:script {:type "application/ld+json"}
(json/generate-string
{"@context" "http://schema.org"
"@type" "WebSite"
:url "http://www.normansicily.org/"
:name "The Norman Sicily Project"
:description
"The Norman Sicily Project is an effort to document the cultural heritage of Sicily from c. 1061 - 1194."
:author [{"@type" "Person"
:name "PI:NAME:<NAME>END_PI"
:honorificSuffix "Ph.D."
:email "mailto:PI:EMAIL:<EMAIL>END_PI"
:jobTitle "Associate Professor of Medieval History"
:url "http://www.thehayesweb.org/dhayes/"
:sameAs ["https://worldcat.org/identities/lccn-n2002112933/",
"https://montclair.academia.edu/DawnMarieHayes",
"https://www.linkedin.com/in/dawn-marie-hayes-49b05414/",
"http://viaf.org/viaf/76568635",
"https://www.researchgate.net/profile/Dawn_Hayes3",
"https://www.montclair.edu/profilepages/view_profile.php?username=hayesd"]}
{"@type" "Person"
:name "PI:NAME:<NAME>END_PI"
:email "mailto:PI:EMAIL:<EMAIL>END_PI"
:url "https://www.linkedin.com/in/joephayes/"
:sameAs ["https://github.com/joephayes"]}]
:sameAs ["https://www.facebook.com/TheNormanSicilyProject/"
"https://twitter.com/Norman_Sicily"
"https://www.instagram.com/thenormansicilyproject/"
"https://github.com/the-norman-sicily-project"
"http://www.worldcat.org/oclc/1003325014"]
:license "http://creativecommons.org/licenses/by-sa/4.0/"})])
(defn render-org-data
[]
[:script {:type "application/ld+json"}
(json/generate-string
{"@context" "http://schema.org"
"@type" "Organization"
:url "http://www.normansicily.org/"
:name "PI:NAME:<NAME>END_PI"
:logo "http://www.normansicily.org/images/favicon-128.png"})])
(defn render-footer
[]
[:div {:class "footer"}
[:div {:class "container"}
[:div {:class "row bottom-padding"}
[:div {:class "col-12-xs"}
[:div {:class "center-block"}
[:a {:href "https://www.facebook.com/TheNormanSicilyProject/" :class "side-padded" :target "_blank"} [:i {:class "fa fa-facebook fa-1x rounded-corner-icon" :title "Facebook"}]]
[:a {:href "https://twitter.com/Norman_Sicily" :class "side-padded" :target "_blank"} [:i {:class "fa fa-twitter fa-1x rounded-corner-icon" :title "Twitter"}]]
[:a {:href "https://www.instagram.com/thenormansicilyproject/?hl=en" :class "side-padded" :target "_blank"} [:i {:class "fa fa-instagram fa-1x rounded-corner-icon" :title "Instagram"}]]
[:a {:href "https://github.com/the-norman-sicily-project" :class "side-padded" :target "_blank"} [:i {:class "fa fa-github fa-1x rounded-corner-icon" :title "GitHub"}]]]]]
[:div {:class "row"}
[:div {:class="col-12-xs"}
[:div {:class "footer-links"}
[:p
"© 2015 - 2019 by PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI. All Rights Reserved."
[:div {:id "license"}
[:a {:rel "license" :href "http://creativecommons.org/licenses/by-sa/4.0/"} [:img {:alt "Creative Commons License" :style "border-width:0;padding-bottom:10px" :src "https://i.creativecommons.org/l/by-sa/4.0/88x31.png"}]] [:br ] "This " [:span {:xmlns:dct "http://purl.org/dc/terms/" :href "http://purl.org/dc/dcmitype/StillImage" :rel "dct:type"} "work"] " by " [:a {:xmlns:cc "http://creativecommons.org/ns#" :href "normansicily.org" :property "cc:attributionName" :rel "cc:attributionURL"} "PI:NAME:<NAME>END_PI, Ph.D. and PI:NAME:<NAME>END_PI "] "is licensed under a" [:a {:rel "license" :href "http://creativecommons.org/licenses/by-sa/4.0/"} " Creative Commons Attribution-ShareAlike 4.0 International License"]]]]]]]])
|
[
{
"context": "NAPSHOT\",\n :url \"https://github.com/technomancy/leiningen\"\n\n :disable-implicit-clea",
"end": 1116,
"score": 0.9992146492004395,
"start": 1105,
"tag": "USERNAME",
"value": "technomancy"
},
{
"context": " (is (= {:url \"http://\" :username \"u\" :password \"p\"}\n (-> (make\n (test-proj",
"end": 10177,
"score": 0.9991769194602966,
"start": 10176,
"tag": "PASSWORD",
"value": "p"
},
{
"context": " :password \"p\"}}}}}))\n (merge-profiles [:blue :qa",
"end": 10586,
"score": 0.9989540576934814,
"start": 10585,
"tag": "PASSWORD",
"value": "p"
}
] |
test/conflicts/mined/leiningen-cc4045b932b1bcfdb631ff5fc4f36f760c3adc9a-ef87397568ee9f5af4365b045f7ac37dd90094c/M.clj
|
nazrhom/vcs-clojure
| 3 |
(ns leiningen.core.test.project
(:refer-clojure :exclude [read])
(:use [clojure.test]
[leiningen.core.project :as project])
(:require [leiningen.core.user :as user]
[leiningen.core.classpath :as classpath]
[leiningen.core.test.helper :refer [abort-msg]]
[clojure.java.io :as io]))
(use-fixtures :once
(fn [f]
;; Can't have user-level profiles interfering!
(with-redefs [user/profiles (constantly {})
user/credentials (constantly nil)]
(f))))
(defn make-project
"Make put a project map's :profiles on it's metadata"
[m]
(project-with-profiles-meta m (:profiles m)))
(def paths {:source-paths ["src"],
:test-paths ["test"],
:resource-paths ["dev-resources" "resources"],
:compile-path "target/classes",
:native-path "target/native",
:target-path "target"})
(def expected {:name "leiningen", :group "leiningen",
:version "2.0.0-SNAPSHOT",
:url "https://github.com/technomancy/leiningen"
:disable-implicit-clean true,
:eval-in :leiningen,
:license {:name "Eclipse Public License"}
:dependencies '[[leiningen-core/leiningen-core "2.0.0-SNAPSHOT"]
[clucy/clucy "0.2.2" :exclusions [[org.clojure/clojure]]]
[lancet/lancet "1.0.1"]
[robert/hooke "1.1.2"]
[stencil/stencil "0.2.0"]],
:twelve 12 ; testing unquote
:repositories [["central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}]
["clojars" {:url "https://clojars.org/repo/"}]]})
(deftest test-read-project
(let [actual (read (.getFile (io/resource "p1.clj")))]
(doseq [[k v] expected]
(is (= v (k actual))))
(doseq [[k path] paths
:when (string? path)]
(is (= (str (:root actual) "/" path)
(k actual))))
(doseq [[k path] paths
:when (coll? path)]
(is (= (for [p path] (str (:root actual) "/" p))
(k actual))))))
;; TODO: test omit-default
;; TODO: test reading project that doesn't def project
(deftest test-merge-profile-displace-replace
(let [test-profiles {:carmine {:foo [3 4]}
:carmined {:foo ^:displace [3 4]}
:carminer {:foo ^:replace [3 4]}
:blue {:foo [5 6]}
:blued {:foo ^:displace [5 6]}
:bluer {:foo ^:replace [5 6]}
:jade {:foo [7 8]}
:jaded {:foo ^:displace [7 8]}
:jader {:foo ^:replace [7 8]}}
test-project (fn [p]
(project-with-profiles-meta
p
(merge test-profiles (:profiles p))))]
(testing "that :^displace throws away the value if another exist"
(is (= [1 2]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined])
:foo)))
(is (= [1 2 5 6]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined :blue :jaded])
:foo)))
(is (= [5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:carmined :blued])
:foo)))
(is (= [7 8 5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:carmined :jade :blued :blue])
:foo))))
(testing "that :^displace preserves metadata"
(is (= {}
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:quux :frob}
(-> (make (test-project {:foo ^{:quux :frob} [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:displace true, :quux :frob}
(-> (make (test-project
{:foo ^{:displace true, :quux :frob} [1 2]}))
(merge-profiles [:carmined :blued :jaded])
:foo meta)))
(is (= {:displace true, :a 1, :b 2}
(-> (make (test-project
{:foo ^{:displace true, :a 1} [1 2]
:profiles
{:bar {:foo
^{:displace true, :b 2} [9 0]}}}))
(merge-profiles [:jaded :bar :carmined])
:foo meta))))
(testing "that ^:replace replaces other values (at most once)"
(is (= [1 2]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carmine])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carminer])
:foo)))
(is (= [1 2 5 6]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carmine :blue])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carminer])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:jader :blue])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carminer :jade])
:foo))))
(testing "that ^:replace preserves metadata"
(is (= {}
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:quux :frob}
(-> (make (test-project {:foo ^{:quux :frob} [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:replace true, :quux :frob}
(-> (make (test-project
{:foo ^{:replace true, :quux :frob} [1 2]}))
(merge-profiles [:carminer :jader :bluer])
:foo meta)))
(is (= {:replace true, :a 1, :b 2}
(-> (make (test-project
{:foo ^{:replace true, :a 1} [1 2]
:profiles {:bar {:foo
^{:replace true, :b 2} [9 0]}}}))
(merge-profiles [:jader :bar :carminer])
:foo meta))))
(testing "that ^:displace and ^:replace operates correctly together"
(is (= [5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:bluer])
:foo)))
(is (= [1 2]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:blued])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:jader :carmined])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined :jader])
:foo))))
(testing "that metadata is preserved at ^:displace/^:replace clashes"
(is (= {:frob true}
(-> (make (test-project
{:foo ^{:displace true, :frob true} [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:frob true}
(-> (make (test-project
{:foo ^{:replace true, :frob true} [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:a 1, :b 2}
(-> (make (test-project
{:foo ^{:replace true, :a 1} [1 2]
:profiles
{:bar {:foo ^{:displace true, :a 3, :b 2} [3 4]}}}))
(merge-profiles [:bar])
:foo meta)))
(is (= {:a 3, :b 2}
(-> (make (test-project
{:foo ^{:displace true, :a 1} [1 2]
:profiles
{:bar {:foo ^{:replace true, :a 3, :b 2} [3 4]}}}))
(merge-profiles [:bar])
:foo meta))))))
(def test-profiles (atom {:qa {:resource-paths ["/etc/myapp"]}
:test {:resource-paths ["test/hi"]}
:repl {:dependencies
'[[org.clojure/tools.nrepl "0.2.0-beta6"
:exclusions [org.clojure/clojure]]
[org.thnetos/cd-client "0.3.4"
:exclusions [org.clojure/clojure]]]}
:tes :test
:dev {:test-paths ["test"]}}))
(deftest test-merge-profile-paths
(let [test-project (fn [p]
(project-with-profiles-meta
p
(merge @test-profiles (:profiles p))))]
(is (= ["/etc/myapp" "test/hi" "blue-resources" "resources"]
(-> (make
(test-project
{:resource-paths ["resources"]
:profiles {:blue {:resource-paths ["blue-resources"]}}}))
(merge-profiles [:blue :tes :qa])
:resource-paths)))
(is (= ["/etc/myapp" "test/hi" "blue-resources"]
(-> (make
(test-project
{:resource-paths ^:displace ["resources"]
:profiles {:blue {:resource-paths ["blue-resources"]}}}))
(merge-profiles [:blue :tes :qa])
:resource-paths)))
(is (= ["replaced"]
(-> (make
(test-project
{:resource-paths ["resources"]
:profiles {:blue {:resource-paths ^:replace ["replaced"]}}}))
(merge-profiles [:tes :qa :blue])
:resource-paths)))
(is (= {:url "http://" :username "u" :password "p"}
(-> (make
(test-project
{:repositories [["foo" {:url "http://" :creds :gpg}]]
:profiles {:blue {:repositories {"foo"
^:replace {:url "http://"
:username "u"
:password "p"}}}}}))
(merge-profiles [:blue :qa :tes])
:repositories
last last)))))
(deftest test-merge-profile-deps
(with-redefs [default-profiles test-profiles]
(let [project (make
{:resource-paths ["resources"]
:dependencies '[^:displace [org.foo/bar "0.1.0" :foo [1 2]]
[org.foo/baz "0.2.0" :foo [1 2]]
[org.foo/zap "0.3.0" :foo [1 2]]]
:profiles {:dev {:dependencies
'[[org.foo/bar "0.1.2"]
[org.foo/baz "0.2.1"]
^:replace [org.foo/zap "0.3.1"]]}}})]
(is (= '[[org.foo/bar "0.1.2"]
[org.foo/baz "0.2.1" :foo [1 2]]
[org.foo/zap "0.3.1"]]
(-> (make-project project)
(merge-profiles [:dev])
:dependencies))))))
(deftest test-merge-profile-repos
(with-redefs [default-profiles test-profiles]
(let [project
(make
<<<<<<< A.clj
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:red {:repositories
[^:replace ["my-repo" "https://my-repo.org/red"]]}
:green {:repositories
[^:displace
["my-repo" "https://my-repo.org/green"]]}
:empty {:repositories ^:replace []}}})]
||||||| O.clj
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:empty {:repositories ^:replace []}}})]
=======
(make-project
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:empty {:repositories ^:replace []}}}))]
>>>>>>> B.clj
(is (= default-repositories
(:repositories project)))
(is (= []
(-> (merge-profiles project [:empty])
:repositories)))
(is (= [["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:empty :blue])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]]
(-> (merge-profiles project [:clojars])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue])
:repositories)))
(is (= [["clojars.org" {:url "https://new-link.org/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue :clj-2])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue :green])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/red"}]]
(-> (merge-profiles project [:blue :clojars :red])
:repositories)))
(is (= [["my-repo" {:url "https://my-repo.org/red"}]
["clojars.org" {:url "https://new-link.org/"}]]
(-> (merge-profiles project [:empty :red :clj-2 :green])
:repositories))))))
(deftest test-global-exclusions
(let [project {:dependencies
'[[lancet "1.0.1"]
[leiningen-core "2.0.0-SNAPSHOT" :exclusions [pomegranate]]
[clucy "0.2.2" :exclusions [org.clojure/clojure]]]
:exclusions '[org.clojure/clojure]}
dependencies (:dependencies (merge-profiles project [:default]))]
(is (= '[[[org.clojure/clojure]]
[[org.clojure/clojure] [pomegranate/pomegranate]]
[[org.clojure/clojure]]]
(map #(distinct (:exclusions (apply hash-map %))) dependencies)))))
(defn add-seven [project]
(assoc project :seven 7))
(deftest test-middleware
(is (= 7 (:seven (init-project (read (.getFile (io/resource "p2.clj"))))))))
(deftest test-activate-middleware
(is (= ""
(with-out-str
(binding [*err* *out*]
(init-project (read (.getFile (io/resource "p3.clj")))))))))
(deftest test-plugin-vars
(are [project hooks middleware] (= (list hooks middleware)
(map (partial plugin-vars project) [:hooks :middleware]))
{:plugins '[[lein-foo "1.2.3"]]}
'(lein-foo.plugin/hooks) '(lein-foo.plugin/middleware)
{:plugins '[[lein-foo "1.2.3" :hooks false]]}
'() '(lein-foo.plugin/middleware)
{:plugins '[[lein-foo "1.2.3" :middleware false]]}
'(lein-foo.plugin/hooks) '()
{:plugins '[[lein-foo "1.2.3" :hooks false :middleware false]]}
'() '()))
;; (deftest test-add-profiles
;; (let [expected-result {:dependencies [] :profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}}}]
;; (is (= expected-result
;; (-> {:dependencies []}
;; (add-profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}}))))
;; (is (= expected-result
;; (-> {:dependencies []}
;; (add-profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}})
;; meta
;; :without-profiles)))))
(deftest test-merge-anon-profiles
(is (= {:A 1, :C 3}
(-> (make-project {:profiles {:a {:A 1} :b {:B 2}}})
(merge-profiles [{:C 3} :a])
(dissoc :profiles)))))
(deftest test-composite-profiles
(is (= {:A '(1 3 2), :B 2, :C 3}
(-> (make-project
{:profiles {:a [:b :c]
:b [{:A [1] :B 1 :C 1} :d]
:c {:A [2] :B 2}
:d {:A [3] :C 3}}})
(merge-profiles [:a])
(dissoc :profiles)))))
(deftest test-override-default
(is (= {:A 1, :B 2, :C 3}
(-> (make-project
{:profiles {:a {:A 1 :B 2}
:b {:B 2 :C 2}
:c {:C 3}
:default [:a :b :c]}})
(merge-profiles [:default])
(dissoc :profiles)))))
(deftest test-unmerge-profiles
(let [expected {:A 1 :C 3}]
(is (= expected
(-> (make-project
{:profiles {:a {:A 1}
:b {:B 2}
:c {:C 3}}})
(merge-profiles [:a :b :c])
(unmerge-profiles [:b])
(dissoc :profiles))))
(is (= expected
(-> (make-project
{:profiles {:a {:A 1}
:b {:B 2}
:c {:C 3}}})
(merge-profiles [:a :b :c {:D 4}])
(unmerge-profiles [:b {:D 4}])
(dissoc :profiles))))))
(deftest test-dedupe-deps
(is (= '[[org.clojure/clojure "1.3.0"]
[org.clojure/clojure "1.3.0" :classifier "sources"]]
(-> (make
{:dependencies '[[org.clojure/clojure "1.4.0"]
[org.clojure/clojure "1.3.0" :classifier "sources"]
[org.clojure/clojure "1.3.0"]]})
(:dependencies)))))
(deftest test-warn-user-repos
(if (System/getenv "LEIN_SUPPRESS_USER_LEVEL_REPO_WARNINGS")
(testing "no output with suppression"
(is (= ""
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}
"clojars" {:url "https://clojars.org/repo/"}}}}))))
(testing "with no suppression,"
(testing "no warning without user level repo"
(is (= "" (abort-msg #'project/warn-user-repos {}))
"No warning in base case"))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}
"clojars" {:url "https://clojars.org/repo/"}}}}))))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" "http://repo1.maven.org/maven2/"
"clojars" "https://clojars.org/repo/"}}}))))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user
{:repositories
[["central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}]
["clojars" {:url "https://clojars.org/repo/"}]]}})))))))
|
159
|
(ns leiningen.core.test.project
(:refer-clojure :exclude [read])
(:use [clojure.test]
[leiningen.core.project :as project])
(:require [leiningen.core.user :as user]
[leiningen.core.classpath :as classpath]
[leiningen.core.test.helper :refer [abort-msg]]
[clojure.java.io :as io]))
(use-fixtures :once
(fn [f]
;; Can't have user-level profiles interfering!
(with-redefs [user/profiles (constantly {})
user/credentials (constantly nil)]
(f))))
(defn make-project
"Make put a project map's :profiles on it's metadata"
[m]
(project-with-profiles-meta m (:profiles m)))
(def paths {:source-paths ["src"],
:test-paths ["test"],
:resource-paths ["dev-resources" "resources"],
:compile-path "target/classes",
:native-path "target/native",
:target-path "target"})
(def expected {:name "leiningen", :group "leiningen",
:version "2.0.0-SNAPSHOT",
:url "https://github.com/technomancy/leiningen"
:disable-implicit-clean true,
:eval-in :leiningen,
:license {:name "Eclipse Public License"}
:dependencies '[[leiningen-core/leiningen-core "2.0.0-SNAPSHOT"]
[clucy/clucy "0.2.2" :exclusions [[org.clojure/clojure]]]
[lancet/lancet "1.0.1"]
[robert/hooke "1.1.2"]
[stencil/stencil "0.2.0"]],
:twelve 12 ; testing unquote
:repositories [["central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}]
["clojars" {:url "https://clojars.org/repo/"}]]})
(deftest test-read-project
(let [actual (read (.getFile (io/resource "p1.clj")))]
(doseq [[k v] expected]
(is (= v (k actual))))
(doseq [[k path] paths
:when (string? path)]
(is (= (str (:root actual) "/" path)
(k actual))))
(doseq [[k path] paths
:when (coll? path)]
(is (= (for [p path] (str (:root actual) "/" p))
(k actual))))))
;; TODO: test omit-default
;; TODO: test reading project that doesn't def project
(deftest test-merge-profile-displace-replace
(let [test-profiles {:carmine {:foo [3 4]}
:carmined {:foo ^:displace [3 4]}
:carminer {:foo ^:replace [3 4]}
:blue {:foo [5 6]}
:blued {:foo ^:displace [5 6]}
:bluer {:foo ^:replace [5 6]}
:jade {:foo [7 8]}
:jaded {:foo ^:displace [7 8]}
:jader {:foo ^:replace [7 8]}}
test-project (fn [p]
(project-with-profiles-meta
p
(merge test-profiles (:profiles p))))]
(testing "that :^displace throws away the value if another exist"
(is (= [1 2]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined])
:foo)))
(is (= [1 2 5 6]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined :blue :jaded])
:foo)))
(is (= [5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:carmined :blued])
:foo)))
(is (= [7 8 5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:carmined :jade :blued :blue])
:foo))))
(testing "that :^displace preserves metadata"
(is (= {}
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:quux :frob}
(-> (make (test-project {:foo ^{:quux :frob} [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:displace true, :quux :frob}
(-> (make (test-project
{:foo ^{:displace true, :quux :frob} [1 2]}))
(merge-profiles [:carmined :blued :jaded])
:foo meta)))
(is (= {:displace true, :a 1, :b 2}
(-> (make (test-project
{:foo ^{:displace true, :a 1} [1 2]
:profiles
{:bar {:foo
^{:displace true, :b 2} [9 0]}}}))
(merge-profiles [:jaded :bar :carmined])
:foo meta))))
(testing "that ^:replace replaces other values (at most once)"
(is (= [1 2]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carmine])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carminer])
:foo)))
(is (= [1 2 5 6]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carmine :blue])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carminer])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:jader :blue])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carminer :jade])
:foo))))
(testing "that ^:replace preserves metadata"
(is (= {}
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:quux :frob}
(-> (make (test-project {:foo ^{:quux :frob} [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:replace true, :quux :frob}
(-> (make (test-project
{:foo ^{:replace true, :quux :frob} [1 2]}))
(merge-profiles [:carminer :jader :bluer])
:foo meta)))
(is (= {:replace true, :a 1, :b 2}
(-> (make (test-project
{:foo ^{:replace true, :a 1} [1 2]
:profiles {:bar {:foo
^{:replace true, :b 2} [9 0]}}}))
(merge-profiles [:jader :bar :carminer])
:foo meta))))
(testing "that ^:displace and ^:replace operates correctly together"
(is (= [5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:bluer])
:foo)))
(is (= [1 2]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:blued])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:jader :carmined])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined :jader])
:foo))))
(testing "that metadata is preserved at ^:displace/^:replace clashes"
(is (= {:frob true}
(-> (make (test-project
{:foo ^{:displace true, :frob true} [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:frob true}
(-> (make (test-project
{:foo ^{:replace true, :frob true} [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:a 1, :b 2}
(-> (make (test-project
{:foo ^{:replace true, :a 1} [1 2]
:profiles
{:bar {:foo ^{:displace true, :a 3, :b 2} [3 4]}}}))
(merge-profiles [:bar])
:foo meta)))
(is (= {:a 3, :b 2}
(-> (make (test-project
{:foo ^{:displace true, :a 1} [1 2]
:profiles
{:bar {:foo ^{:replace true, :a 3, :b 2} [3 4]}}}))
(merge-profiles [:bar])
:foo meta))))))
(def test-profiles (atom {:qa {:resource-paths ["/etc/myapp"]}
:test {:resource-paths ["test/hi"]}
:repl {:dependencies
'[[org.clojure/tools.nrepl "0.2.0-beta6"
:exclusions [org.clojure/clojure]]
[org.thnetos/cd-client "0.3.4"
:exclusions [org.clojure/clojure]]]}
:tes :test
:dev {:test-paths ["test"]}}))
(deftest test-merge-profile-paths
(let [test-project (fn [p]
(project-with-profiles-meta
p
(merge @test-profiles (:profiles p))))]
(is (= ["/etc/myapp" "test/hi" "blue-resources" "resources"]
(-> (make
(test-project
{:resource-paths ["resources"]
:profiles {:blue {:resource-paths ["blue-resources"]}}}))
(merge-profiles [:blue :tes :qa])
:resource-paths)))
(is (= ["/etc/myapp" "test/hi" "blue-resources"]
(-> (make
(test-project
{:resource-paths ^:displace ["resources"]
:profiles {:blue {:resource-paths ["blue-resources"]}}}))
(merge-profiles [:blue :tes :qa])
:resource-paths)))
(is (= ["replaced"]
(-> (make
(test-project
{:resource-paths ["resources"]
:profiles {:blue {:resource-paths ^:replace ["replaced"]}}}))
(merge-profiles [:tes :qa :blue])
:resource-paths)))
(is (= {:url "http://" :username "u" :password "<PASSWORD>"}
(-> (make
(test-project
{:repositories [["foo" {:url "http://" :creds :gpg}]]
:profiles {:blue {:repositories {"foo"
^:replace {:url "http://"
:username "u"
:password "<PASSWORD>"}}}}}))
(merge-profiles [:blue :qa :tes])
:repositories
last last)))))
(deftest test-merge-profile-deps
(with-redefs [default-profiles test-profiles]
(let [project (make
{:resource-paths ["resources"]
:dependencies '[^:displace [org.foo/bar "0.1.0" :foo [1 2]]
[org.foo/baz "0.2.0" :foo [1 2]]
[org.foo/zap "0.3.0" :foo [1 2]]]
:profiles {:dev {:dependencies
'[[org.foo/bar "0.1.2"]
[org.foo/baz "0.2.1"]
^:replace [org.foo/zap "0.3.1"]]}}})]
(is (= '[[org.foo/bar "0.1.2"]
[org.foo/baz "0.2.1" :foo [1 2]]
[org.foo/zap "0.3.1"]]
(-> (make-project project)
(merge-profiles [:dev])
:dependencies))))))
(deftest test-merge-profile-repos
(with-redefs [default-profiles test-profiles]
(let [project
(make
<<<<<<< A.clj
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:red {:repositories
[^:replace ["my-repo" "https://my-repo.org/red"]]}
:green {:repositories
[^:displace
["my-repo" "https://my-repo.org/green"]]}
:empty {:repositories ^:replace []}}})]
||||||| O.clj
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:empty {:repositories ^:replace []}}})]
=======
(make-project
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:empty {:repositories ^:replace []}}}))]
>>>>>>> B.clj
(is (= default-repositories
(:repositories project)))
(is (= []
(-> (merge-profiles project [:empty])
:repositories)))
(is (= [["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:empty :blue])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]]
(-> (merge-profiles project [:clojars])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue])
:repositories)))
(is (= [["clojars.org" {:url "https://new-link.org/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue :clj-2])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue :green])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/red"}]]
(-> (merge-profiles project [:blue :clojars :red])
:repositories)))
(is (= [["my-repo" {:url "https://my-repo.org/red"}]
["clojars.org" {:url "https://new-link.org/"}]]
(-> (merge-profiles project [:empty :red :clj-2 :green])
:repositories))))))
(deftest test-global-exclusions
(let [project {:dependencies
'[[lancet "1.0.1"]
[leiningen-core "2.0.0-SNAPSHOT" :exclusions [pomegranate]]
[clucy "0.2.2" :exclusions [org.clojure/clojure]]]
:exclusions '[org.clojure/clojure]}
dependencies (:dependencies (merge-profiles project [:default]))]
(is (= '[[[org.clojure/clojure]]
[[org.clojure/clojure] [pomegranate/pomegranate]]
[[org.clojure/clojure]]]
(map #(distinct (:exclusions (apply hash-map %))) dependencies)))))
(defn add-seven [project]
(assoc project :seven 7))
(deftest test-middleware
(is (= 7 (:seven (init-project (read (.getFile (io/resource "p2.clj"))))))))
(deftest test-activate-middleware
(is (= ""
(with-out-str
(binding [*err* *out*]
(init-project (read (.getFile (io/resource "p3.clj")))))))))
(deftest test-plugin-vars
(are [project hooks middleware] (= (list hooks middleware)
(map (partial plugin-vars project) [:hooks :middleware]))
{:plugins '[[lein-foo "1.2.3"]]}
'(lein-foo.plugin/hooks) '(lein-foo.plugin/middleware)
{:plugins '[[lein-foo "1.2.3" :hooks false]]}
'() '(lein-foo.plugin/middleware)
{:plugins '[[lein-foo "1.2.3" :middleware false]]}
'(lein-foo.plugin/hooks) '()
{:plugins '[[lein-foo "1.2.3" :hooks false :middleware false]]}
'() '()))
;; (deftest test-add-profiles
;; (let [expected-result {:dependencies [] :profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}}}]
;; (is (= expected-result
;; (-> {:dependencies []}
;; (add-profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}}))))
;; (is (= expected-result
;; (-> {:dependencies []}
;; (add-profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}})
;; meta
;; :without-profiles)))))
(deftest test-merge-anon-profiles
(is (= {:A 1, :C 3}
(-> (make-project {:profiles {:a {:A 1} :b {:B 2}}})
(merge-profiles [{:C 3} :a])
(dissoc :profiles)))))
(deftest test-composite-profiles
(is (= {:A '(1 3 2), :B 2, :C 3}
(-> (make-project
{:profiles {:a [:b :c]
:b [{:A [1] :B 1 :C 1} :d]
:c {:A [2] :B 2}
:d {:A [3] :C 3}}})
(merge-profiles [:a])
(dissoc :profiles)))))
(deftest test-override-default
(is (= {:A 1, :B 2, :C 3}
(-> (make-project
{:profiles {:a {:A 1 :B 2}
:b {:B 2 :C 2}
:c {:C 3}
:default [:a :b :c]}})
(merge-profiles [:default])
(dissoc :profiles)))))
(deftest test-unmerge-profiles
(let [expected {:A 1 :C 3}]
(is (= expected
(-> (make-project
{:profiles {:a {:A 1}
:b {:B 2}
:c {:C 3}}})
(merge-profiles [:a :b :c])
(unmerge-profiles [:b])
(dissoc :profiles))))
(is (= expected
(-> (make-project
{:profiles {:a {:A 1}
:b {:B 2}
:c {:C 3}}})
(merge-profiles [:a :b :c {:D 4}])
(unmerge-profiles [:b {:D 4}])
(dissoc :profiles))))))
(deftest test-dedupe-deps
(is (= '[[org.clojure/clojure "1.3.0"]
[org.clojure/clojure "1.3.0" :classifier "sources"]]
(-> (make
{:dependencies '[[org.clojure/clojure "1.4.0"]
[org.clojure/clojure "1.3.0" :classifier "sources"]
[org.clojure/clojure "1.3.0"]]})
(:dependencies)))))
(deftest test-warn-user-repos
(if (System/getenv "LEIN_SUPPRESS_USER_LEVEL_REPO_WARNINGS")
(testing "no output with suppression"
(is (= ""
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}
"clojars" {:url "https://clojars.org/repo/"}}}}))))
(testing "with no suppression,"
(testing "no warning without user level repo"
(is (= "" (abort-msg #'project/warn-user-repos {}))
"No warning in base case"))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}
"clojars" {:url "https://clojars.org/repo/"}}}}))))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" "http://repo1.maven.org/maven2/"
"clojars" "https://clojars.org/repo/"}}}))))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user
{:repositories
[["central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}]
["clojars" {:url "https://clojars.org/repo/"}]]}})))))))
| true |
(ns leiningen.core.test.project
(:refer-clojure :exclude [read])
(:use [clojure.test]
[leiningen.core.project :as project])
(:require [leiningen.core.user :as user]
[leiningen.core.classpath :as classpath]
[leiningen.core.test.helper :refer [abort-msg]]
[clojure.java.io :as io]))
(use-fixtures :once
(fn [f]
;; Can't have user-level profiles interfering!
(with-redefs [user/profiles (constantly {})
user/credentials (constantly nil)]
(f))))
(defn make-project
"Make put a project map's :profiles on it's metadata"
[m]
(project-with-profiles-meta m (:profiles m)))
(def paths {:source-paths ["src"],
:test-paths ["test"],
:resource-paths ["dev-resources" "resources"],
:compile-path "target/classes",
:native-path "target/native",
:target-path "target"})
(def expected {:name "leiningen", :group "leiningen",
:version "2.0.0-SNAPSHOT",
:url "https://github.com/technomancy/leiningen"
:disable-implicit-clean true,
:eval-in :leiningen,
:license {:name "Eclipse Public License"}
:dependencies '[[leiningen-core/leiningen-core "2.0.0-SNAPSHOT"]
[clucy/clucy "0.2.2" :exclusions [[org.clojure/clojure]]]
[lancet/lancet "1.0.1"]
[robert/hooke "1.1.2"]
[stencil/stencil "0.2.0"]],
:twelve 12 ; testing unquote
:repositories [["central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}]
["clojars" {:url "https://clojars.org/repo/"}]]})
(deftest test-read-project
(let [actual (read (.getFile (io/resource "p1.clj")))]
(doseq [[k v] expected]
(is (= v (k actual))))
(doseq [[k path] paths
:when (string? path)]
(is (= (str (:root actual) "/" path)
(k actual))))
(doseq [[k path] paths
:when (coll? path)]
(is (= (for [p path] (str (:root actual) "/" p))
(k actual))))))
;; TODO: test omit-default
;; TODO: test reading project that doesn't def project
(deftest test-merge-profile-displace-replace
(let [test-profiles {:carmine {:foo [3 4]}
:carmined {:foo ^:displace [3 4]}
:carminer {:foo ^:replace [3 4]}
:blue {:foo [5 6]}
:blued {:foo ^:displace [5 6]}
:bluer {:foo ^:replace [5 6]}
:jade {:foo [7 8]}
:jaded {:foo ^:displace [7 8]}
:jader {:foo ^:replace [7 8]}}
test-project (fn [p]
(project-with-profiles-meta
p
(merge test-profiles (:profiles p))))]
(testing "that :^displace throws away the value if another exist"
(is (= [1 2]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined])
:foo)))
(is (= [1 2 5 6]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined :blue :jaded])
:foo)))
(is (= [5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:carmined :blued])
:foo)))
(is (= [7 8 5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:carmined :jade :blued :blue])
:foo))))
(testing "that :^displace preserves metadata"
(is (= {}
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:quux :frob}
(-> (make (test-project {:foo ^{:quux :frob} [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:displace true, :quux :frob}
(-> (make (test-project
{:foo ^{:displace true, :quux :frob} [1 2]}))
(merge-profiles [:carmined :blued :jaded])
:foo meta)))
(is (= {:displace true, :a 1, :b 2}
(-> (make (test-project
{:foo ^{:displace true, :a 1} [1 2]
:profiles
{:bar {:foo
^{:displace true, :b 2} [9 0]}}}))
(merge-profiles [:jaded :bar :carmined])
:foo meta))))
(testing "that ^:replace replaces other values (at most once)"
(is (= [1 2]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carmine])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carminer])
:foo)))
(is (= [1 2 5 6]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carmine :blue])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carminer])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:jader :blue])
:foo)))
(is (= [3 4]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:carminer :jade])
:foo))))
(testing "that ^:replace preserves metadata"
(is (= {}
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:quux :frob}
(-> (make (test-project {:foo ^{:quux :frob} [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:replace true, :quux :frob}
(-> (make (test-project
{:foo ^{:replace true, :quux :frob} [1 2]}))
(merge-profiles [:carminer :jader :bluer])
:foo meta)))
(is (= {:replace true, :a 1, :b 2}
(-> (make (test-project
{:foo ^{:replace true, :a 1} [1 2]
:profiles {:bar {:foo
^{:replace true, :b 2} [9 0]}}}))
(merge-profiles [:jader :bar :carminer])
:foo meta))))
(testing "that ^:displace and ^:replace operates correctly together"
(is (= [5 6]
(-> (make (test-project {:foo ^:displace [1 2]}))
(merge-profiles [:bluer])
:foo)))
(is (= [1 2]
(-> (make (test-project {:foo ^:replace [1 2]}))
(merge-profiles [:blued])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:jader :carmined])
:foo)))
(is (= [7 8]
(-> (make (test-project {:foo [1 2]}))
(merge-profiles [:carmined :jader])
:foo))))
(testing "that metadata is preserved at ^:displace/^:replace clashes"
(is (= {:frob true}
(-> (make (test-project
{:foo ^{:displace true, :frob true} [1 2]}))
(merge-profiles [:carminer])
:foo meta)))
(is (= {:frob true}
(-> (make (test-project
{:foo ^{:replace true, :frob true} [1 2]}))
(merge-profiles [:carmined])
:foo meta)))
(is (= {:a 1, :b 2}
(-> (make (test-project
{:foo ^{:replace true, :a 1} [1 2]
:profiles
{:bar {:foo ^{:displace true, :a 3, :b 2} [3 4]}}}))
(merge-profiles [:bar])
:foo meta)))
(is (= {:a 3, :b 2}
(-> (make (test-project
{:foo ^{:displace true, :a 1} [1 2]
:profiles
{:bar {:foo ^{:replace true, :a 3, :b 2} [3 4]}}}))
(merge-profiles [:bar])
:foo meta))))))
(def test-profiles (atom {:qa {:resource-paths ["/etc/myapp"]}
:test {:resource-paths ["test/hi"]}
:repl {:dependencies
'[[org.clojure/tools.nrepl "0.2.0-beta6"
:exclusions [org.clojure/clojure]]
[org.thnetos/cd-client "0.3.4"
:exclusions [org.clojure/clojure]]]}
:tes :test
:dev {:test-paths ["test"]}}))
(deftest test-merge-profile-paths
(let [test-project (fn [p]
(project-with-profiles-meta
p
(merge @test-profiles (:profiles p))))]
(is (= ["/etc/myapp" "test/hi" "blue-resources" "resources"]
(-> (make
(test-project
{:resource-paths ["resources"]
:profiles {:blue {:resource-paths ["blue-resources"]}}}))
(merge-profiles [:blue :tes :qa])
:resource-paths)))
(is (= ["/etc/myapp" "test/hi" "blue-resources"]
(-> (make
(test-project
{:resource-paths ^:displace ["resources"]
:profiles {:blue {:resource-paths ["blue-resources"]}}}))
(merge-profiles [:blue :tes :qa])
:resource-paths)))
(is (= ["replaced"]
(-> (make
(test-project
{:resource-paths ["resources"]
:profiles {:blue {:resource-paths ^:replace ["replaced"]}}}))
(merge-profiles [:tes :qa :blue])
:resource-paths)))
(is (= {:url "http://" :username "u" :password "PI:PASSWORD:<PASSWORD>END_PI"}
(-> (make
(test-project
{:repositories [["foo" {:url "http://" :creds :gpg}]]
:profiles {:blue {:repositories {"foo"
^:replace {:url "http://"
:username "u"
:password "PI:PASSWORD:<PASSWORD>END_PI"}}}}}))
(merge-profiles [:blue :qa :tes])
:repositories
last last)))))
(deftest test-merge-profile-deps
(with-redefs [default-profiles test-profiles]
(let [project (make
{:resource-paths ["resources"]
:dependencies '[^:displace [org.foo/bar "0.1.0" :foo [1 2]]
[org.foo/baz "0.2.0" :foo [1 2]]
[org.foo/zap "0.3.0" :foo [1 2]]]
:profiles {:dev {:dependencies
'[[org.foo/bar "0.1.2"]
[org.foo/baz "0.2.1"]
^:replace [org.foo/zap "0.3.1"]]}}})]
(is (= '[[org.foo/bar "0.1.2"]
[org.foo/baz "0.2.1" :foo [1 2]]
[org.foo/zap "0.3.1"]]
(-> (make-project project)
(merge-profiles [:dev])
:dependencies))))))
(deftest test-merge-profile-repos
(with-redefs [default-profiles test-profiles]
(let [project
(make
<<<<<<< A.clj
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:red {:repositories
[^:replace ["my-repo" "https://my-repo.org/red"]]}
:green {:repositories
[^:displace
["my-repo" "https://my-repo.org/green"]]}
:empty {:repositories ^:replace []}}})]
||||||| O.clj
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:empty {:repositories ^:replace []}}})]
=======
(make-project
{:profiles {:clojars {:repositories ^:replace
[["clojars.org" "https://clojars.org/repo/"]]}
:clj-2 {:repositories
[["clojars.org" "https://new-link.org/"]]}
:blue {:repositories
[["my-repo" "https://my-repo.org/"]]}
:empty {:repositories ^:replace []}}}))]
>>>>>>> B.clj
(is (= default-repositories
(:repositories project)))
(is (= []
(-> (merge-profiles project [:empty])
:repositories)))
(is (= [["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:empty :blue])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]]
(-> (merge-profiles project [:clojars])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue])
:repositories)))
(is (= [["clojars.org" {:url "https://new-link.org/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue :clj-2])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/"}]]
(-> (merge-profiles project [:clojars :blue :green])
:repositories)))
(is (= [["clojars.org" {:url "https://clojars.org/repo/"}]
["my-repo" {:url "https://my-repo.org/red"}]]
(-> (merge-profiles project [:blue :clojars :red])
:repositories)))
(is (= [["my-repo" {:url "https://my-repo.org/red"}]
["clojars.org" {:url "https://new-link.org/"}]]
(-> (merge-profiles project [:empty :red :clj-2 :green])
:repositories))))))
(deftest test-global-exclusions
(let [project {:dependencies
'[[lancet "1.0.1"]
[leiningen-core "2.0.0-SNAPSHOT" :exclusions [pomegranate]]
[clucy "0.2.2" :exclusions [org.clojure/clojure]]]
:exclusions '[org.clojure/clojure]}
dependencies (:dependencies (merge-profiles project [:default]))]
(is (= '[[[org.clojure/clojure]]
[[org.clojure/clojure] [pomegranate/pomegranate]]
[[org.clojure/clojure]]]
(map #(distinct (:exclusions (apply hash-map %))) dependencies)))))
(defn add-seven [project]
(assoc project :seven 7))
(deftest test-middleware
(is (= 7 (:seven (init-project (read (.getFile (io/resource "p2.clj"))))))))
(deftest test-activate-middleware
(is (= ""
(with-out-str
(binding [*err* *out*]
(init-project (read (.getFile (io/resource "p3.clj")))))))))
(deftest test-plugin-vars
(are [project hooks middleware] (= (list hooks middleware)
(map (partial plugin-vars project) [:hooks :middleware]))
{:plugins '[[lein-foo "1.2.3"]]}
'(lein-foo.plugin/hooks) '(lein-foo.plugin/middleware)
{:plugins '[[lein-foo "1.2.3" :hooks false]]}
'() '(lein-foo.plugin/middleware)
{:plugins '[[lein-foo "1.2.3" :middleware false]]}
'(lein-foo.plugin/hooks) '()
{:plugins '[[lein-foo "1.2.3" :hooks false :middleware false]]}
'() '()))
;; (deftest test-add-profiles
;; (let [expected-result {:dependencies [] :profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}}}]
;; (is (= expected-result
;; (-> {:dependencies []}
;; (add-profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}}))))
;; (is (= expected-result
;; (-> {:dependencies []}
;; (add-profiles {:a1 {:src-paths ["a1/"]}
;; :a2 {:src-paths ["a2/"]}})
;; meta
;; :without-profiles)))))
(deftest test-merge-anon-profiles
(is (= {:A 1, :C 3}
(-> (make-project {:profiles {:a {:A 1} :b {:B 2}}})
(merge-profiles [{:C 3} :a])
(dissoc :profiles)))))
(deftest test-composite-profiles
(is (= {:A '(1 3 2), :B 2, :C 3}
(-> (make-project
{:profiles {:a [:b :c]
:b [{:A [1] :B 1 :C 1} :d]
:c {:A [2] :B 2}
:d {:A [3] :C 3}}})
(merge-profiles [:a])
(dissoc :profiles)))))
(deftest test-override-default
(is (= {:A 1, :B 2, :C 3}
(-> (make-project
{:profiles {:a {:A 1 :B 2}
:b {:B 2 :C 2}
:c {:C 3}
:default [:a :b :c]}})
(merge-profiles [:default])
(dissoc :profiles)))))
(deftest test-unmerge-profiles
(let [expected {:A 1 :C 3}]
(is (= expected
(-> (make-project
{:profiles {:a {:A 1}
:b {:B 2}
:c {:C 3}}})
(merge-profiles [:a :b :c])
(unmerge-profiles [:b])
(dissoc :profiles))))
(is (= expected
(-> (make-project
{:profiles {:a {:A 1}
:b {:B 2}
:c {:C 3}}})
(merge-profiles [:a :b :c {:D 4}])
(unmerge-profiles [:b {:D 4}])
(dissoc :profiles))))))
(deftest test-dedupe-deps
(is (= '[[org.clojure/clojure "1.3.0"]
[org.clojure/clojure "1.3.0" :classifier "sources"]]
(-> (make
{:dependencies '[[org.clojure/clojure "1.4.0"]
[org.clojure/clojure "1.3.0" :classifier "sources"]
[org.clojure/clojure "1.3.0"]]})
(:dependencies)))))
(deftest test-warn-user-repos
(if (System/getenv "LEIN_SUPPRESS_USER_LEVEL_REPO_WARNINGS")
(testing "no output with suppression"
(is (= ""
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}
"clojars" {:url "https://clojars.org/repo/"}}}}))))
(testing "with no suppression,"
(testing "no warning without user level repo"
(is (= "" (abort-msg #'project/warn-user-repos {}))
"No warning in base case"))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}
"clojars" {:url "https://clojars.org/repo/"}}}}))))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user {:repositories
{"central" "http://repo1.maven.org/maven2/"
"clojars" "https://clojars.org/repo/"}}}))))
(testing "Warning with user level repo"
(is (re-find
#"WARNING: :repositories .* [:user].*"
(abort-msg
#'project/warn-user-repos
{:user
{:repositories
[["central" {:url "http://repo1.maven.org/maven2/"
:snapshots false}]
["clojars" {:url "https://clojars.org/repo/"}]]}})))))))
|
[
{
"context": "[:developer\n [:name \"Daniel Perez Alvarez\"]\n [:email \"unindent",
"end": 352,
"score": 0.9998561143875122,
"start": 332,
"tag": "NAME",
"value": "Daniel Perez Alvarez"
},
{
"context": " Alvarez\"]\n [:email \"[email protected]\"]]]\n\n :scm {:name \"git\"\n :url \"https://gi",
"end": 414,
"score": 0.9999055862426758,
"start": 394,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": "lein-kibit \"0.1.2\"]\n [jonase/eastwood \"0.2.3\"]]}}\n\n :source-paths [\"src\"]\n :",
"end": 755,
"score": 0.7290374040603638,
"start": 749,
"tag": "USERNAME",
"value": "jonase"
}
] |
project.clj
|
unindented/ninety-nine-clojure-problems
| 0 |
(defproject ninety-nine-clojure-problems "0.0.1-SNAPSHOT"
:description "Ninety-nine Clojure problems."
:url "https://github.com/unindented/ninety-nine-clojure-problems"
:license {:name "MIT"
:url "http://opensource.org/licenses/MIT"}
:pom-addition [:developers [:developer
[:name "Daniel Perez Alvarez"]
[:email "[email protected]"]]]
:scm {:name "git"
:url "https://github.com/unindented/ninety-nine-haskell-problems"}
:dependencies [[org.clojure/clojure "1.7.0"]]
:profiles {:dev {:plugins [[lein-cljfmt "0.3.0"]
[lein-bikeshed "0.2.0"]
[lein-kibit "0.1.2"]
[jonase/eastwood "0.2.3"]]}}
:source-paths ["src"]
:test-paths ["src"])
|
48192
|
(defproject ninety-nine-clojure-problems "0.0.1-SNAPSHOT"
:description "Ninety-nine Clojure problems."
:url "https://github.com/unindented/ninety-nine-clojure-problems"
:license {:name "MIT"
:url "http://opensource.org/licenses/MIT"}
:pom-addition [:developers [:developer
[:name "<NAME>"]
[:email "<EMAIL>"]]]
:scm {:name "git"
:url "https://github.com/unindented/ninety-nine-haskell-problems"}
:dependencies [[org.clojure/clojure "1.7.0"]]
:profiles {:dev {:plugins [[lein-cljfmt "0.3.0"]
[lein-bikeshed "0.2.0"]
[lein-kibit "0.1.2"]
[jonase/eastwood "0.2.3"]]}}
:source-paths ["src"]
:test-paths ["src"])
| true |
(defproject ninety-nine-clojure-problems "0.0.1-SNAPSHOT"
:description "Ninety-nine Clojure problems."
:url "https://github.com/unindented/ninety-nine-clojure-problems"
:license {:name "MIT"
:url "http://opensource.org/licenses/MIT"}
:pom-addition [:developers [:developer
[:name "PI:NAME:<NAME>END_PI"]
[:email "PI:EMAIL:<EMAIL>END_PI"]]]
:scm {:name "git"
:url "https://github.com/unindented/ninety-nine-haskell-problems"}
:dependencies [[org.clojure/clojure "1.7.0"]]
:profiles {:dev {:plugins [[lein-cljfmt "0.3.0"]
[lein-bikeshed "0.2.0"]
[lein-kibit "0.1.2"]
[jonase/eastwood "0.2.3"]]}}
:source-paths ["src"]
:test-paths ["src"])
|
[
{
"context": "; Conway's Game of Life, based on the work of:\n;; Laurent Petit https://gist.github.com/1200343\n;; Christophe Gra",
"end": 63,
"score": 0.99986732006073,
"start": 50,
"tag": "NAME",
"value": "Laurent Petit"
},
{
"context": "work of:\n;; Laurent Petit https://gist.github.com/1200343\n;; Christophe Grand http://clj-me.cgrand.net/2011",
"end": 95,
"score": 0.9811859130859375,
"start": 88,
"tag": "USERNAME",
"value": "1200343"
},
{
"context": "; Laurent Petit https://gist.github.com/1200343\n;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-",
"end": 115,
"score": 0.9998943209648132,
"start": 99,
"tag": "NAME",
"value": "Christophe Grand"
}
] |
src/main/resources/org/netbeans/modules/clojure/ClojurePreview.clj
|
onekosha/nb-clojure
| 1 |
; Conway's Game of Life, based on the work of:
;; Laurent Petit https://gist.github.com/1200343
;; Christophe Grand http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
(ns ^{:doc "Conway's Game of Life."}
game-of-life)
;; Core game of life's algorithm functions
(defn neighbours
"Given a cell's coordinates, returns the coordinates of its neighbours."
[[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step
"Given a set of living cells, computes the new set of living cells."
[cells]
(set (for [[cell n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell)))
;; Utility methods for displaying game on a text terminal
(defn print-board
"Prints a board on *out*, representing a step in the game."
[board w h]
(doseq [x (range (inc w)) y (range (inc h))]
(if (= y 0) (print "\n"))
(print (if (board [x y]) "[X]" " . "))))
(defn display-grids
"Prints a squence of boards on *out*, representing several steps."
[grids w h]
(doseq [board grids]
(print-board board w h)
(print "\n")))
;; Launches an example board
(def
^{:doc "board represents the initial set of living cells"}
board #{[2 1] [2 2] [2 3]})
(display-grids (take 3 (iterate step board)) 5 5)
;; Let's play with characters
(println \1 \a \# \\
\" \( \newline
\} \" \space
\tab \return \backspace
\u1000 \uAaAa \u9F9F)
;; Let's play with numbers
(+ 1 -1 1/2 -1/2 -0.5 0.5)
|
111402
|
; Conway's Game of Life, based on the work of:
;; <NAME> https://gist.github.com/1200343
;; <NAME> http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
(ns ^{:doc "Conway's Game of Life."}
game-of-life)
;; Core game of life's algorithm functions
(defn neighbours
"Given a cell's coordinates, returns the coordinates of its neighbours."
[[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step
"Given a set of living cells, computes the new set of living cells."
[cells]
(set (for [[cell n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell)))
;; Utility methods for displaying game on a text terminal
(defn print-board
"Prints a board on *out*, representing a step in the game."
[board w h]
(doseq [x (range (inc w)) y (range (inc h))]
(if (= y 0) (print "\n"))
(print (if (board [x y]) "[X]" " . "))))
(defn display-grids
"Prints a squence of boards on *out*, representing several steps."
[grids w h]
(doseq [board grids]
(print-board board w h)
(print "\n")))
;; Launches an example board
(def
^{:doc "board represents the initial set of living cells"}
board #{[2 1] [2 2] [2 3]})
(display-grids (take 3 (iterate step board)) 5 5)
;; Let's play with characters
(println \1 \a \# \\
\" \( \newline
\} \" \space
\tab \return \backspace
\u1000 \uAaAa \u9F9F)
;; Let's play with numbers
(+ 1 -1 1/2 -1/2 -0.5 0.5)
| true |
; Conway's Game of Life, based on the work of:
;; PI:NAME:<NAME>END_PI https://gist.github.com/1200343
;; PI:NAME:<NAME>END_PI http://clj-me.cgrand.net/2011/08/19/conways-game-of-life
(ns ^{:doc "Conway's Game of Life."}
game-of-life)
;; Core game of life's algorithm functions
(defn neighbours
"Given a cell's coordinates, returns the coordinates of its neighbours."
[[x y]]
(for [dx [-1 0 1] dy (if (zero? dx) [-1 1] [-1 0 1])]
[(+ dx x) (+ dy y)]))
(defn step
"Given a set of living cells, computes the new set of living cells."
[cells]
(set (for [[cell n] (frequencies (mapcat neighbours cells))
:when (or (= n 3) (and (= n 2) (cells cell)))]
cell)))
;; Utility methods for displaying game on a text terminal
(defn print-board
"Prints a board on *out*, representing a step in the game."
[board w h]
(doseq [x (range (inc w)) y (range (inc h))]
(if (= y 0) (print "\n"))
(print (if (board [x y]) "[X]" " . "))))
(defn display-grids
"Prints a squence of boards on *out*, representing several steps."
[grids w h]
(doseq [board grids]
(print-board board w h)
(print "\n")))
;; Launches an example board
(def
^{:doc "board represents the initial set of living cells"}
board #{[2 1] [2 2] [2 3]})
(display-grids (take 3 (iterate step board)) 5 5)
;; Let's play with characters
(println \1 \a \# \\
\" \( \newline
\} \" \space
\tab \return \backspace
\u1000 \uAaAa \u9F9F)
;; Let's play with numbers
(+ 1 -1 1/2 -1/2 -0.5 0.5)
|
[
{
"context": "dmin (make-user\n {:user-name \"admin\"\n :name \"Imago Admin\"\n ",
"end": 12226,
"score": 0.9289966225624084,
"start": 12221,
"tag": "USERNAME",
"value": "admin"
},
{
"context": ":name \"Imago Admin\"\n :password \"imago\"})\n anon (make-user\n ",
"end": 12302,
"score": 0.9993014335632324,
"start": 12297,
"tag": "PASSWORD",
"value": "imago"
}
] |
src/imago/graph/model.clj
|
thi-ng/imago
| 1 |
(ns imago.graph.model
(:require
[imago.graph.vocab :refer :all]
[imago.utils :as utils]
[thi.ng.trio.core :as trio]
[thi.ng.trio.query :as q]
[thi.ng.trio.vocabs.utils :as vu]
[thi.ng.validate.core :as v]
[thi.ng.common.data.core :as d]
[environ.core :refer [env]]
[clojure.java.io :as io]
[slingshot.slingshot :refer [throw+]]))
(def salt (or (env :imago-salt) "969a606798c94d03b53c3fa5e83b4594"))
(defn filtered-triple-seq
[xs] (->> xs (trio/triple-seq) (filter #(-> % last nil? not))))
(defn triple-map
[props rec]
(->> props
(map
(fn [[k f]]
[(:prop f)
(if-let [ser (:values f)]
(ser (k rec))
(k rec))]))
(into {})
(merge (select-keys rec (keys (apply dissoc rec :id (keys props)))))))
(defn pick-id
[id] (fn [x] (let [k (id x)] (if (map? k) (:id k) k))))
(defn pick-id-coll
[id]
(fn [x]
(let [k (id x)
k (if (or (string? k) (number? k) (map? k)) [k] k)]
(mapv #(if (map? %) (:id %) %) k))))
(defn wrap-optional [vals] (mapv #(v/optional %) vals))
(defn build-validators
[props]
(reduce-kv
(fn [acc k {:keys [validate optional card]}]
(if validate
(let [v (if (and optional (not (map? validate)))
(wrap-optional validate)
validate)]
(assoc acc k (if (and (= card :*) (not (map? v))) {:* v} v)))
acc))
{} props))
(defn build-sorter
[id dir]
(fn [props]
(let [p (props id)]
(if (coll? p)
(vec (if (= :asc dir) (sort p) (reverse (sort p))))
p))))
(defn build-initializers
[props]
(reduce-kv
(fn [acc k {:keys [init card order]}]
(let [ordered (if order (build-sorter k order))]
(cond
init (assoc acc k (if order (fn [_] (-> _ order init)) init))
ordered (assoc acc k order)
(= :* card) (assoc acc k (pick-id-coll k))
:else acc)))
{} props))
(defn apply-initializers
[props inits]
(reduce-kv
(fn [acc k v] (if (acc k) (assoc acc k (v acc)) acc))
props inits))
(defn build-defaults
[props]
(reduce-kv
(fn [acc k {:keys [card default]}]
(cond
default (assoc acc k default)
(= :* card) (assoc acc k (fn [_] []))
:else acc))
{} props))
(defn inject-defaults
[props defaults]
(reduce-kv
(fn [acc k v] (if (nil? (acc k)) (assoc acc k (if (fn? v) (v acc) v)) acc))
props defaults))
(defn entity-map-from-triples
[triples props id]
(let [iprop (reduce-kv (fn [acc k v] (assoc acc (:prop v) k)) {} props)
conj* (fnil conj [])]
(->> triples
(filter #(= id (:s %)))
(reduce
(fn [acc [_ p o]]
(let [p' (iprop p p)
op (props p')]
(if (and op (-> op :card (not= :*)))
(assoc acc p' o)
(update-in acc [p'] conj* o))))
{:id id}))))
(defmacro defentity
[name type props]
(let [->sym (comp symbol clojure.core/name)
props (merge {:type {:prop (:type rdf)}} props)
fields (cons 'id (map ->sym (keys props)))
ctor-name (utils/->kebab-case name)
ctor (symbol (str 'make- ctor-name))
dctor (symbol (str 'describe- ctor-name))
dctor-as (symbol (str 'describe-as- ctor-name))
dctor-as2 (symbol (str 'describe-as- ctor-name '2))
mctor (symbol (str 'map-> name))]
`(let [validators# (build-validators ~props)
inits# (build-initializers ~props)
defaults# (build-defaults ~props)]
;;(prn "-------- " ~type)
;;(prn :props ~props)
;;(prn :fields ~fields)
;;(prn :validators validators#)
;;(prn :inits inits#)
;;(prn :defaults defaults#)
(defrecord ~name [~@fields]
trio/PTripleSeq
(~'triple-seq
[_#] (filtered-triple-seq {~'id (triple-map ~props _#)})))
(defn ~ctor
{:doc ~(str "Constructs a new `" (namespace-munge *ns*) "." `~name "` entity from given map.\n"
" Applies entity's property intializers, defaults & validation.\n"
" In case of validation errors, throws map of errors using `slingshot/throw+`.")
:arglists '([~'props])}
[opts#]
(let [[opts# err#]
(-> opts#
(assoc :id (or (:id opts#) (utils/new-uuid)))
(assoc :type (or (:type opts#) ~type))
(apply-initializers inits#)
(inject-defaults defaults#)
(v/validate validators#))]
(if (nil? err#) (~mctor opts#) (throw+ err#))))
(defn ~dctor
{:doc ~(str "Executes a :describe query for given entity ID in graph.\n"
" Returns seq of triples. ")
:arglists '([~'graph ~'id])}
[g# id#]
(q/query
{:describe '~'?id
:from g#
:query [{:where [['~'?id (-> ~props :type :prop) ~type]]}]
:values {'~'?id #{id#}}}))
(defn ~dctor-as
{:doc ~(str "Constructs a new `" (namespace-munge *ns*) "." `~name "` entity based on a graph query\n"
" for given entity ID and its specified props/rels (any additional rels will be included\n"
" too, but are not validated during construction). If returned query results conflict\n"
" with entity validation, throws map of errors using `slingshot/throw+`.")
:arglists '([~'graph ~'id])}
[g# id#]
(-> (~dctor g# id#)
(entity-map-from-triples ~props id#)
(~ctor))))))
(defentity User (:User imago)
{:user-name {:prop (:nick foaf)
:validate [(v/string) (v/min-length 3) (v/max-length 32)]}
:name {:prop (:name foaf)
:validate [(v/string) (v/max-length 64)]
:optional true}
:mbox {:prop (:mbox foaf)
:validate [(v/mailto)]
:optional true}
:homepage {:prop (:homepage foaf)
:validate [(v/url)]
:card :*
:optional true}
:password {:prop (:passwordSha256Hash imago)
:validate [(v/string) (v/fixed-length 64)]
:init (fn [{:keys [user-name password]}]
(if (= 64 (count password))
password
(utils/sha-256 user-name password salt)))
:optional true}
:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}})
(defentity Repository (:Repository imago)
{:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:modified {:prop (:modified dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] [(utils/timestamp)])
:card :*}
:rights {:prop (:accessRights dcterms)
:init (pick-id-coll :rights)
:validate [(v/uuid4)]
:card :*}})
(defentity Collection (:MediaCollection imago)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [_] "Untitled collection")}
:creator {:prop (:creator dcterms)
:validate [(v/uuid4)]
:init (pick-id :creator)}
:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:modified {:prop (:modified dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] [(utils/timestamp)])
:card :*
:order :asc}
:repo {:prop (:isPartOf dcterms)
:validate [(v/uuid4)]
:init (pick-id :repo)}
:rights {:prop (:accessRights dcterms)
:default (fn [_] [])
:validate {:* [(v/uuid4)]}
:card :*}
:media {:prop (:hasPart dcterms)
:validate {:* [(v/uuid4)]}
:optional true
:card :*}
:presets {:prop (:usesPreset imago)
:validate [(v/uuid4)]
:card :*}})
(defentity RightsStatement (:RightsStatement dctypes)
{:user {:prop (:subject rdf)
:validate [(v/uuid4)]
:init (pick-id :user)}
:perm {:prop (:predicate rdf)
:validate [(v/required)]}
:context {:prop (:object rdf)
:validate [(v/uuid4)]
:init (pick-id :context)}})
(defentity ImageVersionPreset (:ImageVersionPreset imago)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [{:keys [width height]}]
(if (and width height)
(str width "x" height)
"Untitled"))}
:restrict {:prop (:restrict imago)
:validate [(v/string)]
:default (fn [_] ["image/png" "image/jpeg" "image/gif" "image/tiff"])
:card :*}
:width {:prop (:width imago)
:validate [(v/number) (v/pos)]
:optional true}
:height {:prop (:height imago)
:validate [(v/number) (v/pos)]
:optional true}
:crop {:prop (:crop imago)
:validate [(v/boolean (constantly false))]
:optional true}
:filter {:prop (:filter imago)
:validate [(v/string)]
:optional true}
:mime {:prop (:format dcterms)
:validate [(v/string)]
:default (fn [_] "image/jpeg")}})
(defentity StillImage (:StillImage dctypes)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [_] "Untitled")}
:creator {:prop (:creator dcterms)
:validate [(v/uuid4)]
:init (pick-id :user)
:optional true}
:contributors {:prop (:contributor dcterms)
:validate [(v/uuid4)]
:card :*
:optional true}
:publisher {:prop (:publisher dcterms)
:validate [(v/uuid4)]
:init (pick-id :publisher)}
:submitted {:prop (:dateSubmitted dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:colls {:prop (:isPartOf dcterms)
:validate [(v/uuid4)]
:card :*}
:versions {:prop (:hasVersion dcterms)
:validate [(v/uuid4)]
:card :*
:optional true}})
(defentity ImageVersion (:ImageVersion imago)
{:preset {:prop (:references dcterms)
:validate [(v/uuid4)]
:init (pick-id :preset)}
:rights {:prop (:accessRights dcterms)
:validate [(v/uuid4)]
:card :*}})
(defn add-entity-rights
[e rights]
(->> rights
(reduce
(fn [acc [user perms]]
(reduce
(fn [[e rs] p]
(let [r (make-rights-statement {:user user :perm p :context (:id e)})]
[(update-in e [:rights] conj (:id r))
(conj rs r)]))
acc (if (coll? perms) perms [perms])))
[e []])
(apply cons)))
(defn make-repository-with-rights
[repo rights]
(-> repo make-repository (add-entity-rights rights)))
(defn make-collection-with-rights
[coll rights]
(-> coll make-collection (add-entity-rights rights)))
(defn make-image-version-with-rights
[v rights]
(-> v make-image-version (add-entity-rights rights)))
(defn default-graph
[{:keys [presets mime-types]}]
(let [presets (map
(fn [[k {:keys [mime filter crop] :as v}]]
(->> {:title (name k)
:mime (mime-types mime)
:filter (name (or filter :none))
:crop (boolean crop)}
(merge v)
(make-image-version-preset)))
presets)
admin (make-user
{:user-name "admin"
:name "Imago Admin"
:password "imago"})
anon (make-user
{:type (:AnonUser imago)
:user-name "anon"})
repo (make-repository-with-rights
{}
{(:id admin) [(:canEditRepo imago) (:canCreateColl imago)]
(:id anon) [(:canViewRepo imago) (:canCreateUser imago)]})
coll (make-collection-with-rights
{:creator (:id admin)
:repo (:id (first repo))
:presets (map :id presets)}
{(:id admin) (:canEditColl imago)
(:id anon) (:canViewColl imago)})]
(concat
(:triples (vu/load-vocab-triples (io/resource "vocabs/imago.edn")))
[admin anon]
repo
coll
presets)))
|
74522
|
(ns imago.graph.model
(:require
[imago.graph.vocab :refer :all]
[imago.utils :as utils]
[thi.ng.trio.core :as trio]
[thi.ng.trio.query :as q]
[thi.ng.trio.vocabs.utils :as vu]
[thi.ng.validate.core :as v]
[thi.ng.common.data.core :as d]
[environ.core :refer [env]]
[clojure.java.io :as io]
[slingshot.slingshot :refer [throw+]]))
(def salt (or (env :imago-salt) "969a606798c94d03b53c3fa5e83b4594"))
(defn filtered-triple-seq
[xs] (->> xs (trio/triple-seq) (filter #(-> % last nil? not))))
(defn triple-map
[props rec]
(->> props
(map
(fn [[k f]]
[(:prop f)
(if-let [ser (:values f)]
(ser (k rec))
(k rec))]))
(into {})
(merge (select-keys rec (keys (apply dissoc rec :id (keys props)))))))
(defn pick-id
[id] (fn [x] (let [k (id x)] (if (map? k) (:id k) k))))
(defn pick-id-coll
[id]
(fn [x]
(let [k (id x)
k (if (or (string? k) (number? k) (map? k)) [k] k)]
(mapv #(if (map? %) (:id %) %) k))))
(defn wrap-optional [vals] (mapv #(v/optional %) vals))
(defn build-validators
[props]
(reduce-kv
(fn [acc k {:keys [validate optional card]}]
(if validate
(let [v (if (and optional (not (map? validate)))
(wrap-optional validate)
validate)]
(assoc acc k (if (and (= card :*) (not (map? v))) {:* v} v)))
acc))
{} props))
(defn build-sorter
[id dir]
(fn [props]
(let [p (props id)]
(if (coll? p)
(vec (if (= :asc dir) (sort p) (reverse (sort p))))
p))))
(defn build-initializers
[props]
(reduce-kv
(fn [acc k {:keys [init card order]}]
(let [ordered (if order (build-sorter k order))]
(cond
init (assoc acc k (if order (fn [_] (-> _ order init)) init))
ordered (assoc acc k order)
(= :* card) (assoc acc k (pick-id-coll k))
:else acc)))
{} props))
(defn apply-initializers
[props inits]
(reduce-kv
(fn [acc k v] (if (acc k) (assoc acc k (v acc)) acc))
props inits))
(defn build-defaults
[props]
(reduce-kv
(fn [acc k {:keys [card default]}]
(cond
default (assoc acc k default)
(= :* card) (assoc acc k (fn [_] []))
:else acc))
{} props))
(defn inject-defaults
[props defaults]
(reduce-kv
(fn [acc k v] (if (nil? (acc k)) (assoc acc k (if (fn? v) (v acc) v)) acc))
props defaults))
(defn entity-map-from-triples
[triples props id]
(let [iprop (reduce-kv (fn [acc k v] (assoc acc (:prop v) k)) {} props)
conj* (fnil conj [])]
(->> triples
(filter #(= id (:s %)))
(reduce
(fn [acc [_ p o]]
(let [p' (iprop p p)
op (props p')]
(if (and op (-> op :card (not= :*)))
(assoc acc p' o)
(update-in acc [p'] conj* o))))
{:id id}))))
(defmacro defentity
[name type props]
(let [->sym (comp symbol clojure.core/name)
props (merge {:type {:prop (:type rdf)}} props)
fields (cons 'id (map ->sym (keys props)))
ctor-name (utils/->kebab-case name)
ctor (symbol (str 'make- ctor-name))
dctor (symbol (str 'describe- ctor-name))
dctor-as (symbol (str 'describe-as- ctor-name))
dctor-as2 (symbol (str 'describe-as- ctor-name '2))
mctor (symbol (str 'map-> name))]
`(let [validators# (build-validators ~props)
inits# (build-initializers ~props)
defaults# (build-defaults ~props)]
;;(prn "-------- " ~type)
;;(prn :props ~props)
;;(prn :fields ~fields)
;;(prn :validators validators#)
;;(prn :inits inits#)
;;(prn :defaults defaults#)
(defrecord ~name [~@fields]
trio/PTripleSeq
(~'triple-seq
[_#] (filtered-triple-seq {~'id (triple-map ~props _#)})))
(defn ~ctor
{:doc ~(str "Constructs a new `" (namespace-munge *ns*) "." `~name "` entity from given map.\n"
" Applies entity's property intializers, defaults & validation.\n"
" In case of validation errors, throws map of errors using `slingshot/throw+`.")
:arglists '([~'props])}
[opts#]
(let [[opts# err#]
(-> opts#
(assoc :id (or (:id opts#) (utils/new-uuid)))
(assoc :type (or (:type opts#) ~type))
(apply-initializers inits#)
(inject-defaults defaults#)
(v/validate validators#))]
(if (nil? err#) (~mctor opts#) (throw+ err#))))
(defn ~dctor
{:doc ~(str "Executes a :describe query for given entity ID in graph.\n"
" Returns seq of triples. ")
:arglists '([~'graph ~'id])}
[g# id#]
(q/query
{:describe '~'?id
:from g#
:query [{:where [['~'?id (-> ~props :type :prop) ~type]]}]
:values {'~'?id #{id#}}}))
(defn ~dctor-as
{:doc ~(str "Constructs a new `" (namespace-munge *ns*) "." `~name "` entity based on a graph query\n"
" for given entity ID and its specified props/rels (any additional rels will be included\n"
" too, but are not validated during construction). If returned query results conflict\n"
" with entity validation, throws map of errors using `slingshot/throw+`.")
:arglists '([~'graph ~'id])}
[g# id#]
(-> (~dctor g# id#)
(entity-map-from-triples ~props id#)
(~ctor))))))
(defentity User (:User imago)
{:user-name {:prop (:nick foaf)
:validate [(v/string) (v/min-length 3) (v/max-length 32)]}
:name {:prop (:name foaf)
:validate [(v/string) (v/max-length 64)]
:optional true}
:mbox {:prop (:mbox foaf)
:validate [(v/mailto)]
:optional true}
:homepage {:prop (:homepage foaf)
:validate [(v/url)]
:card :*
:optional true}
:password {:prop (:passwordSha256Hash imago)
:validate [(v/string) (v/fixed-length 64)]
:init (fn [{:keys [user-name password]}]
(if (= 64 (count password))
password
(utils/sha-256 user-name password salt)))
:optional true}
:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}})
(defentity Repository (:Repository imago)
{:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:modified {:prop (:modified dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] [(utils/timestamp)])
:card :*}
:rights {:prop (:accessRights dcterms)
:init (pick-id-coll :rights)
:validate [(v/uuid4)]
:card :*}})
(defentity Collection (:MediaCollection imago)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [_] "Untitled collection")}
:creator {:prop (:creator dcterms)
:validate [(v/uuid4)]
:init (pick-id :creator)}
:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:modified {:prop (:modified dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] [(utils/timestamp)])
:card :*
:order :asc}
:repo {:prop (:isPartOf dcterms)
:validate [(v/uuid4)]
:init (pick-id :repo)}
:rights {:prop (:accessRights dcterms)
:default (fn [_] [])
:validate {:* [(v/uuid4)]}
:card :*}
:media {:prop (:hasPart dcterms)
:validate {:* [(v/uuid4)]}
:optional true
:card :*}
:presets {:prop (:usesPreset imago)
:validate [(v/uuid4)]
:card :*}})
(defentity RightsStatement (:RightsStatement dctypes)
{:user {:prop (:subject rdf)
:validate [(v/uuid4)]
:init (pick-id :user)}
:perm {:prop (:predicate rdf)
:validate [(v/required)]}
:context {:prop (:object rdf)
:validate [(v/uuid4)]
:init (pick-id :context)}})
(defentity ImageVersionPreset (:ImageVersionPreset imago)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [{:keys [width height]}]
(if (and width height)
(str width "x" height)
"Untitled"))}
:restrict {:prop (:restrict imago)
:validate [(v/string)]
:default (fn [_] ["image/png" "image/jpeg" "image/gif" "image/tiff"])
:card :*}
:width {:prop (:width imago)
:validate [(v/number) (v/pos)]
:optional true}
:height {:prop (:height imago)
:validate [(v/number) (v/pos)]
:optional true}
:crop {:prop (:crop imago)
:validate [(v/boolean (constantly false))]
:optional true}
:filter {:prop (:filter imago)
:validate [(v/string)]
:optional true}
:mime {:prop (:format dcterms)
:validate [(v/string)]
:default (fn [_] "image/jpeg")}})
(defentity StillImage (:StillImage dctypes)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [_] "Untitled")}
:creator {:prop (:creator dcterms)
:validate [(v/uuid4)]
:init (pick-id :user)
:optional true}
:contributors {:prop (:contributor dcterms)
:validate [(v/uuid4)]
:card :*
:optional true}
:publisher {:prop (:publisher dcterms)
:validate [(v/uuid4)]
:init (pick-id :publisher)}
:submitted {:prop (:dateSubmitted dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:colls {:prop (:isPartOf dcterms)
:validate [(v/uuid4)]
:card :*}
:versions {:prop (:hasVersion dcterms)
:validate [(v/uuid4)]
:card :*
:optional true}})
(defentity ImageVersion (:ImageVersion imago)
{:preset {:prop (:references dcterms)
:validate [(v/uuid4)]
:init (pick-id :preset)}
:rights {:prop (:accessRights dcterms)
:validate [(v/uuid4)]
:card :*}})
(defn add-entity-rights
[e rights]
(->> rights
(reduce
(fn [acc [user perms]]
(reduce
(fn [[e rs] p]
(let [r (make-rights-statement {:user user :perm p :context (:id e)})]
[(update-in e [:rights] conj (:id r))
(conj rs r)]))
acc (if (coll? perms) perms [perms])))
[e []])
(apply cons)))
(defn make-repository-with-rights
[repo rights]
(-> repo make-repository (add-entity-rights rights)))
(defn make-collection-with-rights
[coll rights]
(-> coll make-collection (add-entity-rights rights)))
(defn make-image-version-with-rights
[v rights]
(-> v make-image-version (add-entity-rights rights)))
(defn default-graph
[{:keys [presets mime-types]}]
(let [presets (map
(fn [[k {:keys [mime filter crop] :as v}]]
(->> {:title (name k)
:mime (mime-types mime)
:filter (name (or filter :none))
:crop (boolean crop)}
(merge v)
(make-image-version-preset)))
presets)
admin (make-user
{:user-name "admin"
:name "Imago Admin"
:password "<PASSWORD>"})
anon (make-user
{:type (:AnonUser imago)
:user-name "anon"})
repo (make-repository-with-rights
{}
{(:id admin) [(:canEditRepo imago) (:canCreateColl imago)]
(:id anon) [(:canViewRepo imago) (:canCreateUser imago)]})
coll (make-collection-with-rights
{:creator (:id admin)
:repo (:id (first repo))
:presets (map :id presets)}
{(:id admin) (:canEditColl imago)
(:id anon) (:canViewColl imago)})]
(concat
(:triples (vu/load-vocab-triples (io/resource "vocabs/imago.edn")))
[admin anon]
repo
coll
presets)))
| true |
(ns imago.graph.model
(:require
[imago.graph.vocab :refer :all]
[imago.utils :as utils]
[thi.ng.trio.core :as trio]
[thi.ng.trio.query :as q]
[thi.ng.trio.vocabs.utils :as vu]
[thi.ng.validate.core :as v]
[thi.ng.common.data.core :as d]
[environ.core :refer [env]]
[clojure.java.io :as io]
[slingshot.slingshot :refer [throw+]]))
(def salt (or (env :imago-salt) "969a606798c94d03b53c3fa5e83b4594"))
(defn filtered-triple-seq
[xs] (->> xs (trio/triple-seq) (filter #(-> % last nil? not))))
(defn triple-map
[props rec]
(->> props
(map
(fn [[k f]]
[(:prop f)
(if-let [ser (:values f)]
(ser (k rec))
(k rec))]))
(into {})
(merge (select-keys rec (keys (apply dissoc rec :id (keys props)))))))
(defn pick-id
[id] (fn [x] (let [k (id x)] (if (map? k) (:id k) k))))
(defn pick-id-coll
[id]
(fn [x]
(let [k (id x)
k (if (or (string? k) (number? k) (map? k)) [k] k)]
(mapv #(if (map? %) (:id %) %) k))))
(defn wrap-optional [vals] (mapv #(v/optional %) vals))
(defn build-validators
[props]
(reduce-kv
(fn [acc k {:keys [validate optional card]}]
(if validate
(let [v (if (and optional (not (map? validate)))
(wrap-optional validate)
validate)]
(assoc acc k (if (and (= card :*) (not (map? v))) {:* v} v)))
acc))
{} props))
(defn build-sorter
[id dir]
(fn [props]
(let [p (props id)]
(if (coll? p)
(vec (if (= :asc dir) (sort p) (reverse (sort p))))
p))))
(defn build-initializers
[props]
(reduce-kv
(fn [acc k {:keys [init card order]}]
(let [ordered (if order (build-sorter k order))]
(cond
init (assoc acc k (if order (fn [_] (-> _ order init)) init))
ordered (assoc acc k order)
(= :* card) (assoc acc k (pick-id-coll k))
:else acc)))
{} props))
(defn apply-initializers
[props inits]
(reduce-kv
(fn [acc k v] (if (acc k) (assoc acc k (v acc)) acc))
props inits))
(defn build-defaults
[props]
(reduce-kv
(fn [acc k {:keys [card default]}]
(cond
default (assoc acc k default)
(= :* card) (assoc acc k (fn [_] []))
:else acc))
{} props))
(defn inject-defaults
[props defaults]
(reduce-kv
(fn [acc k v] (if (nil? (acc k)) (assoc acc k (if (fn? v) (v acc) v)) acc))
props defaults))
(defn entity-map-from-triples
[triples props id]
(let [iprop (reduce-kv (fn [acc k v] (assoc acc (:prop v) k)) {} props)
conj* (fnil conj [])]
(->> triples
(filter #(= id (:s %)))
(reduce
(fn [acc [_ p o]]
(let [p' (iprop p p)
op (props p')]
(if (and op (-> op :card (not= :*)))
(assoc acc p' o)
(update-in acc [p'] conj* o))))
{:id id}))))
(defmacro defentity
[name type props]
(let [->sym (comp symbol clojure.core/name)
props (merge {:type {:prop (:type rdf)}} props)
fields (cons 'id (map ->sym (keys props)))
ctor-name (utils/->kebab-case name)
ctor (symbol (str 'make- ctor-name))
dctor (symbol (str 'describe- ctor-name))
dctor-as (symbol (str 'describe-as- ctor-name))
dctor-as2 (symbol (str 'describe-as- ctor-name '2))
mctor (symbol (str 'map-> name))]
`(let [validators# (build-validators ~props)
inits# (build-initializers ~props)
defaults# (build-defaults ~props)]
;;(prn "-------- " ~type)
;;(prn :props ~props)
;;(prn :fields ~fields)
;;(prn :validators validators#)
;;(prn :inits inits#)
;;(prn :defaults defaults#)
(defrecord ~name [~@fields]
trio/PTripleSeq
(~'triple-seq
[_#] (filtered-triple-seq {~'id (triple-map ~props _#)})))
(defn ~ctor
{:doc ~(str "Constructs a new `" (namespace-munge *ns*) "." `~name "` entity from given map.\n"
" Applies entity's property intializers, defaults & validation.\n"
" In case of validation errors, throws map of errors using `slingshot/throw+`.")
:arglists '([~'props])}
[opts#]
(let [[opts# err#]
(-> opts#
(assoc :id (or (:id opts#) (utils/new-uuid)))
(assoc :type (or (:type opts#) ~type))
(apply-initializers inits#)
(inject-defaults defaults#)
(v/validate validators#))]
(if (nil? err#) (~mctor opts#) (throw+ err#))))
(defn ~dctor
{:doc ~(str "Executes a :describe query for given entity ID in graph.\n"
" Returns seq of triples. ")
:arglists '([~'graph ~'id])}
[g# id#]
(q/query
{:describe '~'?id
:from g#
:query [{:where [['~'?id (-> ~props :type :prop) ~type]]}]
:values {'~'?id #{id#}}}))
(defn ~dctor-as
{:doc ~(str "Constructs a new `" (namespace-munge *ns*) "." `~name "` entity based on a graph query\n"
" for given entity ID and its specified props/rels (any additional rels will be included\n"
" too, but are not validated during construction). If returned query results conflict\n"
" with entity validation, throws map of errors using `slingshot/throw+`.")
:arglists '([~'graph ~'id])}
[g# id#]
(-> (~dctor g# id#)
(entity-map-from-triples ~props id#)
(~ctor))))))
(defentity User (:User imago)
{:user-name {:prop (:nick foaf)
:validate [(v/string) (v/min-length 3) (v/max-length 32)]}
:name {:prop (:name foaf)
:validate [(v/string) (v/max-length 64)]
:optional true}
:mbox {:prop (:mbox foaf)
:validate [(v/mailto)]
:optional true}
:homepage {:prop (:homepage foaf)
:validate [(v/url)]
:card :*
:optional true}
:password {:prop (:passwordSha256Hash imago)
:validate [(v/string) (v/fixed-length 64)]
:init (fn [{:keys [user-name password]}]
(if (= 64 (count password))
password
(utils/sha-256 user-name password salt)))
:optional true}
:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}})
(defentity Repository (:Repository imago)
{:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:modified {:prop (:modified dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] [(utils/timestamp)])
:card :*}
:rights {:prop (:accessRights dcterms)
:init (pick-id-coll :rights)
:validate [(v/uuid4)]
:card :*}})
(defentity Collection (:MediaCollection imago)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [_] "Untitled collection")}
:creator {:prop (:creator dcterms)
:validate [(v/uuid4)]
:init (pick-id :creator)}
:created {:prop (:created dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:modified {:prop (:modified dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] [(utils/timestamp)])
:card :*
:order :asc}
:repo {:prop (:isPartOf dcterms)
:validate [(v/uuid4)]
:init (pick-id :repo)}
:rights {:prop (:accessRights dcterms)
:default (fn [_] [])
:validate {:* [(v/uuid4)]}
:card :*}
:media {:prop (:hasPart dcterms)
:validate {:* [(v/uuid4)]}
:optional true
:card :*}
:presets {:prop (:usesPreset imago)
:validate [(v/uuid4)]
:card :*}})
(defentity RightsStatement (:RightsStatement dctypes)
{:user {:prop (:subject rdf)
:validate [(v/uuid4)]
:init (pick-id :user)}
:perm {:prop (:predicate rdf)
:validate [(v/required)]}
:context {:prop (:object rdf)
:validate [(v/uuid4)]
:init (pick-id :context)}})
(defentity ImageVersionPreset (:ImageVersionPreset imago)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [{:keys [width height]}]
(if (and width height)
(str width "x" height)
"Untitled"))}
:restrict {:prop (:restrict imago)
:validate [(v/string)]
:default (fn [_] ["image/png" "image/jpeg" "image/gif" "image/tiff"])
:card :*}
:width {:prop (:width imago)
:validate [(v/number) (v/pos)]
:optional true}
:height {:prop (:height imago)
:validate [(v/number) (v/pos)]
:optional true}
:crop {:prop (:crop imago)
:validate [(v/boolean (constantly false))]
:optional true}
:filter {:prop (:filter imago)
:validate [(v/string)]
:optional true}
:mime {:prop (:format dcterms)
:validate [(v/string)]
:default (fn [_] "image/jpeg")}})
(defentity StillImage (:StillImage dctypes)
{:title {:prop (:title dcterms)
:validate [(v/string)]
:default (fn [_] "Untitled")}
:creator {:prop (:creator dcterms)
:validate [(v/uuid4)]
:init (pick-id :user)
:optional true}
:contributors {:prop (:contributor dcterms)
:validate [(v/uuid4)]
:card :*
:optional true}
:publisher {:prop (:publisher dcterms)
:validate [(v/uuid4)]
:init (pick-id :publisher)}
:submitted {:prop (:dateSubmitted dcterms)
:validate [(v/number) (v/pos)]
:default (fn [_] (utils/timestamp))}
:colls {:prop (:isPartOf dcterms)
:validate [(v/uuid4)]
:card :*}
:versions {:prop (:hasVersion dcterms)
:validate [(v/uuid4)]
:card :*
:optional true}})
(defentity ImageVersion (:ImageVersion imago)
{:preset {:prop (:references dcterms)
:validate [(v/uuid4)]
:init (pick-id :preset)}
:rights {:prop (:accessRights dcterms)
:validate [(v/uuid4)]
:card :*}})
(defn add-entity-rights
[e rights]
(->> rights
(reduce
(fn [acc [user perms]]
(reduce
(fn [[e rs] p]
(let [r (make-rights-statement {:user user :perm p :context (:id e)})]
[(update-in e [:rights] conj (:id r))
(conj rs r)]))
acc (if (coll? perms) perms [perms])))
[e []])
(apply cons)))
(defn make-repository-with-rights
[repo rights]
(-> repo make-repository (add-entity-rights rights)))
(defn make-collection-with-rights
[coll rights]
(-> coll make-collection (add-entity-rights rights)))
(defn make-image-version-with-rights
[v rights]
(-> v make-image-version (add-entity-rights rights)))
(defn default-graph
[{:keys [presets mime-types]}]
(let [presets (map
(fn [[k {:keys [mime filter crop] :as v}]]
(->> {:title (name k)
:mime (mime-types mime)
:filter (name (or filter :none))
:crop (boolean crop)}
(merge v)
(make-image-version-preset)))
presets)
admin (make-user
{:user-name "admin"
:name "Imago Admin"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
anon (make-user
{:type (:AnonUser imago)
:user-name "anon"})
repo (make-repository-with-rights
{}
{(:id admin) [(:canEditRepo imago) (:canCreateColl imago)]
(:id anon) [(:canViewRepo imago) (:canCreateUser imago)]})
coll (make-collection-with-rights
{:creator (:id admin)
:repo (:id (first repo))
:presets (map :id presets)}
{(:id admin) (:canEditColl imago)
(:id anon) (:canViewColl imago)})]
(concat
(:triples (vu/load-vocab-triples (io/resource "vocabs/imago.edn")))
[admin anon]
repo
coll
presets)))
|
[
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <[email protected]>\n; This work is free. You can redi",
"end": 34,
"score": 0.9998680353164673,
"start": 21,
"tag": "NAME",
"value": "Sebastian Hoß"
},
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <[email protected]>\n; This work is free. You can redistribute it and",
"end": 49,
"score": 0.9999280571937561,
"start": 36,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/test/clojure/finj/share_price_test.clj
|
sebhoss/finj
| 30 |
;
; Copyright © 2013 Sebastian Hoß <[email protected]>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.share-price-test
(:require [finj.share-price :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest market-price-test
(testing "with real/nominal-capital"
(is (≈ 80 (market-price :real-capital 800 :nominal-capital 1000))))
(testing "with nominal-rate, etc."
(is (≈ 57 (market-price :nominal-rate 0.1 :accumulation-factor 1.1 :effective-accumulation-factor 1.23 :period 5))))
(testing "with real/nominal-benefit"
(is (≈ 800/9 (market-price :real-benefit 120 :nominal-benefit 135))))
(testing "with real/nominal-rate and benefit"
(is (≈ -590 (market-price :period 5 :nominal-rate 0.13 :real-rate 0.1 :real-benefit 120))))
(testing "with effective accumulator and nominal-rate"
(is (≈ 35 (market-price :period 5 :effective-accumulation-factor 1.23 :nominal-rate 0.13))))
(testing "with effective accumulator, nominal-rate and agio"
(is (≈ 1279 (market-price :period 5 :effective-accumulation-factor 1.23 :nominal-rate 0.13 :agio 35))))
(testing "with real/nominal-rate"
(is (≈ 1.3 (market-price :nominal-rate 0.13 :real-rate 0.1))))
(testing "without parameters"
(is (thrown? IllegalArgumentException (market-price)))))
(deftest real-rate-test
(testing "with positive values"
(is (≈ 0.1 (real-rate :market-price 800 :nominal-rate 0.08 :agio 10 :period 5)))))
|
28280
|
;
; Copyright © 2013 <NAME> <<EMAIL>>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.share-price-test
(:require [finj.share-price :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest market-price-test
(testing "with real/nominal-capital"
(is (≈ 80 (market-price :real-capital 800 :nominal-capital 1000))))
(testing "with nominal-rate, etc."
(is (≈ 57 (market-price :nominal-rate 0.1 :accumulation-factor 1.1 :effective-accumulation-factor 1.23 :period 5))))
(testing "with real/nominal-benefit"
(is (≈ 800/9 (market-price :real-benefit 120 :nominal-benefit 135))))
(testing "with real/nominal-rate and benefit"
(is (≈ -590 (market-price :period 5 :nominal-rate 0.13 :real-rate 0.1 :real-benefit 120))))
(testing "with effective accumulator and nominal-rate"
(is (≈ 35 (market-price :period 5 :effective-accumulation-factor 1.23 :nominal-rate 0.13))))
(testing "with effective accumulator, nominal-rate and agio"
(is (≈ 1279 (market-price :period 5 :effective-accumulation-factor 1.23 :nominal-rate 0.13 :agio 35))))
(testing "with real/nominal-rate"
(is (≈ 1.3 (market-price :nominal-rate 0.13 :real-rate 0.1))))
(testing "without parameters"
(is (thrown? IllegalArgumentException (market-price)))))
(deftest real-rate-test
(testing "with positive values"
(is (≈ 0.1 (real-rate :market-price 800 :nominal-rate 0.08 :agio 10 :period 5)))))
| true |
;
; Copyright © 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.share-price-test
(:require [finj.share-price :refer :all]
[com.github.sebhoss.predicate :refer :all]
[clojure.test :refer :all]))
(deftest market-price-test
(testing "with real/nominal-capital"
(is (≈ 80 (market-price :real-capital 800 :nominal-capital 1000))))
(testing "with nominal-rate, etc."
(is (≈ 57 (market-price :nominal-rate 0.1 :accumulation-factor 1.1 :effective-accumulation-factor 1.23 :period 5))))
(testing "with real/nominal-benefit"
(is (≈ 800/9 (market-price :real-benefit 120 :nominal-benefit 135))))
(testing "with real/nominal-rate and benefit"
(is (≈ -590 (market-price :period 5 :nominal-rate 0.13 :real-rate 0.1 :real-benefit 120))))
(testing "with effective accumulator and nominal-rate"
(is (≈ 35 (market-price :period 5 :effective-accumulation-factor 1.23 :nominal-rate 0.13))))
(testing "with effective accumulator, nominal-rate and agio"
(is (≈ 1279 (market-price :period 5 :effective-accumulation-factor 1.23 :nominal-rate 0.13 :agio 35))))
(testing "with real/nominal-rate"
(is (≈ 1.3 (market-price :nominal-rate 0.13 :real-rate 0.1))))
(testing "without parameters"
(is (thrown? IllegalArgumentException (market-price)))))
(deftest real-rate-test
(testing "with positive values"
(is (≈ 0.1 (real-rate :market-price 800 :nominal-rate 0.08 :agio 10 :period 5)))))
|
[
{
"context": "und dreissig\"\n \"0033\"\n (number 33)\n \n \"14\"\n \"vierzehn\"\n (number 14)\n \n \"16\"\n \"sechzehn\"\n (number 1",
"end": 211,
"score": 0.9998186230659485,
"start": 203,
"tag": "NAME",
"value": "vierzehn"
},
{
"context": " \n \"14\"\n \"vierzehn\"\n (number 14)\n \n \"16\"\n \"sechzehn\"\n (number 16)\n\n \"17\"\n \"siebzehn\"\n (number 17)",
"end": 248,
"score": 0.9997974038124084,
"start": 240,
"tag": "NAME",
"value": "sechzehn"
},
{
"context": ")\n \n \"16\"\n \"sechzehn\"\n (number 16)\n\n \"17\"\n \"siebzehn\"\n (number 17)\n\n \"18\"\n \"achzehn\"\n \"achtzehn\"\n ",
"end": 283,
"score": 0.9998188018798828,
"start": 275,
"tag": "NAME",
"value": "siebzehn"
},
{
"context": "16)\n\n \"17\"\n \"siebzehn\"\n (number 17)\n\n \"18\"\n \"achzehn\"\n \"achtzehn\"\n (number 18)\n\n \"1.1\"\n \"1.10\"\n \"",
"end": 317,
"score": 0.999829113483429,
"start": 310,
"tag": "NAME",
"value": "achzehn"
},
{
"context": " \"siebzehn\"\n (number 17)\n\n \"18\"\n \"achzehn\"\n \"achtzehn\"\n (number 18)\n\n \"1.1\"\n \"1.10\"\n \"01.10\"\n (num",
"end": 330,
"score": 0.9997978210449219,
"start": 322,
"tag": "NAME",
"value": "achtzehn"
}
] |
duckling-time/src/main/resources/languages/de/corpus/numbers.clj
|
redlink-gmbh/redlink-nlp
| 0 |
(
; Context map
{}
"0"
"null"
"Null"
(number 0)
"1"
"ein"
"eins"
(number 1)
"33"
"dreiunddreissig"
"dreiunddreißig"
"drei und dreissig"
"0033"
(number 33)
"14"
"vierzehn"
(number 14)
"16"
"sechzehn"
(number 16)
"17"
"siebzehn"
(number 17)
"18"
"achzehn"
"achtzehn"
(number 18)
"1.1"
"1.10"
"01.10"
(number 1.1)
;; not yet supported
; "1,1"
; "1,10"
; "01,10"
; (number 1.1)
"0.77"
".77"
(number 0.77)
;; not yet supported
; "0,77"
; ",77"
; (number 0.77)
"100,000"
"100000"
"100K"
"100k"
(number 100000)
"3M"
"3,000K"
"3000000"
"3,000,000"
(number 3000000)
"1,200,000"
"1200000"
"1.2M"
"1200K"
".0012G"
(number 1200000)
"- 1,200,000"
"- 1200000"
"minus 1,200,000"
; "negativ 1200000"
"- 1.2M"
"- 1200K"
"- 0.0012G"
(number -1200000)
"5 Tausend"
"fünf Tausend"
(number 5000)
"eins zwei zwei"
(number 122)
"zweihunderttausend"
"200 Tausend"
"zweihunderd Tausend"
(number 200000)
"Einundzwanzigtausendundelf"
"Einundzwanzigtausendelf"
(number 21011)
"Siebenhunderteinundzwanzigtausendundzwölf"
"Siebenhunderteinundzwanzigtausendzwölf"
(number 721012)
"Einunddreißig Millionen zweihundertfünfzig Tausend und siebenhunderteinundzwanzig"
(number 31256721)
"4."
"vierte"
(ordinal 4)
)
|
95590
|
(
; Context map
{}
"0"
"null"
"Null"
(number 0)
"1"
"ein"
"eins"
(number 1)
"33"
"dreiunddreissig"
"dreiunddreißig"
"drei und dreissig"
"0033"
(number 33)
"14"
"<NAME>"
(number 14)
"16"
"<NAME>"
(number 16)
"17"
"<NAME>"
(number 17)
"18"
"<NAME>"
"<NAME>"
(number 18)
"1.1"
"1.10"
"01.10"
(number 1.1)
;; not yet supported
; "1,1"
; "1,10"
; "01,10"
; (number 1.1)
"0.77"
".77"
(number 0.77)
;; not yet supported
; "0,77"
; ",77"
; (number 0.77)
"100,000"
"100000"
"100K"
"100k"
(number 100000)
"3M"
"3,000K"
"3000000"
"3,000,000"
(number 3000000)
"1,200,000"
"1200000"
"1.2M"
"1200K"
".0012G"
(number 1200000)
"- 1,200,000"
"- 1200000"
"minus 1,200,000"
; "negativ 1200000"
"- 1.2M"
"- 1200K"
"- 0.0012G"
(number -1200000)
"5 Tausend"
"fünf Tausend"
(number 5000)
"eins zwei zwei"
(number 122)
"zweihunderttausend"
"200 Tausend"
"zweihunderd Tausend"
(number 200000)
"Einundzwanzigtausendundelf"
"Einundzwanzigtausendelf"
(number 21011)
"Siebenhunderteinundzwanzigtausendundzwölf"
"Siebenhunderteinundzwanzigtausendzwölf"
(number 721012)
"Einunddreißig Millionen zweihundertfünfzig Tausend und siebenhunderteinundzwanzig"
(number 31256721)
"4."
"vierte"
(ordinal 4)
)
| true |
(
; Context map
{}
"0"
"null"
"Null"
(number 0)
"1"
"ein"
"eins"
(number 1)
"33"
"dreiunddreissig"
"dreiunddreißig"
"drei und dreissig"
"0033"
(number 33)
"14"
"PI:NAME:<NAME>END_PI"
(number 14)
"16"
"PI:NAME:<NAME>END_PI"
(number 16)
"17"
"PI:NAME:<NAME>END_PI"
(number 17)
"18"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
(number 18)
"1.1"
"1.10"
"01.10"
(number 1.1)
;; not yet supported
; "1,1"
; "1,10"
; "01,10"
; (number 1.1)
"0.77"
".77"
(number 0.77)
;; not yet supported
; "0,77"
; ",77"
; (number 0.77)
"100,000"
"100000"
"100K"
"100k"
(number 100000)
"3M"
"3,000K"
"3000000"
"3,000,000"
(number 3000000)
"1,200,000"
"1200000"
"1.2M"
"1200K"
".0012G"
(number 1200000)
"- 1,200,000"
"- 1200000"
"minus 1,200,000"
; "negativ 1200000"
"- 1.2M"
"- 1200K"
"- 0.0012G"
(number -1200000)
"5 Tausend"
"fünf Tausend"
(number 5000)
"eins zwei zwei"
(number 122)
"zweihunderttausend"
"200 Tausend"
"zweihunderd Tausend"
(number 200000)
"Einundzwanzigtausendundelf"
"Einundzwanzigtausendelf"
(number 21011)
"Siebenhunderteinundzwanzigtausendundzwölf"
"Siebenhunderteinundzwanzigtausendzwölf"
(number 721012)
"Einunddreißig Millionen zweihundertfünfzig Tausend und siebenhunderteinundzwanzig"
(number 31256721)
"4."
"vierte"
(ordinal 4)
)
|
[
{
"context": " (validate-graphite-reporter-config {:extra-key 444 :filter-regex #\".*\" :period-ms 300 :prefix \"\" :h",
"end": 2581,
"score": 0.8158203959465027,
"start": 2580,
"tag": "KEY",
"value": "4"
}
] |
waiter/test/waiter/reporters_test.clj
|
twosigmajab/waiter
| 0 |
;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.reporters-test
(:require [clj-time.core :as t]
[clojure.test :refer [deftest is]] ;; not using :refer :all because clojure.test has "report" that conflicts with waiter.reporter/report
[metrics.core :as mc]
[metrics.counters :as counters]
[waiter.metrics :as metrics]
[waiter.reporter :refer :all])
(:import (clojure.lang ExceptionInfo)
(com.codahale.metrics MetricFilter MetricRegistry ConsoleReporter)
(com.codahale.metrics.graphite GraphiteSender)
(java.io PrintStream ByteArrayOutputStream)))
(def ^:private all-metrics-match-filter (reify MetricFilter (matches [_ _ _] true)))
(defmacro with-isolated-registry
[& body]
`(with-redefs [mc/default-registry (MetricRegistry.)]
(.removeMatching mc/default-registry all-metrics-match-filter)
(do ~@body)
(.removeMatching mc/default-registry all-metrics-match-filter)))
(deftest console-reporter-bad-schema
(is (thrown-with-msg? ExceptionInfo #"period-ms missing-required-key"
(validate-console-reporter-config {:extra-key 444}))))
(deftest console-reporter-good-schema
(validate-console-reporter-config {:extra-key 444 :filter-regex #".*" :period-ms 300}))
(deftest graphite-reporter-bad-schema
(is (thrown-with-msg? ExceptionInfo #"host missing-required-key"
(validate-graphite-reporter-config {:extra-key 444}))))
(deftest graphite-reporter-bad-schema-2
(is (thrown-with-msg? ExceptionInfo #":port \(not \(pos\?"
(validate-graphite-reporter-config {:period-ms 300 :host "localhost" :port -7777}))))
(deftest graphite-reporter-bad-schema-3
(is (thrown-with-msg? ExceptionInfo #":period-ms \(not \(integer\?"
(validate-graphite-reporter-config {:period-ms "five" :host "localhost" :port 7777}))))
(deftest graphite-reporter-good-schema
(validate-graphite-reporter-config {:extra-key 444 :filter-regex #".*" :period-ms 300 :prefix "" :host "localhost" :port 7777}))
(defn make-printstream []
(let [os (ByteArrayOutputStream.)
ps (PrintStream. os)]
{:ps ps :out #(.toString os "UTF8")}))
(deftest console-reporter-wildcard-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [{:keys [ps out]} (make-printstream)
[console-reporter state] (make-console-reporter #".*" ps)]
(is (instance? ConsoleReporter console-reporter))
(.report console-reporter)
(is (= "
-- Counters --------------------------------------------------------------------
services.service-id.counters.fee.fie
count = 0
services.service-id.counters.foo
count = 0
services.service-id.counters.foo.bar
count = 100"
(->> (out)
(clojure.string/split-lines)
(drop 1)
(clojure.string/join "\n"))))
(is (= {:run-state :created} @state)))))
(deftest console-reporter-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [{:keys [ps out]} (make-printstream)
[console-reporter state] (make-console-reporter #"^.*fee.*" ps)]
(is (instance? ConsoleReporter console-reporter))
(.report console-reporter)
(is (= "
-- Counters --------------------------------------------------------------------
services.service-id.counters.fee.fie
count = 0"
(->> (out)
(clojure.string/split-lines)
(drop 1)
(clojure.string/join "\n"))))
(is (= {:run-state :created} @state)))))
;; maximum expected test duration. used for fuzzy timestamp comparison
(def max-test-duration-ms 5000)
(deftest graphite-reporter-wildcard-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(metrics/service-histogram "service-id" "fum")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom {})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ name value timestamp] (swap! actual-values assoc name value "timestamp" timestamp)))
codahale-reporter (make-graphite-reporter 0 #".*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(report codahale-reporter))
(is (= #{"prefix.services.service-id.counters.fee.fie"
"prefix.services.service-id.counters.foo"
"prefix.services.service-id.counters.foo.bar"
"prefix.services.service-id.histograms.fum.count"
"prefix.services.service-id.histograms.fum.value.0_0"
"prefix.services.service-id.histograms.fum.value.0_25"
"prefix.services.service-id.histograms.fum.value.0_5"
"prefix.services.service-id.histograms.fum.value.0_75"
"prefix.services.service-id.histograms.fum.value.0_95"
"prefix.services.service-id.histograms.fum.value.0_99"
"prefix.services.service-id.histograms.fum.value.0_999"
"prefix.services.service-id.histograms.fum.value.1_0"
"timestamp"}
(set (keys @actual-values))))
(is (= (get @actual-values "prefix.services.service-id.counters.fee.fie") "0"))
(is (= (get @actual-values "prefix.services.service-id.counters.foo") "0"))
(is (= (get @actual-values "prefix.services.service-id.counters.foo.bar") "100"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.count") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_0") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_25") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_5") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_75") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_95") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_99") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_999") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.1_0") "0"))
(is (< (Math/abs (- (* 1000 (get @actual-values "timestamp")) (System/currentTimeMillis))) max-test-duration-ms))
(is (= {:run-state :created
:last-reporting-time time
:failed-writes-to-server 0
:last-report-successful true} (state codahale-reporter))))))
(deftest graphite-reporter-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(metrics/service-histogram "service-id" "fum")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom {})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ name value timestamp] (swap! actual-values assoc name value "timestamp" timestamp)))
codahale-reporter (make-graphite-reporter 0 #"^.*fee.*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(report codahale-reporter))
(is (= #{"prefix.services.service-id.counters.fee.fie"
"timestamp"}
(set (keys @actual-values))))
(is (= (get @actual-values "prefix.services.service-id.counters.fee.fie") "0"))
(is (< (Math/abs (- (* 1000 (get @actual-values "timestamp")) (System/currentTimeMillis))) max-test-duration-ms))
(is (= {:run-state :created
:last-reporting-time time
:failed-writes-to-server 0
:last-report-successful true} (state codahale-reporter))))))
(deftest graphite-reporter-wildcard-filter-exception
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom #{})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ _ _ _] (throw (ex-info "test" {}))))
codahale-reporter (make-graphite-reporter 0 #".*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(is (thrown-with-msg? ExceptionInfo #"^test$"
(report codahale-reporter))))
(is (= #{} @actual-values))
(is (= {:run-state :created
:last-send-failed-time time
:failed-writes-to-server 0
:last-report-successful false} (state codahale-reporter))))))
|
60530
|
;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.reporters-test
(:require [clj-time.core :as t]
[clojure.test :refer [deftest is]] ;; not using :refer :all because clojure.test has "report" that conflicts with waiter.reporter/report
[metrics.core :as mc]
[metrics.counters :as counters]
[waiter.metrics :as metrics]
[waiter.reporter :refer :all])
(:import (clojure.lang ExceptionInfo)
(com.codahale.metrics MetricFilter MetricRegistry ConsoleReporter)
(com.codahale.metrics.graphite GraphiteSender)
(java.io PrintStream ByteArrayOutputStream)))
(def ^:private all-metrics-match-filter (reify MetricFilter (matches [_ _ _] true)))
(defmacro with-isolated-registry
[& body]
`(with-redefs [mc/default-registry (MetricRegistry.)]
(.removeMatching mc/default-registry all-metrics-match-filter)
(do ~@body)
(.removeMatching mc/default-registry all-metrics-match-filter)))
(deftest console-reporter-bad-schema
(is (thrown-with-msg? ExceptionInfo #"period-ms missing-required-key"
(validate-console-reporter-config {:extra-key 444}))))
(deftest console-reporter-good-schema
(validate-console-reporter-config {:extra-key 444 :filter-regex #".*" :period-ms 300}))
(deftest graphite-reporter-bad-schema
(is (thrown-with-msg? ExceptionInfo #"host missing-required-key"
(validate-graphite-reporter-config {:extra-key 444}))))
(deftest graphite-reporter-bad-schema-2
(is (thrown-with-msg? ExceptionInfo #":port \(not \(pos\?"
(validate-graphite-reporter-config {:period-ms 300 :host "localhost" :port -7777}))))
(deftest graphite-reporter-bad-schema-3
(is (thrown-with-msg? ExceptionInfo #":period-ms \(not \(integer\?"
(validate-graphite-reporter-config {:period-ms "five" :host "localhost" :port 7777}))))
(deftest graphite-reporter-good-schema
(validate-graphite-reporter-config {:extra-key 4<KEY>4 :filter-regex #".*" :period-ms 300 :prefix "" :host "localhost" :port 7777}))
(defn make-printstream []
(let [os (ByteArrayOutputStream.)
ps (PrintStream. os)]
{:ps ps :out #(.toString os "UTF8")}))
(deftest console-reporter-wildcard-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [{:keys [ps out]} (make-printstream)
[console-reporter state] (make-console-reporter #".*" ps)]
(is (instance? ConsoleReporter console-reporter))
(.report console-reporter)
(is (= "
-- Counters --------------------------------------------------------------------
services.service-id.counters.fee.fie
count = 0
services.service-id.counters.foo
count = 0
services.service-id.counters.foo.bar
count = 100"
(->> (out)
(clojure.string/split-lines)
(drop 1)
(clojure.string/join "\n"))))
(is (= {:run-state :created} @state)))))
(deftest console-reporter-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [{:keys [ps out]} (make-printstream)
[console-reporter state] (make-console-reporter #"^.*fee.*" ps)]
(is (instance? ConsoleReporter console-reporter))
(.report console-reporter)
(is (= "
-- Counters --------------------------------------------------------------------
services.service-id.counters.fee.fie
count = 0"
(->> (out)
(clojure.string/split-lines)
(drop 1)
(clojure.string/join "\n"))))
(is (= {:run-state :created} @state)))))
;; maximum expected test duration. used for fuzzy timestamp comparison
(def max-test-duration-ms 5000)
(deftest graphite-reporter-wildcard-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(metrics/service-histogram "service-id" "fum")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom {})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ name value timestamp] (swap! actual-values assoc name value "timestamp" timestamp)))
codahale-reporter (make-graphite-reporter 0 #".*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(report codahale-reporter))
(is (= #{"prefix.services.service-id.counters.fee.fie"
"prefix.services.service-id.counters.foo"
"prefix.services.service-id.counters.foo.bar"
"prefix.services.service-id.histograms.fum.count"
"prefix.services.service-id.histograms.fum.value.0_0"
"prefix.services.service-id.histograms.fum.value.0_25"
"prefix.services.service-id.histograms.fum.value.0_5"
"prefix.services.service-id.histograms.fum.value.0_75"
"prefix.services.service-id.histograms.fum.value.0_95"
"prefix.services.service-id.histograms.fum.value.0_99"
"prefix.services.service-id.histograms.fum.value.0_999"
"prefix.services.service-id.histograms.fum.value.1_0"
"timestamp"}
(set (keys @actual-values))))
(is (= (get @actual-values "prefix.services.service-id.counters.fee.fie") "0"))
(is (= (get @actual-values "prefix.services.service-id.counters.foo") "0"))
(is (= (get @actual-values "prefix.services.service-id.counters.foo.bar") "100"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.count") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_0") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_25") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_5") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_75") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_95") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_99") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_999") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.1_0") "0"))
(is (< (Math/abs (- (* 1000 (get @actual-values "timestamp")) (System/currentTimeMillis))) max-test-duration-ms))
(is (= {:run-state :created
:last-reporting-time time
:failed-writes-to-server 0
:last-report-successful true} (state codahale-reporter))))))
(deftest graphite-reporter-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(metrics/service-histogram "service-id" "fum")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom {})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ name value timestamp] (swap! actual-values assoc name value "timestamp" timestamp)))
codahale-reporter (make-graphite-reporter 0 #"^.*fee.*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(report codahale-reporter))
(is (= #{"prefix.services.service-id.counters.fee.fie"
"timestamp"}
(set (keys @actual-values))))
(is (= (get @actual-values "prefix.services.service-id.counters.fee.fie") "0"))
(is (< (Math/abs (- (* 1000 (get @actual-values "timestamp")) (System/currentTimeMillis))) max-test-duration-ms))
(is (= {:run-state :created
:last-reporting-time time
:failed-writes-to-server 0
:last-report-successful true} (state codahale-reporter))))))
(deftest graphite-reporter-wildcard-filter-exception
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom #{})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ _ _ _] (throw (ex-info "test" {}))))
codahale-reporter (make-graphite-reporter 0 #".*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(is (thrown-with-msg? ExceptionInfo #"^test$"
(report codahale-reporter))))
(is (= #{} @actual-values))
(is (= {:run-state :created
:last-send-failed-time time
:failed-writes-to-server 0
:last-report-successful false} (state codahale-reporter))))))
| true |
;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(ns waiter.reporters-test
(:require [clj-time.core :as t]
[clojure.test :refer [deftest is]] ;; not using :refer :all because clojure.test has "report" that conflicts with waiter.reporter/report
[metrics.core :as mc]
[metrics.counters :as counters]
[waiter.metrics :as metrics]
[waiter.reporter :refer :all])
(:import (clojure.lang ExceptionInfo)
(com.codahale.metrics MetricFilter MetricRegistry ConsoleReporter)
(com.codahale.metrics.graphite GraphiteSender)
(java.io PrintStream ByteArrayOutputStream)))
(def ^:private all-metrics-match-filter (reify MetricFilter (matches [_ _ _] true)))
(defmacro with-isolated-registry
[& body]
`(with-redefs [mc/default-registry (MetricRegistry.)]
(.removeMatching mc/default-registry all-metrics-match-filter)
(do ~@body)
(.removeMatching mc/default-registry all-metrics-match-filter)))
(deftest console-reporter-bad-schema
(is (thrown-with-msg? ExceptionInfo #"period-ms missing-required-key"
(validate-console-reporter-config {:extra-key 444}))))
(deftest console-reporter-good-schema
(validate-console-reporter-config {:extra-key 444 :filter-regex #".*" :period-ms 300}))
(deftest graphite-reporter-bad-schema
(is (thrown-with-msg? ExceptionInfo #"host missing-required-key"
(validate-graphite-reporter-config {:extra-key 444}))))
(deftest graphite-reporter-bad-schema-2
(is (thrown-with-msg? ExceptionInfo #":port \(not \(pos\?"
(validate-graphite-reporter-config {:period-ms 300 :host "localhost" :port -7777}))))
(deftest graphite-reporter-bad-schema-3
(is (thrown-with-msg? ExceptionInfo #":period-ms \(not \(integer\?"
(validate-graphite-reporter-config {:period-ms "five" :host "localhost" :port 7777}))))
(deftest graphite-reporter-good-schema
(validate-graphite-reporter-config {:extra-key 4PI:KEY:<KEY>END_PI4 :filter-regex #".*" :period-ms 300 :prefix "" :host "localhost" :port 7777}))
(defn make-printstream []
(let [os (ByteArrayOutputStream.)
ps (PrintStream. os)]
{:ps ps :out #(.toString os "UTF8")}))
(deftest console-reporter-wildcard-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [{:keys [ps out]} (make-printstream)
[console-reporter state] (make-console-reporter #".*" ps)]
(is (instance? ConsoleReporter console-reporter))
(.report console-reporter)
(is (= "
-- Counters --------------------------------------------------------------------
services.service-id.counters.fee.fie
count = 0
services.service-id.counters.foo
count = 0
services.service-id.counters.foo.bar
count = 100"
(->> (out)
(clojure.string/split-lines)
(drop 1)
(clojure.string/join "\n"))))
(is (= {:run-state :created} @state)))))
(deftest console-reporter-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [{:keys [ps out]} (make-printstream)
[console-reporter state] (make-console-reporter #"^.*fee.*" ps)]
(is (instance? ConsoleReporter console-reporter))
(.report console-reporter)
(is (= "
-- Counters --------------------------------------------------------------------
services.service-id.counters.fee.fie
count = 0"
(->> (out)
(clojure.string/split-lines)
(drop 1)
(clojure.string/join "\n"))))
(is (= {:run-state :created} @state)))))
;; maximum expected test duration. used for fuzzy timestamp comparison
(def max-test-duration-ms 5000)
(deftest graphite-reporter-wildcard-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(metrics/service-histogram "service-id" "fum")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom {})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ name value timestamp] (swap! actual-values assoc name value "timestamp" timestamp)))
codahale-reporter (make-graphite-reporter 0 #".*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(report codahale-reporter))
(is (= #{"prefix.services.service-id.counters.fee.fie"
"prefix.services.service-id.counters.foo"
"prefix.services.service-id.counters.foo.bar"
"prefix.services.service-id.histograms.fum.count"
"prefix.services.service-id.histograms.fum.value.0_0"
"prefix.services.service-id.histograms.fum.value.0_25"
"prefix.services.service-id.histograms.fum.value.0_5"
"prefix.services.service-id.histograms.fum.value.0_75"
"prefix.services.service-id.histograms.fum.value.0_95"
"prefix.services.service-id.histograms.fum.value.0_99"
"prefix.services.service-id.histograms.fum.value.0_999"
"prefix.services.service-id.histograms.fum.value.1_0"
"timestamp"}
(set (keys @actual-values))))
(is (= (get @actual-values "prefix.services.service-id.counters.fee.fie") "0"))
(is (= (get @actual-values "prefix.services.service-id.counters.foo") "0"))
(is (= (get @actual-values "prefix.services.service-id.counters.foo.bar") "100"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.count") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_0") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_25") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_5") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_75") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_95") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_99") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.0_999") "0"))
(is (= (get @actual-values "prefix.services.service-id.histograms.fum.value.1_0") "0"))
(is (< (Math/abs (- (* 1000 (get @actual-values "timestamp")) (System/currentTimeMillis))) max-test-duration-ms))
(is (= {:run-state :created
:last-reporting-time time
:failed-writes-to-server 0
:last-report-successful true} (state codahale-reporter))))))
(deftest graphite-reporter-filter
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(metrics/service-histogram "service-id" "fum")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom {})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ name value timestamp] (swap! actual-values assoc name value "timestamp" timestamp)))
codahale-reporter (make-graphite-reporter 0 #"^.*fee.*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(report codahale-reporter))
(is (= #{"prefix.services.service-id.counters.fee.fie"
"timestamp"}
(set (keys @actual-values))))
(is (= (get @actual-values "prefix.services.service-id.counters.fee.fie") "0"))
(is (< (Math/abs (- (* 1000 (get @actual-values "timestamp")) (System/currentTimeMillis))) max-test-duration-ms))
(is (= {:run-state :created
:last-reporting-time time
:failed-writes-to-server 0
:last-report-successful true} (state codahale-reporter))))))
(deftest graphite-reporter-wildcard-filter-exception
(with-isolated-registry
(metrics/service-counter "service-id" "foo")
(metrics/service-counter "service-id" "foo" "bar")
(metrics/service-counter "service-id" "fee" "fie")
(counters/inc! (metrics/service-counter "service-id" "foo" "bar") 100)
(let [actual-values (atom #{})
time (t/now)
graphite (reify GraphiteSender
(flush [_])
(getFailures [_] 0)
(isConnected [_] true)
(send [_ _ _ _] (throw (ex-info "test" {}))))
codahale-reporter (make-graphite-reporter 0 #".*" "prefix" graphite)]
(is (satisfies? CodahaleReporter codahale-reporter))
(with-redefs [t/now (constantly time)]
(is (thrown-with-msg? ExceptionInfo #"^test$"
(report codahale-reporter))))
(is (= #{} @actual-values))
(is (= {:run-state :created
:last-send-failed-time time
:failed-writes-to-server 0
:last-report-successful false} (state codahale-reporter))))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998151659965515,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] |
test/clojure/test_clojure/java/io.clj
|
lorettahe/clojure
| 1 |
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.test-clojure.java.io
(:use clojure.test clojure.java.io
[clojure.test-helper :only [platform-newlines]])
(:import (java.io File BufferedInputStream
FileInputStream InputStreamReader InputStream
FileOutputStream OutputStreamWriter OutputStream
ByteArrayInputStream ByteArrayOutputStream)
(java.net URL URI Socket ServerSocket)))
(defn temp-file
[prefix suffix]
(doto (File/createTempFile prefix suffix)
(.deleteOnExit)))
;; does not work on IBM JDK
#_(deftest test-spit-and-slurp
(let [f (temp-file "clojure.java.io" "test")
content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))]
(spit f content)
(is (= content (slurp f)))
;; UTF-16 must be last for the following test
(doseq [enc [ "UTF-8" "UTF-16BE" "UTF-16LE" "UTF-16" ]]
(spit f content :encoding enc)
(is (= content (slurp f :encoding enc))))
(testing "deprecated arity"
(is (=
(platform-newlines "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).\n")
(with-out-str
(is (= content (slurp f "UTF-16")))))))))
(deftest test-streams-defaults
(let [f (temp-file "clojure.java.io" "test-reader-writer")
content "testing"]
(try
(is (thrown? Exception (reader (Object.))))
(is (thrown? Exception (writer (Object.))))
(are [write-to read-from] (= content (do
(spit write-to content :encoding "UTF-8")
(slurp read-from :encoding "UTF-8")))
f f
(.getAbsolutePath f) (.getAbsolutePath f)
(.toURL f) (.toURL f)
(.toURI f) (.toURI f)
(FileOutputStream. f) (FileInputStream. f)
(OutputStreamWriter. (FileOutputStream. f) "UTF-8") (reader f :encoding "UTF-8")
f (FileInputStream. f)
(writer f :encoding "UTF-8") (InputStreamReader. (FileInputStream. f) "UTF-8"))
(is (= content (slurp (.getBytes content "UTF-8"))))
(is (= content (slurp (.toCharArray content))))
(finally
(.delete f)))))
(defn bytes-should-equal [byte-array-1 byte-array-2 msg]
(is (= @#'clojure.java.io/byte-array-type (class byte-array-1) (class byte-array-2)) msg)
(is (= (into [] byte-array-1) (into [] byte-array-2)) msg))
(defn data-fixture
"in memory fixture data for tests"
[encoding]
(let [s (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))
bs (.getBytes s encoding)
cs (.toCharArray s)
i (ByteArrayInputStream. bs)
;; Make UTF-8 encoding explicit for the InputStreamReader and
;; OutputStreamWriter, since some JVMs use a different default
;; encoding.
r (InputStreamReader. i "UTF-8")
o (ByteArrayOutputStream.)
w (OutputStreamWriter. o "UTF-8")]
{:bs bs
:i i
:r r
:o o
:s s
:cs cs
:w w}))
(deftest test-copy
(dorun
(for [{:keys [in out flush] :as test}
[{:in :i :out :o}
{:in :i :out :w}
{:in :r :out :o}
{:in :r :out :w}
{:in :cs :out :o}
{:in :cs :out :w}
{:in :bs :out :o}
{:in :bs :out :w}]
opts
[{} {:buffer-size 16} {:buffer-size 256}]]
(let [{:keys [s o] :as d} (data-fixture "UTF-8")]
(apply copy (in d) (out d) (flatten (vec opts)))
#_(when (= out :w) (.flush (:w d)))
(.flush (out d))
(bytes-should-equal (.getBytes s "UTF-8")
(.toByteArray o)
(str "combination " test opts))))))
;; does not work on IBM JDK
#_(deftest test-copy-encodings
(doseq [enc [ "UTF-8" "UTF-16" "UTF-16BE" "UTF-16LE" ]]
(testing (str "from inputstream " enc " to writer UTF-8")
(let [{:keys [i s o w bs]} (data-fixture enc)]
(copy i w :encoding enc :buffer-size 16)
(.flush w)
(bytes-should-equal (.getBytes s "UTF-8") (.toByteArray o) "")))
(testing (str "from reader UTF-8 to output-stream " enc)
(let [{:keys [r o s]} (data-fixture "UTF-8")]
(copy r o :encoding enc :buffer-size 16)
(bytes-should-equal (.getBytes s enc) (.toByteArray o) "")))))
(deftest test-as-file
(are [result input] (= result (as-file input))
(File. "foo") "foo"
(File. "bar") (File. "bar")
(File. "baz") (URL. "file:baz")
(File. "bar+baz") (URL. "file:bar+baz")
(File. "bar baz qux") (URL. "file:bar%20baz%20qux")
(File. "quux") (URI. "file:quux")
(File. "abcíd/foo.txt") (URL. "file:abc%c3%add/foo.txt")
nil nil))
(deftest test-resources-with-spaces
(let [file-with-spaces (temp-file "test resource 2" "txt")
url (as-url (.getParentFile file-with-spaces))
loader (java.net.URLClassLoader. (into-array [url]))
r (resource (.getName file-with-spaces) loader)]
(is (= r (as-url file-with-spaces)))
(spit r "foobar")
(is (= "foobar" (slurp r)))))
(deftest test-file
(are [result args] (= (File. result) (apply file args))
"foo" ["foo"]
"foo/bar" ["foo" "bar"]
"foo/bar/baz" ["foo" "bar" "baz"]))
(deftest test-as-url
(are [file-part input] (= (URL. (str "file:" file-part)) (as-url input))
"foo" "file:foo"
"baz" (URL. "file:baz")
"quux" (URI. "file:quux"))
(is (nil? (as-url nil))))
(deftest test-delete-file
(let [file (temp-file "test" "deletion")
not-file (File. (str (java.util.UUID/randomUUID)))]
(delete-file (.getAbsolutePath file))
(is (not (.exists file)))
(is (thrown? java.io.IOException (delete-file not-file)))
(is (= :silently (delete-file not-file :silently)))))
(deftest test-as-relative-path
(testing "strings"
(is (= "foo" (as-relative-path "foo"))))
(testing "absolute path strings are forbidden"
(is (thrown? IllegalArgumentException (as-relative-path (.getAbsolutePath (File. "baz"))))))
(testing "relative File paths"
(is (= "bar" (as-relative-path (File. "bar")))))
(testing "absolute File paths are forbidden"
(is (thrown? IllegalArgumentException (as-relative-path (File. (.getAbsolutePath (File. "quux"))))))))
(defn stream-should-have [stream expected-bytes msg]
(let [actual-bytes (byte-array (alength expected-bytes))]
(.read stream actual-bytes)
(is (= -1 (.read stream)) (str msg " : should be end of stream"))
(is (= (seq expected-bytes) (seq actual-bytes)) (str msg " : byte arrays should match"))))
(deftest test-input-stream
(let [file (temp-file "test-input-stream" "txt")
content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))
bytes (.getBytes content "UTF-8")]
(spit file content)
(doseq [[expr msg]
[[file File]
[(FileInputStream. file) FileInputStream]
[(BufferedInputStream. (FileInputStream. file)) BufferedInputStream]
[(.. file toURI) URI]
[(.. file toURI toURL) URL]
[(.. file toURI toURL toString) "URL as String"]
[(.. file toString) "File as String"]]]
(with-open [s (input-stream expr)]
(stream-should-have s bytes msg)))))
(deftest test-streams-buffering
(let [data (.getBytes "")]
(is (instance? java.io.BufferedReader (reader data)))
(is (instance? java.io.BufferedWriter (writer (java.io.ByteArrayOutputStream.))))
(is (instance? java.io.BufferedInputStream (input-stream data)))
(is (instance? java.io.BufferedOutputStream (output-stream (java.io.ByteArrayOutputStream.))))))
(deftest test-resource
(is (nil? (resource "non/existent/resource")))
(is (instance? URL (resource "clojure/core.clj")))
(let [file (temp-file "test-resource" "txt")
url (as-url (.getParentFile file))
loader (java.net.URLClassLoader. (into-array [url]))]
(is (nil? (resource "non/existent/resource" loader)))
(is (instance? URL (resource (.getName file) loader)))))
(deftest test-make-parents
(let [tmp (System/getProperty "java.io.tmpdir")]
(delete-file (file tmp "test-make-parents" "child" "grandchild") :silently)
(delete-file (file tmp "test-make-parents" "child") :silently)
(delete-file (file tmp "test-make-parents") :silently)
(make-parents tmp "test-make-parents" "child" "grandchild")
(is (.isDirectory (file tmp "test-make-parents" "child")))
(is (not (.isDirectory (file tmp "test-make-parents" "child" "grandchild"))))
(delete-file (file tmp "test-make-parents" "child"))
(delete-file (file tmp "test-make-parents"))))
(deftest test-socket-iofactory
(let [port 65321
server-socket (ServerSocket. port)
client-socket (Socket. "localhost" port)]
(try
(is (instance? InputStream (input-stream client-socket)))
(is (instance? OutputStream (output-stream client-socket)))
(finally (.close server-socket)
(.close client-socket)))))
|
27162
|
; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.test-clojure.java.io
(:use clojure.test clojure.java.io
[clojure.test-helper :only [platform-newlines]])
(:import (java.io File BufferedInputStream
FileInputStream InputStreamReader InputStream
FileOutputStream OutputStreamWriter OutputStream
ByteArrayInputStream ByteArrayOutputStream)
(java.net URL URI Socket ServerSocket)))
(defn temp-file
[prefix suffix]
(doto (File/createTempFile prefix suffix)
(.deleteOnExit)))
;; does not work on IBM JDK
#_(deftest test-spit-and-slurp
(let [f (temp-file "clojure.java.io" "test")
content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))]
(spit f content)
(is (= content (slurp f)))
;; UTF-16 must be last for the following test
(doseq [enc [ "UTF-8" "UTF-16BE" "UTF-16LE" "UTF-16" ]]
(spit f content :encoding enc)
(is (= content (slurp f :encoding enc))))
(testing "deprecated arity"
(is (=
(platform-newlines "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).\n")
(with-out-str
(is (= content (slurp f "UTF-16")))))))))
(deftest test-streams-defaults
(let [f (temp-file "clojure.java.io" "test-reader-writer")
content "testing"]
(try
(is (thrown? Exception (reader (Object.))))
(is (thrown? Exception (writer (Object.))))
(are [write-to read-from] (= content (do
(spit write-to content :encoding "UTF-8")
(slurp read-from :encoding "UTF-8")))
f f
(.getAbsolutePath f) (.getAbsolutePath f)
(.toURL f) (.toURL f)
(.toURI f) (.toURI f)
(FileOutputStream. f) (FileInputStream. f)
(OutputStreamWriter. (FileOutputStream. f) "UTF-8") (reader f :encoding "UTF-8")
f (FileInputStream. f)
(writer f :encoding "UTF-8") (InputStreamReader. (FileInputStream. f) "UTF-8"))
(is (= content (slurp (.getBytes content "UTF-8"))))
(is (= content (slurp (.toCharArray content))))
(finally
(.delete f)))))
(defn bytes-should-equal [byte-array-1 byte-array-2 msg]
(is (= @#'clojure.java.io/byte-array-type (class byte-array-1) (class byte-array-2)) msg)
(is (= (into [] byte-array-1) (into [] byte-array-2)) msg))
(defn data-fixture
"in memory fixture data for tests"
[encoding]
(let [s (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))
bs (.getBytes s encoding)
cs (.toCharArray s)
i (ByteArrayInputStream. bs)
;; Make UTF-8 encoding explicit for the InputStreamReader and
;; OutputStreamWriter, since some JVMs use a different default
;; encoding.
r (InputStreamReader. i "UTF-8")
o (ByteArrayOutputStream.)
w (OutputStreamWriter. o "UTF-8")]
{:bs bs
:i i
:r r
:o o
:s s
:cs cs
:w w}))
(deftest test-copy
(dorun
(for [{:keys [in out flush] :as test}
[{:in :i :out :o}
{:in :i :out :w}
{:in :r :out :o}
{:in :r :out :w}
{:in :cs :out :o}
{:in :cs :out :w}
{:in :bs :out :o}
{:in :bs :out :w}]
opts
[{} {:buffer-size 16} {:buffer-size 256}]]
(let [{:keys [s o] :as d} (data-fixture "UTF-8")]
(apply copy (in d) (out d) (flatten (vec opts)))
#_(when (= out :w) (.flush (:w d)))
(.flush (out d))
(bytes-should-equal (.getBytes s "UTF-8")
(.toByteArray o)
(str "combination " test opts))))))
;; does not work on IBM JDK
#_(deftest test-copy-encodings
(doseq [enc [ "UTF-8" "UTF-16" "UTF-16BE" "UTF-16LE" ]]
(testing (str "from inputstream " enc " to writer UTF-8")
(let [{:keys [i s o w bs]} (data-fixture enc)]
(copy i w :encoding enc :buffer-size 16)
(.flush w)
(bytes-should-equal (.getBytes s "UTF-8") (.toByteArray o) "")))
(testing (str "from reader UTF-8 to output-stream " enc)
(let [{:keys [r o s]} (data-fixture "UTF-8")]
(copy r o :encoding enc :buffer-size 16)
(bytes-should-equal (.getBytes s enc) (.toByteArray o) "")))))
(deftest test-as-file
(are [result input] (= result (as-file input))
(File. "foo") "foo"
(File. "bar") (File. "bar")
(File. "baz") (URL. "file:baz")
(File. "bar+baz") (URL. "file:bar+baz")
(File. "bar baz qux") (URL. "file:bar%20baz%20qux")
(File. "quux") (URI. "file:quux")
(File. "abcíd/foo.txt") (URL. "file:abc%c3%add/foo.txt")
nil nil))
(deftest test-resources-with-spaces
(let [file-with-spaces (temp-file "test resource 2" "txt")
url (as-url (.getParentFile file-with-spaces))
loader (java.net.URLClassLoader. (into-array [url]))
r (resource (.getName file-with-spaces) loader)]
(is (= r (as-url file-with-spaces)))
(spit r "foobar")
(is (= "foobar" (slurp r)))))
(deftest test-file
(are [result args] (= (File. result) (apply file args))
"foo" ["foo"]
"foo/bar" ["foo" "bar"]
"foo/bar/baz" ["foo" "bar" "baz"]))
(deftest test-as-url
(are [file-part input] (= (URL. (str "file:" file-part)) (as-url input))
"foo" "file:foo"
"baz" (URL. "file:baz")
"quux" (URI. "file:quux"))
(is (nil? (as-url nil))))
(deftest test-delete-file
(let [file (temp-file "test" "deletion")
not-file (File. (str (java.util.UUID/randomUUID)))]
(delete-file (.getAbsolutePath file))
(is (not (.exists file)))
(is (thrown? java.io.IOException (delete-file not-file)))
(is (= :silently (delete-file not-file :silently)))))
(deftest test-as-relative-path
(testing "strings"
(is (= "foo" (as-relative-path "foo"))))
(testing "absolute path strings are forbidden"
(is (thrown? IllegalArgumentException (as-relative-path (.getAbsolutePath (File. "baz"))))))
(testing "relative File paths"
(is (= "bar" (as-relative-path (File. "bar")))))
(testing "absolute File paths are forbidden"
(is (thrown? IllegalArgumentException (as-relative-path (File. (.getAbsolutePath (File. "quux"))))))))
(defn stream-should-have [stream expected-bytes msg]
(let [actual-bytes (byte-array (alength expected-bytes))]
(.read stream actual-bytes)
(is (= -1 (.read stream)) (str msg " : should be end of stream"))
(is (= (seq expected-bytes) (seq actual-bytes)) (str msg " : byte arrays should match"))))
(deftest test-input-stream
(let [file (temp-file "test-input-stream" "txt")
content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))
bytes (.getBytes content "UTF-8")]
(spit file content)
(doseq [[expr msg]
[[file File]
[(FileInputStream. file) FileInputStream]
[(BufferedInputStream. (FileInputStream. file)) BufferedInputStream]
[(.. file toURI) URI]
[(.. file toURI toURL) URL]
[(.. file toURI toURL toString) "URL as String"]
[(.. file toString) "File as String"]]]
(with-open [s (input-stream expr)]
(stream-should-have s bytes msg)))))
(deftest test-streams-buffering
(let [data (.getBytes "")]
(is (instance? java.io.BufferedReader (reader data)))
(is (instance? java.io.BufferedWriter (writer (java.io.ByteArrayOutputStream.))))
(is (instance? java.io.BufferedInputStream (input-stream data)))
(is (instance? java.io.BufferedOutputStream (output-stream (java.io.ByteArrayOutputStream.))))))
(deftest test-resource
(is (nil? (resource "non/existent/resource")))
(is (instance? URL (resource "clojure/core.clj")))
(let [file (temp-file "test-resource" "txt")
url (as-url (.getParentFile file))
loader (java.net.URLClassLoader. (into-array [url]))]
(is (nil? (resource "non/existent/resource" loader)))
(is (instance? URL (resource (.getName file) loader)))))
(deftest test-make-parents
(let [tmp (System/getProperty "java.io.tmpdir")]
(delete-file (file tmp "test-make-parents" "child" "grandchild") :silently)
(delete-file (file tmp "test-make-parents" "child") :silently)
(delete-file (file tmp "test-make-parents") :silently)
(make-parents tmp "test-make-parents" "child" "grandchild")
(is (.isDirectory (file tmp "test-make-parents" "child")))
(is (not (.isDirectory (file tmp "test-make-parents" "child" "grandchild"))))
(delete-file (file tmp "test-make-parents" "child"))
(delete-file (file tmp "test-make-parents"))))
(deftest test-socket-iofactory
(let [port 65321
server-socket (ServerSocket. port)
client-socket (Socket. "localhost" port)]
(try
(is (instance? InputStream (input-stream client-socket)))
(is (instance? OutputStream (output-stream client-socket)))
(finally (.close server-socket)
(.close client-socket)))))
| true |
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.test-clojure.java.io
(:use clojure.test clojure.java.io
[clojure.test-helper :only [platform-newlines]])
(:import (java.io File BufferedInputStream
FileInputStream InputStreamReader InputStream
FileOutputStream OutputStreamWriter OutputStream
ByteArrayInputStream ByteArrayOutputStream)
(java.net URL URI Socket ServerSocket)))
(defn temp-file
[prefix suffix]
(doto (File/createTempFile prefix suffix)
(.deleteOnExit)))
;; does not work on IBM JDK
#_(deftest test-spit-and-slurp
(let [f (temp-file "clojure.java.io" "test")
content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))]
(spit f content)
(is (= content (slurp f)))
;; UTF-16 must be last for the following test
(doseq [enc [ "UTF-8" "UTF-16BE" "UTF-16LE" "UTF-16" ]]
(spit f content :encoding enc)
(is (= content (slurp f :encoding enc))))
(testing "deprecated arity"
(is (=
(platform-newlines "WARNING: (slurp f enc) is deprecated, use (slurp f :encoding enc).\n")
(with-out-str
(is (= content (slurp f "UTF-16")))))))))
(deftest test-streams-defaults
(let [f (temp-file "clojure.java.io" "test-reader-writer")
content "testing"]
(try
(is (thrown? Exception (reader (Object.))))
(is (thrown? Exception (writer (Object.))))
(are [write-to read-from] (= content (do
(spit write-to content :encoding "UTF-8")
(slurp read-from :encoding "UTF-8")))
f f
(.getAbsolutePath f) (.getAbsolutePath f)
(.toURL f) (.toURL f)
(.toURI f) (.toURI f)
(FileOutputStream. f) (FileInputStream. f)
(OutputStreamWriter. (FileOutputStream. f) "UTF-8") (reader f :encoding "UTF-8")
f (FileInputStream. f)
(writer f :encoding "UTF-8") (InputStreamReader. (FileInputStream. f) "UTF-8"))
(is (= content (slurp (.getBytes content "UTF-8"))))
(is (= content (slurp (.toCharArray content))))
(finally
(.delete f)))))
(defn bytes-should-equal [byte-array-1 byte-array-2 msg]
(is (= @#'clojure.java.io/byte-array-type (class byte-array-1) (class byte-array-2)) msg)
(is (= (into [] byte-array-1) (into [] byte-array-2)) msg))
(defn data-fixture
"in memory fixture data for tests"
[encoding]
(let [s (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))
bs (.getBytes s encoding)
cs (.toCharArray s)
i (ByteArrayInputStream. bs)
;; Make UTF-8 encoding explicit for the InputStreamReader and
;; OutputStreamWriter, since some JVMs use a different default
;; encoding.
r (InputStreamReader. i "UTF-8")
o (ByteArrayOutputStream.)
w (OutputStreamWriter. o "UTF-8")]
{:bs bs
:i i
:r r
:o o
:s s
:cs cs
:w w}))
(deftest test-copy
(dorun
(for [{:keys [in out flush] :as test}
[{:in :i :out :o}
{:in :i :out :w}
{:in :r :out :o}
{:in :r :out :w}
{:in :cs :out :o}
{:in :cs :out :w}
{:in :bs :out :o}
{:in :bs :out :w}]
opts
[{} {:buffer-size 16} {:buffer-size 256}]]
(let [{:keys [s o] :as d} (data-fixture "UTF-8")]
(apply copy (in d) (out d) (flatten (vec opts)))
#_(when (= out :w) (.flush (:w d)))
(.flush (out d))
(bytes-should-equal (.getBytes s "UTF-8")
(.toByteArray o)
(str "combination " test opts))))))
;; does not work on IBM JDK
#_(deftest test-copy-encodings
(doseq [enc [ "UTF-8" "UTF-16" "UTF-16BE" "UTF-16LE" ]]
(testing (str "from inputstream " enc " to writer UTF-8")
(let [{:keys [i s o w bs]} (data-fixture enc)]
(copy i w :encoding enc :buffer-size 16)
(.flush w)
(bytes-should-equal (.getBytes s "UTF-8") (.toByteArray o) "")))
(testing (str "from reader UTF-8 to output-stream " enc)
(let [{:keys [r o s]} (data-fixture "UTF-8")]
(copy r o :encoding enc :buffer-size 16)
(bytes-should-equal (.getBytes s enc) (.toByteArray o) "")))))
(deftest test-as-file
(are [result input] (= result (as-file input))
(File. "foo") "foo"
(File. "bar") (File. "bar")
(File. "baz") (URL. "file:baz")
(File. "bar+baz") (URL. "file:bar+baz")
(File. "bar baz qux") (URL. "file:bar%20baz%20qux")
(File. "quux") (URI. "file:quux")
(File. "abcíd/foo.txt") (URL. "file:abc%c3%add/foo.txt")
nil nil))
(deftest test-resources-with-spaces
(let [file-with-spaces (temp-file "test resource 2" "txt")
url (as-url (.getParentFile file-with-spaces))
loader (java.net.URLClassLoader. (into-array [url]))
r (resource (.getName file-with-spaces) loader)]
(is (= r (as-url file-with-spaces)))
(spit r "foobar")
(is (= "foobar" (slurp r)))))
(deftest test-file
(are [result args] (= (File. result) (apply file args))
"foo" ["foo"]
"foo/bar" ["foo" "bar"]
"foo/bar/baz" ["foo" "bar" "baz"]))
(deftest test-as-url
(are [file-part input] (= (URL. (str "file:" file-part)) (as-url input))
"foo" "file:foo"
"baz" (URL. "file:baz")
"quux" (URI. "file:quux"))
(is (nil? (as-url nil))))
(deftest test-delete-file
(let [file (temp-file "test" "deletion")
not-file (File. (str (java.util.UUID/randomUUID)))]
(delete-file (.getAbsolutePath file))
(is (not (.exists file)))
(is (thrown? java.io.IOException (delete-file not-file)))
(is (= :silently (delete-file not-file :silently)))))
(deftest test-as-relative-path
(testing "strings"
(is (= "foo" (as-relative-path "foo"))))
(testing "absolute path strings are forbidden"
(is (thrown? IllegalArgumentException (as-relative-path (.getAbsolutePath (File. "baz"))))))
(testing "relative File paths"
(is (= "bar" (as-relative-path (File. "bar")))))
(testing "absolute File paths are forbidden"
(is (thrown? IllegalArgumentException (as-relative-path (File. (.getAbsolutePath (File. "quux"))))))))
(defn stream-should-have [stream expected-bytes msg]
(let [actual-bytes (byte-array (alength expected-bytes))]
(.read stream actual-bytes)
(is (= -1 (.read stream)) (str msg " : should be end of stream"))
(is (= (seq expected-bytes) (seq actual-bytes)) (str msg " : byte arrays should match"))))
(deftest test-input-stream
(let [file (temp-file "test-input-stream" "txt")
content (apply str (concat "a" (repeat 500 "\u226a\ud83d\ude03")))
bytes (.getBytes content "UTF-8")]
(spit file content)
(doseq [[expr msg]
[[file File]
[(FileInputStream. file) FileInputStream]
[(BufferedInputStream. (FileInputStream. file)) BufferedInputStream]
[(.. file toURI) URI]
[(.. file toURI toURL) URL]
[(.. file toURI toURL toString) "URL as String"]
[(.. file toString) "File as String"]]]
(with-open [s (input-stream expr)]
(stream-should-have s bytes msg)))))
(deftest test-streams-buffering
(let [data (.getBytes "")]
(is (instance? java.io.BufferedReader (reader data)))
(is (instance? java.io.BufferedWriter (writer (java.io.ByteArrayOutputStream.))))
(is (instance? java.io.BufferedInputStream (input-stream data)))
(is (instance? java.io.BufferedOutputStream (output-stream (java.io.ByteArrayOutputStream.))))))
(deftest test-resource
(is (nil? (resource "non/existent/resource")))
(is (instance? URL (resource "clojure/core.clj")))
(let [file (temp-file "test-resource" "txt")
url (as-url (.getParentFile file))
loader (java.net.URLClassLoader. (into-array [url]))]
(is (nil? (resource "non/existent/resource" loader)))
(is (instance? URL (resource (.getName file) loader)))))
(deftest test-make-parents
(let [tmp (System/getProperty "java.io.tmpdir")]
(delete-file (file tmp "test-make-parents" "child" "grandchild") :silently)
(delete-file (file tmp "test-make-parents" "child") :silently)
(delete-file (file tmp "test-make-parents") :silently)
(make-parents tmp "test-make-parents" "child" "grandchild")
(is (.isDirectory (file tmp "test-make-parents" "child")))
(is (not (.isDirectory (file tmp "test-make-parents" "child" "grandchild"))))
(delete-file (file tmp "test-make-parents" "child"))
(delete-file (file tmp "test-make-parents"))))
(deftest test-socket-iofactory
(let [port 65321
server-socket (ServerSocket. port)
client-socket (Socket. "localhost" port)]
(try
(is (instance? InputStream (input-stream client-socket)))
(is (instance? OutputStream (output-stream client-socket)))
(finally (.close server-socket)
(.close client-socket)))))
|
[
{
"context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998817443847656,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
}
] |
src/territory_bro/db.clj
|
JessRoberts/territory_assistant
| 0 |
;; Copyright © 2015-2019 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.db
(:require [clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[conman.core :as conman]
[hugsql.adapter.clojure-java-jdbc] ; for hugsql.core/get-adapter to not crash on first usage
[hugsql.core :as hugsql]
[mount.core :as mount]
[territory-bro.config :as config]
[territory-bro.json :as json]
[territory-bro.util :refer [getx]])
(:import (clojure.lang IPersistentMap IPersistentVector)
(com.zaxxer.hikari HikariDataSource)
(java.net URL)
(java.sql Date Timestamp PreparedStatement Array)
(org.flywaydb.core Flyway)
(org.postgresql.util PGobject)))
;; PostgreSQL error codes
;; https://www.postgresql.org/docs/11/errcodes-appendix.html
(def psql-serialization-failure "40001")
(def psql-undefined-object "42704")
(def psql-duplicate-object "42710")
(defn connect! [database-url]
(log/info "Connect" database-url)
(conman/connect! {:jdbc-url database-url}))
(defn disconnect! [connection]
(log/info "Disconnect" (if-let [ds (:datasource connection)]
(.getJdbcUrl ^HikariDataSource ds)))
(conman/disconnect! connection))
(mount/defstate database
:start (connect! (getx config/env :database-url))
:stop (disconnect! database))
(defn to-date [^java.util.Date sql-date]
(-> sql-date (.getTime) (java.util.Date.)))
(extend-protocol jdbc/IResultSetReadColumn
Date
(result-set-read-column [v _ _] (to-date v))
Timestamp
(result-set-read-column [v _ _] (to-date v))
Array
(result-set-read-column [v _ _] (vec (.getArray v)))
PGobject
(result-set-read-column [pgobj _metadata _index]
(let [type (.getType pgobj)
value (.getValue pgobj)]
(case type
"json" (json/parse-string value)
"jsonb" (json/parse-string value)
"citext" (str value)
value))))
(extend-type java.util.Date
jdbc/ISQLParameter
(set-parameter [v ^PreparedStatement stmt idx]
(.setTimestamp stmt idx (Timestamp. (.getTime v)))))
(defn to-pg-json [value]
(doto (PGobject.)
(.setType "jsonb")
(.setValue (json/generate-string value))))
(extend-type IPersistentVector
jdbc/ISQLParameter
(set-parameter [v ^PreparedStatement stmt ^long idx]
(let [conn (.getConnection stmt)
meta (.getParameterMetaData stmt)
type-name (.getParameterTypeName meta idx)]
(if-let [elem-type (when (= (first type-name) \_) (apply str (rest type-name)))]
(.setObject stmt idx (.createArrayOf conn elem-type (to-array v)))
(.setObject stmt idx (to-pg-json v))))))
(extend-protocol jdbc/ISQLValue
IPersistentMap
(sql-value [value] (to-pg-json value))
IPersistentVector
(sql-value [value] (to-pg-json value)))
;; new stuff
(defn- ^"[Ljava.lang.String;" strings [& strings]
(into-array String strings))
(defn ^Flyway master-schema [schema]
(-> (Flyway/configure)
(.dataSource (:datasource database))
(.schemas (strings schema))
(.locations (strings "classpath:db/flyway/master"))
(.placeholders {"masterSchema" schema})
(.load)))
(defn ^Flyway tenant-schema [schema master-schema]
(-> (Flyway/configure)
(.dataSource (:datasource database))
(.schemas (strings schema))
(.locations (strings "classpath:db/flyway/tenant"))
(.placeholders {"masterSchema" master-schema})
(.load)))
(defn migrate-master-schema! []
(let [schema (:database-schema config/env)]
(log/info "Migrating master schema:" schema)
(-> (master-schema schema)
(.migrate))))
(defn migrate-tenant-schema! [schema]
(log/info "Migrating tenant schema:" schema)
(-> (tenant-schema schema (:database-schema config/env))
(.migrate)))
(defn get-schemas [conn]
(->> (jdbc/query conn ["select schema_name from information_schema.schemata"])
(map :schema_name)
(doall)))
(defn set-search-path [conn schemas]
(doseq [schema schemas]
(assert (and schema (re-matches #"^[a-zA-Z0-9_]+$" schema))
{:schema schema}))
(jdbc/execute! conn [(str "set search_path to " (str/join "," schemas))]))
(def ^:private public-schema "public") ; contains PostGIS types
(defn use-master-schema [conn]
(set-search-path conn [(:database-schema config/env)
public-schema]))
(defn use-tenant-schema [conn tenant-schema]
(set-search-path conn [(:database-schema config/env)
tenant-schema
public-schema]))
(defmacro with-db [binding & body]
(let [conn (first binding)
options (merge {:isolation :serializable}
(second binding))]
`(jdbc/with-db-transaction [~conn database ~options]
(use-master-schema ~conn)
~@body)))
(defn check-database-version [minimum-version]
(with-db [conn {:read-only? true}]
(let [metadata (-> (jdbc/db-connection conn) .getMetaData)
version (.getDatabaseMajorVersion metadata)]
(assert (>= version minimum-version)
(str "Expected the database to be PostgreSQL " minimum-version " but it was "
(.getDatabaseProductName metadata) " " (.getDatabaseProductVersion metadata))))))
(defn- load-queries [*queries]
;; TODO: implement detecting resource changes to clojure.tools.namespace.repl/refresh
(let [{queries :queries, resource :resource, old-last-modified :last-modified} @*queries
new-last-modified (-> ^URL resource
(.openConnection)
(.getLastModified))]
(if (= old-last-modified new-last-modified)
queries
(:queries (reset! *queries {:resource resource
:queries (hugsql/map-of-db-fns resource)
:last-modified new-last-modified})))))
(defn- query! [conn *queries name params]
(let [query-fn (get-in (load-queries *queries) [name :fn])]
(assert query-fn (str "Query not found: " name))
(apply query-fn conn params)))
(defn compile-queries [path]
(let [resource (io/resource path)
_ (assert resource (str "Resource not found: " path))
*queries (atom {:resource resource})]
(fn [conn name & params]
(query! conn *queries name params))))
|
56456
|
;; Copyright © 2015-2019 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.db
(:require [clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[conman.core :as conman]
[hugsql.adapter.clojure-java-jdbc] ; for hugsql.core/get-adapter to not crash on first usage
[hugsql.core :as hugsql]
[mount.core :as mount]
[territory-bro.config :as config]
[territory-bro.json :as json]
[territory-bro.util :refer [getx]])
(:import (clojure.lang IPersistentMap IPersistentVector)
(com.zaxxer.hikari HikariDataSource)
(java.net URL)
(java.sql Date Timestamp PreparedStatement Array)
(org.flywaydb.core Flyway)
(org.postgresql.util PGobject)))
;; PostgreSQL error codes
;; https://www.postgresql.org/docs/11/errcodes-appendix.html
(def psql-serialization-failure "40001")
(def psql-undefined-object "42704")
(def psql-duplicate-object "42710")
(defn connect! [database-url]
(log/info "Connect" database-url)
(conman/connect! {:jdbc-url database-url}))
(defn disconnect! [connection]
(log/info "Disconnect" (if-let [ds (:datasource connection)]
(.getJdbcUrl ^HikariDataSource ds)))
(conman/disconnect! connection))
(mount/defstate database
:start (connect! (getx config/env :database-url))
:stop (disconnect! database))
(defn to-date [^java.util.Date sql-date]
(-> sql-date (.getTime) (java.util.Date.)))
(extend-protocol jdbc/IResultSetReadColumn
Date
(result-set-read-column [v _ _] (to-date v))
Timestamp
(result-set-read-column [v _ _] (to-date v))
Array
(result-set-read-column [v _ _] (vec (.getArray v)))
PGobject
(result-set-read-column [pgobj _metadata _index]
(let [type (.getType pgobj)
value (.getValue pgobj)]
(case type
"json" (json/parse-string value)
"jsonb" (json/parse-string value)
"citext" (str value)
value))))
(extend-type java.util.Date
jdbc/ISQLParameter
(set-parameter [v ^PreparedStatement stmt idx]
(.setTimestamp stmt idx (Timestamp. (.getTime v)))))
(defn to-pg-json [value]
(doto (PGobject.)
(.setType "jsonb")
(.setValue (json/generate-string value))))
(extend-type IPersistentVector
jdbc/ISQLParameter
(set-parameter [v ^PreparedStatement stmt ^long idx]
(let [conn (.getConnection stmt)
meta (.getParameterMetaData stmt)
type-name (.getParameterTypeName meta idx)]
(if-let [elem-type (when (= (first type-name) \_) (apply str (rest type-name)))]
(.setObject stmt idx (.createArrayOf conn elem-type (to-array v)))
(.setObject stmt idx (to-pg-json v))))))
(extend-protocol jdbc/ISQLValue
IPersistentMap
(sql-value [value] (to-pg-json value))
IPersistentVector
(sql-value [value] (to-pg-json value)))
;; new stuff
(defn- ^"[Ljava.lang.String;" strings [& strings]
(into-array String strings))
(defn ^Flyway master-schema [schema]
(-> (Flyway/configure)
(.dataSource (:datasource database))
(.schemas (strings schema))
(.locations (strings "classpath:db/flyway/master"))
(.placeholders {"masterSchema" schema})
(.load)))
(defn ^Flyway tenant-schema [schema master-schema]
(-> (Flyway/configure)
(.dataSource (:datasource database))
(.schemas (strings schema))
(.locations (strings "classpath:db/flyway/tenant"))
(.placeholders {"masterSchema" master-schema})
(.load)))
(defn migrate-master-schema! []
(let [schema (:database-schema config/env)]
(log/info "Migrating master schema:" schema)
(-> (master-schema schema)
(.migrate))))
(defn migrate-tenant-schema! [schema]
(log/info "Migrating tenant schema:" schema)
(-> (tenant-schema schema (:database-schema config/env))
(.migrate)))
(defn get-schemas [conn]
(->> (jdbc/query conn ["select schema_name from information_schema.schemata"])
(map :schema_name)
(doall)))
(defn set-search-path [conn schemas]
(doseq [schema schemas]
(assert (and schema (re-matches #"^[a-zA-Z0-9_]+$" schema))
{:schema schema}))
(jdbc/execute! conn [(str "set search_path to " (str/join "," schemas))]))
(def ^:private public-schema "public") ; contains PostGIS types
(defn use-master-schema [conn]
(set-search-path conn [(:database-schema config/env)
public-schema]))
(defn use-tenant-schema [conn tenant-schema]
(set-search-path conn [(:database-schema config/env)
tenant-schema
public-schema]))
(defmacro with-db [binding & body]
(let [conn (first binding)
options (merge {:isolation :serializable}
(second binding))]
`(jdbc/with-db-transaction [~conn database ~options]
(use-master-schema ~conn)
~@body)))
(defn check-database-version [minimum-version]
(with-db [conn {:read-only? true}]
(let [metadata (-> (jdbc/db-connection conn) .getMetaData)
version (.getDatabaseMajorVersion metadata)]
(assert (>= version minimum-version)
(str "Expected the database to be PostgreSQL " minimum-version " but it was "
(.getDatabaseProductName metadata) " " (.getDatabaseProductVersion metadata))))))
(defn- load-queries [*queries]
;; TODO: implement detecting resource changes to clojure.tools.namespace.repl/refresh
(let [{queries :queries, resource :resource, old-last-modified :last-modified} @*queries
new-last-modified (-> ^URL resource
(.openConnection)
(.getLastModified))]
(if (= old-last-modified new-last-modified)
queries
(:queries (reset! *queries {:resource resource
:queries (hugsql/map-of-db-fns resource)
:last-modified new-last-modified})))))
(defn- query! [conn *queries name params]
(let [query-fn (get-in (load-queries *queries) [name :fn])]
(assert query-fn (str "Query not found: " name))
(apply query-fn conn params)))
(defn compile-queries [path]
(let [resource (io/resource path)
_ (assert resource (str "Resource not found: " path))
*queries (atom {:resource resource})]
(fn [conn name & params]
(query! conn *queries name params))))
| true |
;; Copyright © 2015-2019 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.db
(:require [clojure.java.io :as io]
[clojure.java.jdbc :as jdbc]
[clojure.string :as str]
[clojure.tools.logging :as log]
[conman.core :as conman]
[hugsql.adapter.clojure-java-jdbc] ; for hugsql.core/get-adapter to not crash on first usage
[hugsql.core :as hugsql]
[mount.core :as mount]
[territory-bro.config :as config]
[territory-bro.json :as json]
[territory-bro.util :refer [getx]])
(:import (clojure.lang IPersistentMap IPersistentVector)
(com.zaxxer.hikari HikariDataSource)
(java.net URL)
(java.sql Date Timestamp PreparedStatement Array)
(org.flywaydb.core Flyway)
(org.postgresql.util PGobject)))
;; PostgreSQL error codes
;; https://www.postgresql.org/docs/11/errcodes-appendix.html
(def psql-serialization-failure "40001")
(def psql-undefined-object "42704")
(def psql-duplicate-object "42710")
(defn connect! [database-url]
(log/info "Connect" database-url)
(conman/connect! {:jdbc-url database-url}))
(defn disconnect! [connection]
(log/info "Disconnect" (if-let [ds (:datasource connection)]
(.getJdbcUrl ^HikariDataSource ds)))
(conman/disconnect! connection))
(mount/defstate database
:start (connect! (getx config/env :database-url))
:stop (disconnect! database))
(defn to-date [^java.util.Date sql-date]
(-> sql-date (.getTime) (java.util.Date.)))
(extend-protocol jdbc/IResultSetReadColumn
Date
(result-set-read-column [v _ _] (to-date v))
Timestamp
(result-set-read-column [v _ _] (to-date v))
Array
(result-set-read-column [v _ _] (vec (.getArray v)))
PGobject
(result-set-read-column [pgobj _metadata _index]
(let [type (.getType pgobj)
value (.getValue pgobj)]
(case type
"json" (json/parse-string value)
"jsonb" (json/parse-string value)
"citext" (str value)
value))))
(extend-type java.util.Date
jdbc/ISQLParameter
(set-parameter [v ^PreparedStatement stmt idx]
(.setTimestamp stmt idx (Timestamp. (.getTime v)))))
(defn to-pg-json [value]
(doto (PGobject.)
(.setType "jsonb")
(.setValue (json/generate-string value))))
(extend-type IPersistentVector
jdbc/ISQLParameter
(set-parameter [v ^PreparedStatement stmt ^long idx]
(let [conn (.getConnection stmt)
meta (.getParameterMetaData stmt)
type-name (.getParameterTypeName meta idx)]
(if-let [elem-type (when (= (first type-name) \_) (apply str (rest type-name)))]
(.setObject stmt idx (.createArrayOf conn elem-type (to-array v)))
(.setObject stmt idx (to-pg-json v))))))
(extend-protocol jdbc/ISQLValue
IPersistentMap
(sql-value [value] (to-pg-json value))
IPersistentVector
(sql-value [value] (to-pg-json value)))
;; new stuff
(defn- ^"[Ljava.lang.String;" strings [& strings]
(into-array String strings))
(defn ^Flyway master-schema [schema]
(-> (Flyway/configure)
(.dataSource (:datasource database))
(.schemas (strings schema))
(.locations (strings "classpath:db/flyway/master"))
(.placeholders {"masterSchema" schema})
(.load)))
(defn ^Flyway tenant-schema [schema master-schema]
(-> (Flyway/configure)
(.dataSource (:datasource database))
(.schemas (strings schema))
(.locations (strings "classpath:db/flyway/tenant"))
(.placeholders {"masterSchema" master-schema})
(.load)))
(defn migrate-master-schema! []
(let [schema (:database-schema config/env)]
(log/info "Migrating master schema:" schema)
(-> (master-schema schema)
(.migrate))))
(defn migrate-tenant-schema! [schema]
(log/info "Migrating tenant schema:" schema)
(-> (tenant-schema schema (:database-schema config/env))
(.migrate)))
(defn get-schemas [conn]
(->> (jdbc/query conn ["select schema_name from information_schema.schemata"])
(map :schema_name)
(doall)))
(defn set-search-path [conn schemas]
(doseq [schema schemas]
(assert (and schema (re-matches #"^[a-zA-Z0-9_]+$" schema))
{:schema schema}))
(jdbc/execute! conn [(str "set search_path to " (str/join "," schemas))]))
(def ^:private public-schema "public") ; contains PostGIS types
(defn use-master-schema [conn]
(set-search-path conn [(:database-schema config/env)
public-schema]))
(defn use-tenant-schema [conn tenant-schema]
(set-search-path conn [(:database-schema config/env)
tenant-schema
public-schema]))
(defmacro with-db [binding & body]
(let [conn (first binding)
options (merge {:isolation :serializable}
(second binding))]
`(jdbc/with-db-transaction [~conn database ~options]
(use-master-schema ~conn)
~@body)))
(defn check-database-version [minimum-version]
(with-db [conn {:read-only? true}]
(let [metadata (-> (jdbc/db-connection conn) .getMetaData)
version (.getDatabaseMajorVersion metadata)]
(assert (>= version minimum-version)
(str "Expected the database to be PostgreSQL " minimum-version " but it was "
(.getDatabaseProductName metadata) " " (.getDatabaseProductVersion metadata))))))
(defn- load-queries [*queries]
;; TODO: implement detecting resource changes to clojure.tools.namespace.repl/refresh
(let [{queries :queries, resource :resource, old-last-modified :last-modified} @*queries
new-last-modified (-> ^URL resource
(.openConnection)
(.getLastModified))]
(if (= old-last-modified new-last-modified)
queries
(:queries (reset! *queries {:resource resource
:queries (hugsql/map-of-db-fns resource)
:last-modified new-last-modified})))))
(defn- query! [conn *queries name params]
(let [query-fn (get-in (load-queries *queries) [name :fn])]
(assert query-fn (str "Query not found: " name))
(apply query-fn conn params)))
(defn compile-queries [path]
(let [resource (io/resource path)
_ (assert resource (str "Resource not found: " path))
*queries (atom {:resource resource})]
(fn [conn name & params]
(query! conn *queries name params))))
|
[
{
"context": " :nickname username,\n :password (md5 password),\n :avatar nil})))))\n",
"end": 1543,
"score": 0.9983317255973816,
"start": 1531,
"tag": "PASSWORD",
"value": "md5 password"
}
] |
src/app/updater/user.cljs
|
jimengio/locales-editor
| 1 |
(ns app.updater.user (:require [app.util :refer [find-first]] ["md5" :as md5]))
(defn log-in [db op-data sid op-id op-time]
(let [[username password] op-data
maybe-user (find-first
(fn [user] (and (= username (:name user))))
(vals (:users db)))]
(update-in
db
[:sessions sid]
(fn [session]
(if (some? maybe-user)
(if (= (md5 password) (:password maybe-user))
(assoc session :user-id (:id maybe-user))
(update
session
:messages
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "Wrong password for " username)}))))
(update
session
:messages
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "No user named: " username)}))))))))
(defn log-out [db op-data sid op-id op-time] (assoc-in db [:sessions sid :user-id] nil))
(defn sign-up [db op-data sid op-id op-time]
(let [[username password] op-data
maybe-user (find-first (fn [user] (= username (:name user))) (vals (:users db)))]
(if (some? maybe-user)
(update-in
db
[:sessions sid :messages]
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "Name is token: " username)})))
(-> db
(assoc-in [:sessions sid :user-id] op-id)
(assoc-in
[:users op-id]
{:id op-id,
:name username,
:nickname username,
:password (md5 password),
:avatar nil})))))
|
8901
|
(ns app.updater.user (:require [app.util :refer [find-first]] ["md5" :as md5]))
(defn log-in [db op-data sid op-id op-time]
(let [[username password] op-data
maybe-user (find-first
(fn [user] (and (= username (:name user))))
(vals (:users db)))]
(update-in
db
[:sessions sid]
(fn [session]
(if (some? maybe-user)
(if (= (md5 password) (:password maybe-user))
(assoc session :user-id (:id maybe-user))
(update
session
:messages
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "Wrong password for " username)}))))
(update
session
:messages
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "No user named: " username)}))))))))
(defn log-out [db op-data sid op-id op-time] (assoc-in db [:sessions sid :user-id] nil))
(defn sign-up [db op-data sid op-id op-time]
(let [[username password] op-data
maybe-user (find-first (fn [user] (= username (:name user))) (vals (:users db)))]
(if (some? maybe-user)
(update-in
db
[:sessions sid :messages]
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "Name is token: " username)})))
(-> db
(assoc-in [:sessions sid :user-id] op-id)
(assoc-in
[:users op-id]
{:id op-id,
:name username,
:nickname username,
:password (<PASSWORD>),
:avatar nil})))))
| true |
(ns app.updater.user (:require [app.util :refer [find-first]] ["md5" :as md5]))
(defn log-in [db op-data sid op-id op-time]
(let [[username password] op-data
maybe-user (find-first
(fn [user] (and (= username (:name user))))
(vals (:users db)))]
(update-in
db
[:sessions sid]
(fn [session]
(if (some? maybe-user)
(if (= (md5 password) (:password maybe-user))
(assoc session :user-id (:id maybe-user))
(update
session
:messages
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "Wrong password for " username)}))))
(update
session
:messages
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "No user named: " username)}))))))))
(defn log-out [db op-data sid op-id op-time] (assoc-in db [:sessions sid :user-id] nil))
(defn sign-up [db op-data sid op-id op-time]
(let [[username password] op-data
maybe-user (find-first (fn [user] (= username (:name user))) (vals (:users db)))]
(if (some? maybe-user)
(update-in
db
[:sessions sid :messages]
(fn [messages]
(assoc messages op-id {:id op-id, :text (str "Name is token: " username)})))
(-> db
(assoc-in [:sessions sid :user-id] op-id)
(assoc-in
[:users op-id]
{:id op-id,
:name username,
:nickname username,
:password (PI:PASSWORD:<PASSWORD>END_PI),
:avatar nil})))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998056888580322,
"start": 96,
"tag": "NAME",
"value": "Ragnar Svensson"
},
{
"context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ",
"end": 129,
"score": 0.9998193383216858,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] |
editor/src/clj/editor/gui_clipping.clj
|
cmarincia/defold
| 0 |
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gui-clipping
(:require [dynamo.graph :as g]
[clojure.pprint :refer [cl-format]])
(:import [com.jogamp.opengl GL GL2]
[clojure.lang ExceptionInfo]))
;;
;; Clipping
;;
;; Clipping uses the stencil buffer. Similar to the depth buffer, the
;; stencil buffer is used to determine whether or not to draw by
;; comparing a value from the buffer with a value from what you're
;; drawing. For the depth buffer we're roughly comparing the z component
;; of what you're drawing with the value in the depth buffer. If the z
;; value is < (or > depending on axis direction?) we draw, and update the
;; depth buffer with the new z.
;;
;; For the stencil buffer the api is slightly different. The functions we
;; use are:
;;
;; * glStencilOp sfail dpfail dppass
;; * glStencilFunc func ref mask
;; * glStencilMask stencil-mask
;; * glEnable/glDisable with GL_STENCIL_TEST
;; * glClear with GL_STENCIL_BUFFER_BIT
;;
;; When the stencil buffer is enabled, the following test is performed
;; before the depth test:
;;
;; (ref & mask) func (<value from stencil buffer> & mask)
;;
;; If this test fails, we update the stencil buffer according to sfail.
;; If it succeeds and the depth test fails, we update according to dpfail.
;; If both tests pass, we update according to dppass and draw.
;;
;; The stencil buffer can be updated by incrementing or decrementing
;; the value, setting it to zero, inverting the bits, keeping the
;; original value or replacing it with ref. Only the bits masked by
;; stencil-mask are updated.
;;
;; The parameters we use are:
;;
;; * glStencilOp GL_KEEP GL_REPLACE GL_REPLACE
;; The stencil buffer is updated whenever the stencil test
;; succeeds. If the test fails, we keep the old value.
;;
;; * glStencilFunc GL_EQUAL ref mask
;; With ref and mask set depending on where we are in the gui scene.
;;
;; * glStencilMask 0xff or 0
;; Depending on if we're drawing a clipper or a normal node.
;;
;; So for us, the test is:
;;
;; (ref & mask) == (<value from stencil buffer> & mask)
;;
;; And since we replace the value on success, the value written will
;; effectively be:
;;
;; (<old-stencil-value> & ~stencil-mask) | (ref & stencil-mask)
;;
;; But since we always set stencil-mask to 0xff or 0, we either leave
;; the bits as-is or replace it entirely.
;;
;; Note that ref is used both in the test and for setting the new
;; value.
;;
;; In Defold we assume the stencil buffer depth is 8 bits, so ref and
;; mask are 8 bits. We support inverted- and non-inverted clippers,
;; and clippers can be nested. Think of the clippers in a scene as
;; nested scopes. All nodes within a scope are drawn with a ref and
;; mask that identifies the scope in order to clip it properly. One
;; pseudo-scope covers the whole scene and any node drawn in that
;; scope (not under an actual clipper) is drawn without clipping
;; enabled. To identify nested non-inverted clipper scopes we split
;; the 8 bits of the ref value into groups. The value of each group is
;; roughly the steps in a path you take along the clipper hierarchy to
;; reach a particular non-inverted clipper scope. The nodes drawn
;; within that scope use as ref all the bits from the groups. The mask
;; is simply enough 1's to cover the group bits.
;;
;; In the example below, the clipper will be drawn using ref and mask set
;; accordingly, and any (non-clipper) child nodes with child ref and
;; child mask.
;; clipper type ref mask child ref child mask
;; - scene
;; - A non-inverted 00000001 00000000 00000001 00000011
;; - B non-inverted 00000101 00000011 00000101 00001111
;; - C non-inverted 00001001 00000011 00001001 00001111
;; - D non-inverted 00011001 00001111 00011001 00011111
;; - E non-inverted 00111001 00011111 00111001 01111111
;; - F non-inverted 01011001 00011111 01011001 01111111
;; - G non-inverted 00001101 00000011 00001101 00001111
;; - H non-inverted 00000010 00000000 00000010 00000011
;;
;; In the scene scope, we have the non-inverted clippers A and H. Since
;; these are top level clippers we always want to draw them, so the mask
;; is 0. In order to draw their child nodes properly we need to be able
;; to distinguish the two scopes, so they each get assigned a unique ref
;; value within this scope: 01 and 10. We cannot use the value 0 when
;; identifying a scope, because that value is also used used "outside"
;; the clipper. So: 00 is off limits, 01 and 10 are taken. We have three
;; values and must use two bits for our first bit group. The child mask
;; is unsurprisingly 00000011.
;;
;; Looking below A we have the non-inverted clippers B, C and G. The refs
;; of each have 01 in the two lowest bits, and we use the mask 11 when
;; drawing to confine them to A. By the same reasoning as earlier we need
;; two more bits to distinguish their scopes.
;;
;; Looking at C, there is only one non-inverted clipper D in scope so
;; this time we only need one bit. Finally below D we need two bits.
;;
;; Effectively the ref bits are used as follows:
;;
;; Bits: 7 6 5 4 3 2 1 0
;; Meaning: [not used] [E or F] [D] [B, C or G] [A or H]
;;
;; If in this example there had been more non-inverted clippers under H,
;; the bit patterns in bit 7->2 could have been reused. There would be no
;; risk of confusing the scopes since bits 0 and 1 (A or H) would differ.
;;
;; Notice that the mask gets filled as we go deeper in the clipper
;; hierarchy.
;;
;; Inverted clippers doesn't fit the bit group scheme. We want to draw
;; the clipper using a ref that identifies the clipper. But when drawing
;; the nodes in its scope, we want to *not* draw where the inverted
;; clipper is drawn. We must also still respect the scopes of clippers
;; higher up in the hierarchy.
;;
;; It's like we want the stencil test for nodes in scope to check:
;; "We are drawing in the parent of the inverted clipper" AND
;; "We are not drawing in the inverted clipper"
;;
;; (inverted-clipper-parent-ref & inverted-clipper-parent-child-mask) ==
;; (<value from stencil-buffer> & inverted-clipper-parent-child-mask)
;; AND
;; inverted-clipper-bit-value != (<value from stencil buffer> & inverted-clipper-bit-mask)
;;
;; We can't do this literally with the stencil functions, but we can
;; express it differently:
;;
;; (inverted-clipper-parent-ref & inverted-clipper-parent-child-mask) ==
;; (<value from stencil-buffer> & inverted-clipper-parent-child-mask)
;; AND
;; 0 == (<value from stencil buffer> & inverted-clipper-bit-mask)
;;
;; Then we do the two comparisons simultaneously:
;;
;; ((0 | inverted-clipper-parent-ref) & (inverted-clipper-bit-mask | inverted-clipper-parent-child-mask)) ==
;; (<value from stencil-buffer> & (inverted-clipper-bit-mask | inverted-clipper-parent-child-mask))
;;
;; We allocate the non-inverted group bits from lowest to highest. Then
;; for each inverted clipper within a non-inverted clipper scope (or the
;; top level pseudo scope), we allocate and set 1 bit from highest ->
;; lowest. The nodes in scope of an inverted clipper then includes that
;; clippers bit in its mask, but uses a ref value with the bit set to 0 -
;; effectively the child ref value is unchanged.
;;
;; An example:
;;
;; clipper type ref mask child ref child mask
;; - scene
;; - A non-inverted 00000001 00000000 00000001 00000011
;; - B non-inverted 00000101 00000011 00000101 00000111
;; - C non-inverted 00000010 00000000 00000010 00000011
;; - D inverted 10000010 00000011 00000010 10000011
;; - E inverted 01000010 10000011 00000010 11000011
;; - F inverted 00100010 00000011 00000010 00100011
;; - G non-inverted 00000110 00100011 00000110 00100111
;; - H inverted 00010110 00100111 00000110 00110111
;; - I inverted 10000000 00000000 00000000 10000000
;; - J non-inverted 00000011 10000000 00000011 10000011
;;
;; In the top level scene scope we have the obvious non-inverted clippers
;; A, C but now we also count J. The reason we include J in the scene
;; scope even though I lies between is that I is an inverted node. We
;; cannot use the bit we assign to I for distinguishing between A, C and
;; J. So, we have the off limits 00 + 01, 10, 11 for A, C and J requiring
;; 2 bits for the top level group.
;;
;; We assign bit 7 for I. We draw J with 0 in I's bit but with a mask
;; covering it. This makes sure we don't draw J on I. Notice that the
;; child mask of J must include I's bit.
;;
;; In the scope of C we have one non-inverted clipper G, requiring 1 bit,
;; and three inverted clippers D, E and F. Since we cannot use the bit
;; assigned to clippers to distinguish scopes, they get assigned one bit
;; each. We can not for instance use bit 6 for both E and F: when drawing
;; G we would be unable to draw where E was drawn.
;;
;; The implementation is mostly concerned with counting different types
;; of clippers in the scopes, assigning ref and mask values, and
;; transfering these to the scene nodes so the clipping is applied when
;; drawing.
;;
;; Visible Clippers
;;
;; Clippers can be marked as visible, meaning we draw them with the
;; color or texture assigned.
;;
;; We implement this by injecting a new scene node drawing the visible
;; part of the clipper. For inverted clippers, this representation must
;; still be drawn inside the clipper as opposed to the other children
;; being drawn only outside.
;;
;; Layers and rendering order
;;
;; For clipping to work properly, the clipper must be drawn before its
;; children. Normally we can change the draw order of nodes (starting out
;; as depth first, in order traversal) by assigning layers to nodes. But
;; doing that for clipper child nodes to draw it before the clipper would
;; be pointless. Instead the meaning of layers within clippers is changed
;; to only affect the relative draw order of the nodes in its scope. The
;; layer set on the clipper node itself does not affect its draw order -
;; but it *is* inherited by any child node with no layer set (like
;; outside clippers) and especially by the node representing a visible
;; clipper. The clipper is effectively drawn in the "null" layer.
;;
;; Bit overflow
;;
;; The 8 bits available creates some restrictions on how deep we can
;; nest clippers and how many clipper siblings we can have within the
;; scopes. If too many bits are needed the engine will start printing
;; warnings and clipping will simply break. In the editor we try to
;; recover from this by clearing the stencil buffer between rendering
;; each "top level" clipper in the scene. This helps if we have too
;; many siblings on the top level, but we can't recover from an
;; individual top level clipper tree requiring too many bits. It's
;; debatable whether we should even try to recover since the engine
;; can't.
;;
(set! *warn-on-reflection* true)
(def ^:private stencil-bits 8)
(defn- visible-clipper? [scene]
(get-in scene [:renderable :user-data :clipping :visible]))
(defn- clipper-scene? [scene]
(contains? (-> scene :renderable :user-data) :clipping))
(defn- clipper-trees
([scene]
(clipper-trees scene []))
([scene path]
(let [child-clippers (into []
(comp (map-indexed (fn [i e] (clipper-trees e (conj path i))))
cat)
(:children scene))]
(if-let [clipping (get-in scene [:renderable :user-data :clipping])]
[{:node-id (:node-id scene) ; for error values
;; add for debugging
;; :id (g/node-value (:node-id scene) :id)
:clipping clipping
:path path
:children child-clippers}]
child-clippers))))
(defn- wrap-trees [clipper-trees]
{:children clipper-trees})
(defn- inverted? [clipper]
(= true (get-in clipper [:clipping :inverted])))
(defn- non-inverted? [clipper]
(= false (get-in clipper [:clipping :inverted])))
(defn- wrapper? [clipper]
(and (not (inverted? clipper))
(not (non-inverted? clipper))))
(defn- count-inverted-clipper-scope [clipper-tree]
(assert (inverted? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
;; Number of paths down from this clipper that lead to a
;; non-inverted clipper (via only inverted clippers!).
;; We use this to determine how many bits to allocate for
;; distinguishinging successor non-inverted clippers in the
;; ancestor non-inverted clipper.
:successor-non-inverted successor-non-inverted
;; Number of inverted clippers along the paths down to a
;; non-inverted clipper (or bottom) + this inverted clipper.
;; We use this to determine how many individual bits to
;; allocate for inverted clippers between the ancestor
;; non-inverted clipper and successor non-inverted
;; clippers (or bottom).
:inverted-since-non-inverted-or-bottom (inc inverted-since-non-inverted-or-bottom)
;; On every non-inverted clipper we accumulate a required
;; bit count from the required bit counts of successor
;; non-inverted scopes, the number of successor
;; non-inverted scopes, and the number of inverted
;; scopes passed between.
:max-successor-non-inverted-allocated-bits max-successor-non-inverted-allocated-bits)))
(defn- log2 [n] (/ (Math/log n) (Math/log 2)))
(defn- pow2 [n] (bit-shift-left 1 n))
(defn- n->bits [n] (int (+ 1 (log2 n))))
(defn- bits->mask [bits] (dec (pow2 bits)))
(defn- count-non-inverted-clipper-scope [clipper-tree]
(assert (non-inverted? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
non-inverted-ref-bits (if (= successor-non-inverted 0) 0 (n->bits successor-non-inverted))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
;; Contributes 1 successor to the ancestor non-inverted
;; scope.
:successor-non-inverted 1
;; Accumulated bits needed to distinguish successor
;; non-inverted clipper scopes. Used during assignment of
;; ref-val and mask.
:non-inverted-ref-bits non-inverted-ref-bits
;; see count-inverted-clipper-scope
:max-successor-non-inverted-allocated-bits (+ non-inverted-ref-bits
inverted-since-non-inverted-or-bottom
max-successor-non-inverted-allocated-bits))))
(defn- count-wrapper-scope [clipper-tree]
(assert (wrapper? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
non-inverted-ref-bits (if (= successor-non-inverted 0) 0 (n->bits successor-non-inverted))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
:non-inverted-ref-bits non-inverted-ref-bits
:allocated-bits (+ non-inverted-ref-bits inverted-since-non-inverted-or-bottom max-successor-non-inverted-allocated-bits))))
(defn- count-clipper-scopes [clipper-tree]
(let [clipper-tree' (update clipper-tree :children #(map count-clipper-scopes %))]
(cond
(inverted? clipper-tree')
(count-inverted-clipper-scope clipper-tree')
(non-inverted? clipper-tree')
(count-non-inverted-clipper-scope clipper-tree')
true
(count-wrapper-scope clipper-tree'))))
(declare assign-clipper-bits)
(defn- assign-inverted-clipper-bits [clipper-tree context]
(let [inverted-clipper-bit-mask (bit-shift-left 1 (- (dec stencil-bits) (:inverted-clipper-bits-used context)))
ref-val (bit-or (:ref-val context) inverted-clipper-bit-mask)
mask (:mask context)
child-ref-val (:ref-val context) ; bit for this clipper is already 0 in context ref
child-mask (bit-or mask inverted-clipper-bit-mask)
child-context (-> context
(update :inverted-clipper-bits-used inc)
(assoc :ref-val child-ref-val
:mask child-mask))
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))
clipper-tree' (assoc clipper-tree
:ref-val ref-val
:mask mask
:child-ref-val child-ref-val
:child-mask child-mask
:children children')
context' (assoc context
:non-inverted-ref-val-counter (:non-inverted-ref-val-counter child-context')
:inverted-clipper-bits-used (:inverted-clipper-bits-used child-context'))]
[clipper-tree' context']))
(defn- assign-non-inverted-clipper-bits [clipper-tree context]
(let [ref-val (bit-or (:ref-val context) (bit-shift-left (:non-inverted-ref-val-counter context) (:non-inverted-ref-bits-used context)))
mask (:mask context)
child-ref-val ref-val
child-mask (bit-or mask (bit-shift-left (bits->mask (:non-inverted-ref-bits context)) (:non-inverted-ref-bits-used context)))
child-context {:ref-val child-ref-val
:mask child-mask
:inverted-clipper-bits-used (:inverted-clipper-bits-used context)
:non-inverted-ref-val-counter 1
:non-inverted-ref-bits (:non-inverted-ref-bits clipper-tree)
:non-inverted-ref-bits-used (+ (:non-inverted-ref-bits-used context) (:non-inverted-ref-bits context))}
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))
clipper-tree' (assoc clipper-tree
:ref-val ref-val
:mask mask
:child-ref-val child-ref-val
:child-mask child-mask
:children children')
context' (update context :non-inverted-ref-val-counter inc)]
[clipper-tree' context']))
(defn- assign-wrapper-clipper-bits [clipper-tree]
(assert (wrapper? clipper-tree))
(let [allocated (:allocated-bits clipper-tree)]
(if (<= allocated stencil-bits)
(let [child-context {:ref-val 0
:mask 0
:inverted-clipper-bits-used 0
:non-inverted-ref-val-counter 1
:non-inverted-ref-bits (:non-inverted-ref-bits clipper-tree)
:non-inverted-ref-bits-used 0}
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))]
(assoc clipper-tree :children children'))
(let [wrapped-child-clipper-trees (map (comp count-wrapper-scope wrap-trees vector) (:children clipper-tree))]
;; If the clipper-tree (wrapper) requires more bits than
;; available in the stencil buffer, we try to recover
;; by inserting a clear betweeen each top level clipper.
;; This is only possible if each of the top level clippers
;; would fit on its own. Otherwise, we bail with an error.
(if-let [overflowing-child-clipper-tree (first (filter #(> (:allocated-bits %) stencil-bits) wrapped-child-clipper-trees))]
(g/error-fatal "bit overflow" {:type :bit-overflow :source-id (-> overflowing-child-clipper-tree :children first :node-id)})
;; Try recovering from the overflow by adding clear
;; flags. Note that the engine does not do this, so you
;; might be misled into building a gui in the editor that
;; will not work during runtime. Apparently the engine only
;; inserts clears between rendering different gui scenes.
(let [children' (into []
(comp
(mapcat (fn [wrapped-child-clipper-tree]
;; Each wrapped-child-clipper-tree has one child, and assign-wrapper-clipper-bits
;; leaves the tree structure unchanged.
(let [{:keys [children]} (assign-wrapper-clipper-bits wrapped-child-clipper-tree)]
(assert (= 1 (count children)))
children)))
(map #(assoc % :clear true)))
wrapped-child-clipper-trees)]
(assoc clipper-tree :children children')))))))
(defn- assign-clipper-bits
([clipper-tree]
(assign-wrapper-clipper-bits clipper-tree))
([clipper-tree context]
(cond
(inverted? clipper-tree)
(assign-inverted-clipper-bits clipper-tree context)
(non-inverted? clipper-tree)
(assign-non-inverted-clipper-bits clipper-tree context))))
(defn- make-visible-clipper-scene [scene]
;; The visible clipper scene for an inverted clipper needs a
;; different mask & ref than other nodes in the clippers scope to
;; make it draw *inside* rather than outside the clipper. For this
;; we tag it with :visible-clipper-scene?
(-> scene
(update-in [:renderable :user-data] dissoc :clipping) ; don't want to treat this node as a clipper
(assoc-in [:renderable :user-data :visible-clipper-scene?] true) ; tag it
(dissoc :children :transform :aabb)))
(defn- visible-clipper-scene? [scene]
(get-in scene [:renderable :user-data :visible-clipper-scene?]))
(defn- inject-visible-clipper-scenes [scene]
(cond-> (update scene :children #(map inject-visible-clipper-scenes %))
(visible-clipper? scene)
(update :children #(into [(make-visible-clipper-scene scene)] %))))
(defn- remove-clipper-renderable-tags
"We remove the renderable tags for all clipper scenes to make sure
the clipping state is drawn. Any visible clipper representation
retains the tags and can be hidden."
[scene]
(cond-> (update scene :children #(map remove-clipper-renderable-tags %))
(clipper-scene? scene)
(update-in [:renderable] dissoc :tags)))
(defn- clipper-tree->trie [clipper-tree]
(reduce (fn [trie clipper-tree]
(assoc-in trie (:path clipper-tree) (select-keys clipper-tree [:ref-val :mask :child-ref-val :child-mask :clear])))
(select-keys clipper-tree [:ref-val :mask :child-ref-val :child-mask :clear])
(rest (tree-seq :children :children clipper-tree))))
(defn- descendant-clipping-state [last-clipper-trie visible-clipper-scene?]
;; If this is the injected scene for showing the clipper contents, it should be drawn using the same
;; ref and mask as the clipper itself.
{:ref-val (if visible-clipper-scene? (:ref-val last-clipper-trie) (:child-ref-val last-clipper-trie))
:mask (if visible-clipper-scene? (:mask last-clipper-trie) (:child-mask last-clipper-trie))
:write-mask 0
:color-mask [true true true true]})
(defn- clipper-clipping-state [clipper-trie]
(cond-> {:ref-val (:ref-val clipper-trie)
:mask (:mask clipper-trie)
:write-mask 0xff
:color-mask [false false false false]}
(:clear clipper-trie)
(assoc :clear true)))
(defn- clipper-trie? [trie]
(contains? trie :ref-val))
(defn- lookup-clipping-state [trie last-clipper-trie step visible-clipper-scene?]
(if-let [next-trie (get trie step)]
(if (clipper-trie? next-trie)
;; trie represents clipper -> this is a clipper node
[next-trie next-trie (clipper-clipping-state next-trie)]
;; trie does not represent a clipper -> this is a descendant node of some earlier clipper
[next-trie last-clipper-trie (when last-clipper-trie (descendant-clipping-state last-clipper-trie visible-clipper-scene?))])
;; stepping outside the tree of clippers -> this is a descendant node of some earlier clipper
[nil last-clipper-trie (when last-clipper-trie (descendant-clipping-state last-clipper-trie visible-clipper-scene?))]))
(defn- add-clipping-state [scene clipping-state]
(-> scene
(assoc-in [:renderable :user-data :clipping-state] clipping-state)
(assoc-in [:renderable :batch-key :clipping-state] clipping-state)))
(defn- apply-clippers [clipper-tree scene]
(let [trie (clipper-tree->trie clipper-tree)]
(letfn [(apply-clipping [scene [trie last-clipper-trie clipping-state]]
(let [new-children (map-indexed (fn [index child]
(let [child-lookup-result (lookup-clipping-state trie last-clipper-trie index (visible-clipper-scene? child))]
(apply-clipping child child-lookup-result)))
(:children scene))]
(cond-> (assoc scene :children new-children)
(contains? scene :renderable)
(add-clipping-state clipping-state)
:because-gui-clipping-tests-need-it
(assoc-in [:renderable :user-data :clipping-child-state]
(nth (lookup-clipping-state trie last-clipper-trie :fake-child-step false) 2)))))]
(assert (not (clipper-trie? trie)))
(apply-clipping scene [trie nil nil]))))
#_(defn- bitstring
([n] (bitstring n stencil-bits))
([n total-bits] (cl-format nil (str "~" total-bits ",'0',B") n)))
#_(defn- print-clipper-tree
([clipper-tree] (print-clipper-tree clipper-tree ""))
([clipper-tree prefix]
(let [{:keys [id node-id clear max-successor-non-inverted-allocated-bits path ref-val mask child-ref-val child-mask]} clipper-tree]
(println prefix :id id
(cond (inverted? clipper-tree) :inverted
(non-inverted? clipper-tree) :non-inverted
:else :not-a-clipper)
:node-id node-id
:clear clear
:bits-allocated max-successor-non-inverted-allocated-bits
:path path
:ref-val (when ref-val (bitstring ref-val))
:mask (when mask (bitstring mask))
:child-ref-val (when child-ref-val (bitstring child-ref-val))
:child-mask (when child-mask (bitstring child-mask))))
(run! #(print-clipper-tree % (str prefix " ")) (:children clipper-tree))))
(defn setup-states [scene]
(let [scene-with-visible-clippers (-> scene
inject-visible-clipper-scenes
remove-clipper-renderable-tags)
clipper-tree (-> scene-with-visible-clippers
clipper-trees
wrap-trees
count-clipper-scopes
assign-clipper-bits)]
(cond
(g/error? clipper-tree)
clipper-tree
true
(apply-clippers clipper-tree scene-with-visible-clippers))))
(defn scene-key [scene]
[(:node-id scene) (get-in scene [:renderable :user-data :clipping-state])])
(defn- trickle-down-default-layers
"Perform inheritance of parent node layer to child nodes with no
layer assigned, and strip layer from clipper nodes."
([scene]
(trickle-down-default-layers nil scene))
([default-layer scene]
(let [layer (get-in scene [:renderable :layer-index])]
(if (and layer (>= layer 0))
(cond-> (update scene :children #(mapv (partial trickle-down-default-layers layer) %))
(clipper-scene? scene)
(assoc-in [:renderable :layer-index] nil)) ; clipper nodes render in the null layer (first)
(cond-> (update scene :children #(mapv (partial trickle-down-default-layers default-layer) %))
(not (clipper-scene? scene))
(assoc-in [:renderable :layer-index] default-layer))))))
(defn- scope-scenes
"Collect scenes in depth first pre order (parent visited before children), stopping at clipper nodes."
[scene]
(loop [children-stack (list (:children scene))
scenes []]
(cond
(not (seq children-stack))
scenes
(not (seq (first children-stack)))
(recur (rest children-stack) scenes)
true
(let [child (ffirst children-stack)
next-children (if (clipper-scene? child) [] (:children child))]
(recur (cons next-children (cons (rest (first children-stack)) (rest children-stack)))
(conj scenes child))))))
(defn- render-keys
([scene]
(render-keys {} (scope-scenes scene)))
([assignment unsorted-scenes]
(let [scenes (sort-by #(get-in % [:renderable :layer-index]) unsorted-scenes)]
(reduce (fn [assignment scene]
(if (clipper-scene? scene)
(-> assignment
(assoc (scene-key scene) (count assignment))
(render-keys (scope-scenes scene)))
(assoc assignment (scene-key scene) (count assignment))))
assignment
scenes))))
(defn scene->render-keys [scene]
(-> scene
trickle-down-default-layers
render-keys))
(defn setup-gl [^GL2 gl state]
(when state
(.glEnable gl GL/GL_STENCIL_TEST)
(.glStencilOp gl GL/GL_KEEP GL/GL_REPLACE GL/GL_REPLACE)
(.glStencilFunc gl GL2/GL_EQUAL (:ref-val state) (:mask state))
(.glStencilMask gl (:write-mask state))
(when (:clear state)
(.glClear gl GL/GL_STENCIL_BUFFER_BIT))
(let [[c0 c1 c2 c3] (:color-mask state)]
(.glColorMask gl c0 c1 c2 c3))))
(defn restore-gl [^GL2 gl state]
(when state
(.glDisable gl GL/GL_STENCIL_TEST)
(.glColorMask gl true true true true)))
|
17657
|
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 <NAME>, <NAME>
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gui-clipping
(:require [dynamo.graph :as g]
[clojure.pprint :refer [cl-format]])
(:import [com.jogamp.opengl GL GL2]
[clojure.lang ExceptionInfo]))
;;
;; Clipping
;;
;; Clipping uses the stencil buffer. Similar to the depth buffer, the
;; stencil buffer is used to determine whether or not to draw by
;; comparing a value from the buffer with a value from what you're
;; drawing. For the depth buffer we're roughly comparing the z component
;; of what you're drawing with the value in the depth buffer. If the z
;; value is < (or > depending on axis direction?) we draw, and update the
;; depth buffer with the new z.
;;
;; For the stencil buffer the api is slightly different. The functions we
;; use are:
;;
;; * glStencilOp sfail dpfail dppass
;; * glStencilFunc func ref mask
;; * glStencilMask stencil-mask
;; * glEnable/glDisable with GL_STENCIL_TEST
;; * glClear with GL_STENCIL_BUFFER_BIT
;;
;; When the stencil buffer is enabled, the following test is performed
;; before the depth test:
;;
;; (ref & mask) func (<value from stencil buffer> & mask)
;;
;; If this test fails, we update the stencil buffer according to sfail.
;; If it succeeds and the depth test fails, we update according to dpfail.
;; If both tests pass, we update according to dppass and draw.
;;
;; The stencil buffer can be updated by incrementing or decrementing
;; the value, setting it to zero, inverting the bits, keeping the
;; original value or replacing it with ref. Only the bits masked by
;; stencil-mask are updated.
;;
;; The parameters we use are:
;;
;; * glStencilOp GL_KEEP GL_REPLACE GL_REPLACE
;; The stencil buffer is updated whenever the stencil test
;; succeeds. If the test fails, we keep the old value.
;;
;; * glStencilFunc GL_EQUAL ref mask
;; With ref and mask set depending on where we are in the gui scene.
;;
;; * glStencilMask 0xff or 0
;; Depending on if we're drawing a clipper or a normal node.
;;
;; So for us, the test is:
;;
;; (ref & mask) == (<value from stencil buffer> & mask)
;;
;; And since we replace the value on success, the value written will
;; effectively be:
;;
;; (<old-stencil-value> & ~stencil-mask) | (ref & stencil-mask)
;;
;; But since we always set stencil-mask to 0xff or 0, we either leave
;; the bits as-is or replace it entirely.
;;
;; Note that ref is used both in the test and for setting the new
;; value.
;;
;; In Defold we assume the stencil buffer depth is 8 bits, so ref and
;; mask are 8 bits. We support inverted- and non-inverted clippers,
;; and clippers can be nested. Think of the clippers in a scene as
;; nested scopes. All nodes within a scope are drawn with a ref and
;; mask that identifies the scope in order to clip it properly. One
;; pseudo-scope covers the whole scene and any node drawn in that
;; scope (not under an actual clipper) is drawn without clipping
;; enabled. To identify nested non-inverted clipper scopes we split
;; the 8 bits of the ref value into groups. The value of each group is
;; roughly the steps in a path you take along the clipper hierarchy to
;; reach a particular non-inverted clipper scope. The nodes drawn
;; within that scope use as ref all the bits from the groups. The mask
;; is simply enough 1's to cover the group bits.
;;
;; In the example below, the clipper will be drawn using ref and mask set
;; accordingly, and any (non-clipper) child nodes with child ref and
;; child mask.
;; clipper type ref mask child ref child mask
;; - scene
;; - A non-inverted 00000001 00000000 00000001 00000011
;; - B non-inverted 00000101 00000011 00000101 00001111
;; - C non-inverted 00001001 00000011 00001001 00001111
;; - D non-inverted 00011001 00001111 00011001 00011111
;; - E non-inverted 00111001 00011111 00111001 01111111
;; - F non-inverted 01011001 00011111 01011001 01111111
;; - G non-inverted 00001101 00000011 00001101 00001111
;; - H non-inverted 00000010 00000000 00000010 00000011
;;
;; In the scene scope, we have the non-inverted clippers A and H. Since
;; these are top level clippers we always want to draw them, so the mask
;; is 0. In order to draw their child nodes properly we need to be able
;; to distinguish the two scopes, so they each get assigned a unique ref
;; value within this scope: 01 and 10. We cannot use the value 0 when
;; identifying a scope, because that value is also used used "outside"
;; the clipper. So: 00 is off limits, 01 and 10 are taken. We have three
;; values and must use two bits for our first bit group. The child mask
;; is unsurprisingly 00000011.
;;
;; Looking below A we have the non-inverted clippers B, C and G. The refs
;; of each have 01 in the two lowest bits, and we use the mask 11 when
;; drawing to confine them to A. By the same reasoning as earlier we need
;; two more bits to distinguish their scopes.
;;
;; Looking at C, there is only one non-inverted clipper D in scope so
;; this time we only need one bit. Finally below D we need two bits.
;;
;; Effectively the ref bits are used as follows:
;;
;; Bits: 7 6 5 4 3 2 1 0
;; Meaning: [not used] [E or F] [D] [B, C or G] [A or H]
;;
;; If in this example there had been more non-inverted clippers under H,
;; the bit patterns in bit 7->2 could have been reused. There would be no
;; risk of confusing the scopes since bits 0 and 1 (A or H) would differ.
;;
;; Notice that the mask gets filled as we go deeper in the clipper
;; hierarchy.
;;
;; Inverted clippers doesn't fit the bit group scheme. We want to draw
;; the clipper using a ref that identifies the clipper. But when drawing
;; the nodes in its scope, we want to *not* draw where the inverted
;; clipper is drawn. We must also still respect the scopes of clippers
;; higher up in the hierarchy.
;;
;; It's like we want the stencil test for nodes in scope to check:
;; "We are drawing in the parent of the inverted clipper" AND
;; "We are not drawing in the inverted clipper"
;;
;; (inverted-clipper-parent-ref & inverted-clipper-parent-child-mask) ==
;; (<value from stencil-buffer> & inverted-clipper-parent-child-mask)
;; AND
;; inverted-clipper-bit-value != (<value from stencil buffer> & inverted-clipper-bit-mask)
;;
;; We can't do this literally with the stencil functions, but we can
;; express it differently:
;;
;; (inverted-clipper-parent-ref & inverted-clipper-parent-child-mask) ==
;; (<value from stencil-buffer> & inverted-clipper-parent-child-mask)
;; AND
;; 0 == (<value from stencil buffer> & inverted-clipper-bit-mask)
;;
;; Then we do the two comparisons simultaneously:
;;
;; ((0 | inverted-clipper-parent-ref) & (inverted-clipper-bit-mask | inverted-clipper-parent-child-mask)) ==
;; (<value from stencil-buffer> & (inverted-clipper-bit-mask | inverted-clipper-parent-child-mask))
;;
;; We allocate the non-inverted group bits from lowest to highest. Then
;; for each inverted clipper within a non-inverted clipper scope (or the
;; top level pseudo scope), we allocate and set 1 bit from highest ->
;; lowest. The nodes in scope of an inverted clipper then includes that
;; clippers bit in its mask, but uses a ref value with the bit set to 0 -
;; effectively the child ref value is unchanged.
;;
;; An example:
;;
;; clipper type ref mask child ref child mask
;; - scene
;; - A non-inverted 00000001 00000000 00000001 00000011
;; - B non-inverted 00000101 00000011 00000101 00000111
;; - C non-inverted 00000010 00000000 00000010 00000011
;; - D inverted 10000010 00000011 00000010 10000011
;; - E inverted 01000010 10000011 00000010 11000011
;; - F inverted 00100010 00000011 00000010 00100011
;; - G non-inverted 00000110 00100011 00000110 00100111
;; - H inverted 00010110 00100111 00000110 00110111
;; - I inverted 10000000 00000000 00000000 10000000
;; - J non-inverted 00000011 10000000 00000011 10000011
;;
;; In the top level scene scope we have the obvious non-inverted clippers
;; A, C but now we also count J. The reason we include J in the scene
;; scope even though I lies between is that I is an inverted node. We
;; cannot use the bit we assign to I for distinguishing between A, C and
;; J. So, we have the off limits 00 + 01, 10, 11 for A, C and J requiring
;; 2 bits for the top level group.
;;
;; We assign bit 7 for I. We draw J with 0 in I's bit but with a mask
;; covering it. This makes sure we don't draw J on I. Notice that the
;; child mask of J must include I's bit.
;;
;; In the scope of C we have one non-inverted clipper G, requiring 1 bit,
;; and three inverted clippers D, E and F. Since we cannot use the bit
;; assigned to clippers to distinguish scopes, they get assigned one bit
;; each. We can not for instance use bit 6 for both E and F: when drawing
;; G we would be unable to draw where E was drawn.
;;
;; The implementation is mostly concerned with counting different types
;; of clippers in the scopes, assigning ref and mask values, and
;; transfering these to the scene nodes so the clipping is applied when
;; drawing.
;;
;; Visible Clippers
;;
;; Clippers can be marked as visible, meaning we draw them with the
;; color or texture assigned.
;;
;; We implement this by injecting a new scene node drawing the visible
;; part of the clipper. For inverted clippers, this representation must
;; still be drawn inside the clipper as opposed to the other children
;; being drawn only outside.
;;
;; Layers and rendering order
;;
;; For clipping to work properly, the clipper must be drawn before its
;; children. Normally we can change the draw order of nodes (starting out
;; as depth first, in order traversal) by assigning layers to nodes. But
;; doing that for clipper child nodes to draw it before the clipper would
;; be pointless. Instead the meaning of layers within clippers is changed
;; to only affect the relative draw order of the nodes in its scope. The
;; layer set on the clipper node itself does not affect its draw order -
;; but it *is* inherited by any child node with no layer set (like
;; outside clippers) and especially by the node representing a visible
;; clipper. The clipper is effectively drawn in the "null" layer.
;;
;; Bit overflow
;;
;; The 8 bits available creates some restrictions on how deep we can
;; nest clippers and how many clipper siblings we can have within the
;; scopes. If too many bits are needed the engine will start printing
;; warnings and clipping will simply break. In the editor we try to
;; recover from this by clearing the stencil buffer between rendering
;; each "top level" clipper in the scene. This helps if we have too
;; many siblings on the top level, but we can't recover from an
;; individual top level clipper tree requiring too many bits. It's
;; debatable whether we should even try to recover since the engine
;; can't.
;;
(set! *warn-on-reflection* true)
(def ^:private stencil-bits 8)
(defn- visible-clipper? [scene]
(get-in scene [:renderable :user-data :clipping :visible]))
(defn- clipper-scene? [scene]
(contains? (-> scene :renderable :user-data) :clipping))
(defn- clipper-trees
([scene]
(clipper-trees scene []))
([scene path]
(let [child-clippers (into []
(comp (map-indexed (fn [i e] (clipper-trees e (conj path i))))
cat)
(:children scene))]
(if-let [clipping (get-in scene [:renderable :user-data :clipping])]
[{:node-id (:node-id scene) ; for error values
;; add for debugging
;; :id (g/node-value (:node-id scene) :id)
:clipping clipping
:path path
:children child-clippers}]
child-clippers))))
(defn- wrap-trees [clipper-trees]
{:children clipper-trees})
(defn- inverted? [clipper]
(= true (get-in clipper [:clipping :inverted])))
(defn- non-inverted? [clipper]
(= false (get-in clipper [:clipping :inverted])))
(defn- wrapper? [clipper]
(and (not (inverted? clipper))
(not (non-inverted? clipper))))
(defn- count-inverted-clipper-scope [clipper-tree]
(assert (inverted? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
;; Number of paths down from this clipper that lead to a
;; non-inverted clipper (via only inverted clippers!).
;; We use this to determine how many bits to allocate for
;; distinguishinging successor non-inverted clippers in the
;; ancestor non-inverted clipper.
:successor-non-inverted successor-non-inverted
;; Number of inverted clippers along the paths down to a
;; non-inverted clipper (or bottom) + this inverted clipper.
;; We use this to determine how many individual bits to
;; allocate for inverted clippers between the ancestor
;; non-inverted clipper and successor non-inverted
;; clippers (or bottom).
:inverted-since-non-inverted-or-bottom (inc inverted-since-non-inverted-or-bottom)
;; On every non-inverted clipper we accumulate a required
;; bit count from the required bit counts of successor
;; non-inverted scopes, the number of successor
;; non-inverted scopes, and the number of inverted
;; scopes passed between.
:max-successor-non-inverted-allocated-bits max-successor-non-inverted-allocated-bits)))
(defn- log2 [n] (/ (Math/log n) (Math/log 2)))
(defn- pow2 [n] (bit-shift-left 1 n))
(defn- n->bits [n] (int (+ 1 (log2 n))))
(defn- bits->mask [bits] (dec (pow2 bits)))
(defn- count-non-inverted-clipper-scope [clipper-tree]
(assert (non-inverted? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
non-inverted-ref-bits (if (= successor-non-inverted 0) 0 (n->bits successor-non-inverted))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
;; Contributes 1 successor to the ancestor non-inverted
;; scope.
:successor-non-inverted 1
;; Accumulated bits needed to distinguish successor
;; non-inverted clipper scopes. Used during assignment of
;; ref-val and mask.
:non-inverted-ref-bits non-inverted-ref-bits
;; see count-inverted-clipper-scope
:max-successor-non-inverted-allocated-bits (+ non-inverted-ref-bits
inverted-since-non-inverted-or-bottom
max-successor-non-inverted-allocated-bits))))
(defn- count-wrapper-scope [clipper-tree]
(assert (wrapper? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
non-inverted-ref-bits (if (= successor-non-inverted 0) 0 (n->bits successor-non-inverted))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
:non-inverted-ref-bits non-inverted-ref-bits
:allocated-bits (+ non-inverted-ref-bits inverted-since-non-inverted-or-bottom max-successor-non-inverted-allocated-bits))))
(defn- count-clipper-scopes [clipper-tree]
(let [clipper-tree' (update clipper-tree :children #(map count-clipper-scopes %))]
(cond
(inverted? clipper-tree')
(count-inverted-clipper-scope clipper-tree')
(non-inverted? clipper-tree')
(count-non-inverted-clipper-scope clipper-tree')
true
(count-wrapper-scope clipper-tree'))))
(declare assign-clipper-bits)
(defn- assign-inverted-clipper-bits [clipper-tree context]
(let [inverted-clipper-bit-mask (bit-shift-left 1 (- (dec stencil-bits) (:inverted-clipper-bits-used context)))
ref-val (bit-or (:ref-val context) inverted-clipper-bit-mask)
mask (:mask context)
child-ref-val (:ref-val context) ; bit for this clipper is already 0 in context ref
child-mask (bit-or mask inverted-clipper-bit-mask)
child-context (-> context
(update :inverted-clipper-bits-used inc)
(assoc :ref-val child-ref-val
:mask child-mask))
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))
clipper-tree' (assoc clipper-tree
:ref-val ref-val
:mask mask
:child-ref-val child-ref-val
:child-mask child-mask
:children children')
context' (assoc context
:non-inverted-ref-val-counter (:non-inverted-ref-val-counter child-context')
:inverted-clipper-bits-used (:inverted-clipper-bits-used child-context'))]
[clipper-tree' context']))
(defn- assign-non-inverted-clipper-bits [clipper-tree context]
(let [ref-val (bit-or (:ref-val context) (bit-shift-left (:non-inverted-ref-val-counter context) (:non-inverted-ref-bits-used context)))
mask (:mask context)
child-ref-val ref-val
child-mask (bit-or mask (bit-shift-left (bits->mask (:non-inverted-ref-bits context)) (:non-inverted-ref-bits-used context)))
child-context {:ref-val child-ref-val
:mask child-mask
:inverted-clipper-bits-used (:inverted-clipper-bits-used context)
:non-inverted-ref-val-counter 1
:non-inverted-ref-bits (:non-inverted-ref-bits clipper-tree)
:non-inverted-ref-bits-used (+ (:non-inverted-ref-bits-used context) (:non-inverted-ref-bits context))}
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))
clipper-tree' (assoc clipper-tree
:ref-val ref-val
:mask mask
:child-ref-val child-ref-val
:child-mask child-mask
:children children')
context' (update context :non-inverted-ref-val-counter inc)]
[clipper-tree' context']))
(defn- assign-wrapper-clipper-bits [clipper-tree]
(assert (wrapper? clipper-tree))
(let [allocated (:allocated-bits clipper-tree)]
(if (<= allocated stencil-bits)
(let [child-context {:ref-val 0
:mask 0
:inverted-clipper-bits-used 0
:non-inverted-ref-val-counter 1
:non-inverted-ref-bits (:non-inverted-ref-bits clipper-tree)
:non-inverted-ref-bits-used 0}
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))]
(assoc clipper-tree :children children'))
(let [wrapped-child-clipper-trees (map (comp count-wrapper-scope wrap-trees vector) (:children clipper-tree))]
;; If the clipper-tree (wrapper) requires more bits than
;; available in the stencil buffer, we try to recover
;; by inserting a clear betweeen each top level clipper.
;; This is only possible if each of the top level clippers
;; would fit on its own. Otherwise, we bail with an error.
(if-let [overflowing-child-clipper-tree (first (filter #(> (:allocated-bits %) stencil-bits) wrapped-child-clipper-trees))]
(g/error-fatal "bit overflow" {:type :bit-overflow :source-id (-> overflowing-child-clipper-tree :children first :node-id)})
;; Try recovering from the overflow by adding clear
;; flags. Note that the engine does not do this, so you
;; might be misled into building a gui in the editor that
;; will not work during runtime. Apparently the engine only
;; inserts clears between rendering different gui scenes.
(let [children' (into []
(comp
(mapcat (fn [wrapped-child-clipper-tree]
;; Each wrapped-child-clipper-tree has one child, and assign-wrapper-clipper-bits
;; leaves the tree structure unchanged.
(let [{:keys [children]} (assign-wrapper-clipper-bits wrapped-child-clipper-tree)]
(assert (= 1 (count children)))
children)))
(map #(assoc % :clear true)))
wrapped-child-clipper-trees)]
(assoc clipper-tree :children children')))))))
(defn- assign-clipper-bits
([clipper-tree]
(assign-wrapper-clipper-bits clipper-tree))
([clipper-tree context]
(cond
(inverted? clipper-tree)
(assign-inverted-clipper-bits clipper-tree context)
(non-inverted? clipper-tree)
(assign-non-inverted-clipper-bits clipper-tree context))))
(defn- make-visible-clipper-scene [scene]
;; The visible clipper scene for an inverted clipper needs a
;; different mask & ref than other nodes in the clippers scope to
;; make it draw *inside* rather than outside the clipper. For this
;; we tag it with :visible-clipper-scene?
(-> scene
(update-in [:renderable :user-data] dissoc :clipping) ; don't want to treat this node as a clipper
(assoc-in [:renderable :user-data :visible-clipper-scene?] true) ; tag it
(dissoc :children :transform :aabb)))
(defn- visible-clipper-scene? [scene]
(get-in scene [:renderable :user-data :visible-clipper-scene?]))
(defn- inject-visible-clipper-scenes [scene]
(cond-> (update scene :children #(map inject-visible-clipper-scenes %))
(visible-clipper? scene)
(update :children #(into [(make-visible-clipper-scene scene)] %))))
(defn- remove-clipper-renderable-tags
"We remove the renderable tags for all clipper scenes to make sure
the clipping state is drawn. Any visible clipper representation
retains the tags and can be hidden."
[scene]
(cond-> (update scene :children #(map remove-clipper-renderable-tags %))
(clipper-scene? scene)
(update-in [:renderable] dissoc :tags)))
(defn- clipper-tree->trie [clipper-tree]
(reduce (fn [trie clipper-tree]
(assoc-in trie (:path clipper-tree) (select-keys clipper-tree [:ref-val :mask :child-ref-val :child-mask :clear])))
(select-keys clipper-tree [:ref-val :mask :child-ref-val :child-mask :clear])
(rest (tree-seq :children :children clipper-tree))))
(defn- descendant-clipping-state [last-clipper-trie visible-clipper-scene?]
;; If this is the injected scene for showing the clipper contents, it should be drawn using the same
;; ref and mask as the clipper itself.
{:ref-val (if visible-clipper-scene? (:ref-val last-clipper-trie) (:child-ref-val last-clipper-trie))
:mask (if visible-clipper-scene? (:mask last-clipper-trie) (:child-mask last-clipper-trie))
:write-mask 0
:color-mask [true true true true]})
(defn- clipper-clipping-state [clipper-trie]
(cond-> {:ref-val (:ref-val clipper-trie)
:mask (:mask clipper-trie)
:write-mask 0xff
:color-mask [false false false false]}
(:clear clipper-trie)
(assoc :clear true)))
(defn- clipper-trie? [trie]
(contains? trie :ref-val))
(defn- lookup-clipping-state [trie last-clipper-trie step visible-clipper-scene?]
(if-let [next-trie (get trie step)]
(if (clipper-trie? next-trie)
;; trie represents clipper -> this is a clipper node
[next-trie next-trie (clipper-clipping-state next-trie)]
;; trie does not represent a clipper -> this is a descendant node of some earlier clipper
[next-trie last-clipper-trie (when last-clipper-trie (descendant-clipping-state last-clipper-trie visible-clipper-scene?))])
;; stepping outside the tree of clippers -> this is a descendant node of some earlier clipper
[nil last-clipper-trie (when last-clipper-trie (descendant-clipping-state last-clipper-trie visible-clipper-scene?))]))
(defn- add-clipping-state [scene clipping-state]
(-> scene
(assoc-in [:renderable :user-data :clipping-state] clipping-state)
(assoc-in [:renderable :batch-key :clipping-state] clipping-state)))
(defn- apply-clippers [clipper-tree scene]
(let [trie (clipper-tree->trie clipper-tree)]
(letfn [(apply-clipping [scene [trie last-clipper-trie clipping-state]]
(let [new-children (map-indexed (fn [index child]
(let [child-lookup-result (lookup-clipping-state trie last-clipper-trie index (visible-clipper-scene? child))]
(apply-clipping child child-lookup-result)))
(:children scene))]
(cond-> (assoc scene :children new-children)
(contains? scene :renderable)
(add-clipping-state clipping-state)
:because-gui-clipping-tests-need-it
(assoc-in [:renderable :user-data :clipping-child-state]
(nth (lookup-clipping-state trie last-clipper-trie :fake-child-step false) 2)))))]
(assert (not (clipper-trie? trie)))
(apply-clipping scene [trie nil nil]))))
#_(defn- bitstring
([n] (bitstring n stencil-bits))
([n total-bits] (cl-format nil (str "~" total-bits ",'0',B") n)))
#_(defn- print-clipper-tree
([clipper-tree] (print-clipper-tree clipper-tree ""))
([clipper-tree prefix]
(let [{:keys [id node-id clear max-successor-non-inverted-allocated-bits path ref-val mask child-ref-val child-mask]} clipper-tree]
(println prefix :id id
(cond (inverted? clipper-tree) :inverted
(non-inverted? clipper-tree) :non-inverted
:else :not-a-clipper)
:node-id node-id
:clear clear
:bits-allocated max-successor-non-inverted-allocated-bits
:path path
:ref-val (when ref-val (bitstring ref-val))
:mask (when mask (bitstring mask))
:child-ref-val (when child-ref-val (bitstring child-ref-val))
:child-mask (when child-mask (bitstring child-mask))))
(run! #(print-clipper-tree % (str prefix " ")) (:children clipper-tree))))
(defn setup-states [scene]
(let [scene-with-visible-clippers (-> scene
inject-visible-clipper-scenes
remove-clipper-renderable-tags)
clipper-tree (-> scene-with-visible-clippers
clipper-trees
wrap-trees
count-clipper-scopes
assign-clipper-bits)]
(cond
(g/error? clipper-tree)
clipper-tree
true
(apply-clippers clipper-tree scene-with-visible-clippers))))
(defn scene-key [scene]
[(:node-id scene) (get-in scene [:renderable :user-data :clipping-state])])
(defn- trickle-down-default-layers
"Perform inheritance of parent node layer to child nodes with no
layer assigned, and strip layer from clipper nodes."
([scene]
(trickle-down-default-layers nil scene))
([default-layer scene]
(let [layer (get-in scene [:renderable :layer-index])]
(if (and layer (>= layer 0))
(cond-> (update scene :children #(mapv (partial trickle-down-default-layers layer) %))
(clipper-scene? scene)
(assoc-in [:renderable :layer-index] nil)) ; clipper nodes render in the null layer (first)
(cond-> (update scene :children #(mapv (partial trickle-down-default-layers default-layer) %))
(not (clipper-scene? scene))
(assoc-in [:renderable :layer-index] default-layer))))))
(defn- scope-scenes
"Collect scenes in depth first pre order (parent visited before children), stopping at clipper nodes."
[scene]
(loop [children-stack (list (:children scene))
scenes []]
(cond
(not (seq children-stack))
scenes
(not (seq (first children-stack)))
(recur (rest children-stack) scenes)
true
(let [child (ffirst children-stack)
next-children (if (clipper-scene? child) [] (:children child))]
(recur (cons next-children (cons (rest (first children-stack)) (rest children-stack)))
(conj scenes child))))))
(defn- render-keys
([scene]
(render-keys {} (scope-scenes scene)))
([assignment unsorted-scenes]
(let [scenes (sort-by #(get-in % [:renderable :layer-index]) unsorted-scenes)]
(reduce (fn [assignment scene]
(if (clipper-scene? scene)
(-> assignment
(assoc (scene-key scene) (count assignment))
(render-keys (scope-scenes scene)))
(assoc assignment (scene-key scene) (count assignment))))
assignment
scenes))))
(defn scene->render-keys [scene]
(-> scene
trickle-down-default-layers
render-keys))
(defn setup-gl [^GL2 gl state]
(when state
(.glEnable gl GL/GL_STENCIL_TEST)
(.glStencilOp gl GL/GL_KEEP GL/GL_REPLACE GL/GL_REPLACE)
(.glStencilFunc gl GL2/GL_EQUAL (:ref-val state) (:mask state))
(.glStencilMask gl (:write-mask state))
(when (:clear state)
(.glClear gl GL/GL_STENCIL_BUFFER_BIT))
(let [[c0 c1 c2 c3] (:color-mask state)]
(.glColorMask gl c0 c1 c2 c3))))
(defn restore-gl [^GL2 gl state]
(when state
(.glDisable gl GL/GL_STENCIL_TEST)
(.glColorMask gl true true true true)))
| true |
;; Copyright 2020-2022 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.gui-clipping
(:require [dynamo.graph :as g]
[clojure.pprint :refer [cl-format]])
(:import [com.jogamp.opengl GL GL2]
[clojure.lang ExceptionInfo]))
;;
;; Clipping
;;
;; Clipping uses the stencil buffer. Similar to the depth buffer, the
;; stencil buffer is used to determine whether or not to draw by
;; comparing a value from the buffer with a value from what you're
;; drawing. For the depth buffer we're roughly comparing the z component
;; of what you're drawing with the value in the depth buffer. If the z
;; value is < (or > depending on axis direction?) we draw, and update the
;; depth buffer with the new z.
;;
;; For the stencil buffer the api is slightly different. The functions we
;; use are:
;;
;; * glStencilOp sfail dpfail dppass
;; * glStencilFunc func ref mask
;; * glStencilMask stencil-mask
;; * glEnable/glDisable with GL_STENCIL_TEST
;; * glClear with GL_STENCIL_BUFFER_BIT
;;
;; When the stencil buffer is enabled, the following test is performed
;; before the depth test:
;;
;; (ref & mask) func (<value from stencil buffer> & mask)
;;
;; If this test fails, we update the stencil buffer according to sfail.
;; If it succeeds and the depth test fails, we update according to dpfail.
;; If both tests pass, we update according to dppass and draw.
;;
;; The stencil buffer can be updated by incrementing or decrementing
;; the value, setting it to zero, inverting the bits, keeping the
;; original value or replacing it with ref. Only the bits masked by
;; stencil-mask are updated.
;;
;; The parameters we use are:
;;
;; * glStencilOp GL_KEEP GL_REPLACE GL_REPLACE
;; The stencil buffer is updated whenever the stencil test
;; succeeds. If the test fails, we keep the old value.
;;
;; * glStencilFunc GL_EQUAL ref mask
;; With ref and mask set depending on where we are in the gui scene.
;;
;; * glStencilMask 0xff or 0
;; Depending on if we're drawing a clipper or a normal node.
;;
;; So for us, the test is:
;;
;; (ref & mask) == (<value from stencil buffer> & mask)
;;
;; And since we replace the value on success, the value written will
;; effectively be:
;;
;; (<old-stencil-value> & ~stencil-mask) | (ref & stencil-mask)
;;
;; But since we always set stencil-mask to 0xff or 0, we either leave
;; the bits as-is or replace it entirely.
;;
;; Note that ref is used both in the test and for setting the new
;; value.
;;
;; In Defold we assume the stencil buffer depth is 8 bits, so ref and
;; mask are 8 bits. We support inverted- and non-inverted clippers,
;; and clippers can be nested. Think of the clippers in a scene as
;; nested scopes. All nodes within a scope are drawn with a ref and
;; mask that identifies the scope in order to clip it properly. One
;; pseudo-scope covers the whole scene and any node drawn in that
;; scope (not under an actual clipper) is drawn without clipping
;; enabled. To identify nested non-inverted clipper scopes we split
;; the 8 bits of the ref value into groups. The value of each group is
;; roughly the steps in a path you take along the clipper hierarchy to
;; reach a particular non-inverted clipper scope. The nodes drawn
;; within that scope use as ref all the bits from the groups. The mask
;; is simply enough 1's to cover the group bits.
;;
;; In the example below, the clipper will be drawn using ref and mask set
;; accordingly, and any (non-clipper) child nodes with child ref and
;; child mask.
;; clipper type ref mask child ref child mask
;; - scene
;; - A non-inverted 00000001 00000000 00000001 00000011
;; - B non-inverted 00000101 00000011 00000101 00001111
;; - C non-inverted 00001001 00000011 00001001 00001111
;; - D non-inverted 00011001 00001111 00011001 00011111
;; - E non-inverted 00111001 00011111 00111001 01111111
;; - F non-inverted 01011001 00011111 01011001 01111111
;; - G non-inverted 00001101 00000011 00001101 00001111
;; - H non-inverted 00000010 00000000 00000010 00000011
;;
;; In the scene scope, we have the non-inverted clippers A and H. Since
;; these are top level clippers we always want to draw them, so the mask
;; is 0. In order to draw their child nodes properly we need to be able
;; to distinguish the two scopes, so they each get assigned a unique ref
;; value within this scope: 01 and 10. We cannot use the value 0 when
;; identifying a scope, because that value is also used used "outside"
;; the clipper. So: 00 is off limits, 01 and 10 are taken. We have three
;; values and must use two bits for our first bit group. The child mask
;; is unsurprisingly 00000011.
;;
;; Looking below A we have the non-inverted clippers B, C and G. The refs
;; of each have 01 in the two lowest bits, and we use the mask 11 when
;; drawing to confine them to A. By the same reasoning as earlier we need
;; two more bits to distinguish their scopes.
;;
;; Looking at C, there is only one non-inverted clipper D in scope so
;; this time we only need one bit. Finally below D we need two bits.
;;
;; Effectively the ref bits are used as follows:
;;
;; Bits: 7 6 5 4 3 2 1 0
;; Meaning: [not used] [E or F] [D] [B, C or G] [A or H]
;;
;; If in this example there had been more non-inverted clippers under H,
;; the bit patterns in bit 7->2 could have been reused. There would be no
;; risk of confusing the scopes since bits 0 and 1 (A or H) would differ.
;;
;; Notice that the mask gets filled as we go deeper in the clipper
;; hierarchy.
;;
;; Inverted clippers doesn't fit the bit group scheme. We want to draw
;; the clipper using a ref that identifies the clipper. But when drawing
;; the nodes in its scope, we want to *not* draw where the inverted
;; clipper is drawn. We must also still respect the scopes of clippers
;; higher up in the hierarchy.
;;
;; It's like we want the stencil test for nodes in scope to check:
;; "We are drawing in the parent of the inverted clipper" AND
;; "We are not drawing in the inverted clipper"
;;
;; (inverted-clipper-parent-ref & inverted-clipper-parent-child-mask) ==
;; (<value from stencil-buffer> & inverted-clipper-parent-child-mask)
;; AND
;; inverted-clipper-bit-value != (<value from stencil buffer> & inverted-clipper-bit-mask)
;;
;; We can't do this literally with the stencil functions, but we can
;; express it differently:
;;
;; (inverted-clipper-parent-ref & inverted-clipper-parent-child-mask) ==
;; (<value from stencil-buffer> & inverted-clipper-parent-child-mask)
;; AND
;; 0 == (<value from stencil buffer> & inverted-clipper-bit-mask)
;;
;; Then we do the two comparisons simultaneously:
;;
;; ((0 | inverted-clipper-parent-ref) & (inverted-clipper-bit-mask | inverted-clipper-parent-child-mask)) ==
;; (<value from stencil-buffer> & (inverted-clipper-bit-mask | inverted-clipper-parent-child-mask))
;;
;; We allocate the non-inverted group bits from lowest to highest. Then
;; for each inverted clipper within a non-inverted clipper scope (or the
;; top level pseudo scope), we allocate and set 1 bit from highest ->
;; lowest. The nodes in scope of an inverted clipper then includes that
;; clippers bit in its mask, but uses a ref value with the bit set to 0 -
;; effectively the child ref value is unchanged.
;;
;; An example:
;;
;; clipper type ref mask child ref child mask
;; - scene
;; - A non-inverted 00000001 00000000 00000001 00000011
;; - B non-inverted 00000101 00000011 00000101 00000111
;; - C non-inverted 00000010 00000000 00000010 00000011
;; - D inverted 10000010 00000011 00000010 10000011
;; - E inverted 01000010 10000011 00000010 11000011
;; - F inverted 00100010 00000011 00000010 00100011
;; - G non-inverted 00000110 00100011 00000110 00100111
;; - H inverted 00010110 00100111 00000110 00110111
;; - I inverted 10000000 00000000 00000000 10000000
;; - J non-inverted 00000011 10000000 00000011 10000011
;;
;; In the top level scene scope we have the obvious non-inverted clippers
;; A, C but now we also count J. The reason we include J in the scene
;; scope even though I lies between is that I is an inverted node. We
;; cannot use the bit we assign to I for distinguishing between A, C and
;; J. So, we have the off limits 00 + 01, 10, 11 for A, C and J requiring
;; 2 bits for the top level group.
;;
;; We assign bit 7 for I. We draw J with 0 in I's bit but with a mask
;; covering it. This makes sure we don't draw J on I. Notice that the
;; child mask of J must include I's bit.
;;
;; In the scope of C we have one non-inverted clipper G, requiring 1 bit,
;; and three inverted clippers D, E and F. Since we cannot use the bit
;; assigned to clippers to distinguish scopes, they get assigned one bit
;; each. We can not for instance use bit 6 for both E and F: when drawing
;; G we would be unable to draw where E was drawn.
;;
;; The implementation is mostly concerned with counting different types
;; of clippers in the scopes, assigning ref and mask values, and
;; transfering these to the scene nodes so the clipping is applied when
;; drawing.
;;
;; Visible Clippers
;;
;; Clippers can be marked as visible, meaning we draw them with the
;; color or texture assigned.
;;
;; We implement this by injecting a new scene node drawing the visible
;; part of the clipper. For inverted clippers, this representation must
;; still be drawn inside the clipper as opposed to the other children
;; being drawn only outside.
;;
;; Layers and rendering order
;;
;; For clipping to work properly, the clipper must be drawn before its
;; children. Normally we can change the draw order of nodes (starting out
;; as depth first, in order traversal) by assigning layers to nodes. But
;; doing that for clipper child nodes to draw it before the clipper would
;; be pointless. Instead the meaning of layers within clippers is changed
;; to only affect the relative draw order of the nodes in its scope. The
;; layer set on the clipper node itself does not affect its draw order -
;; but it *is* inherited by any child node with no layer set (like
;; outside clippers) and especially by the node representing a visible
;; clipper. The clipper is effectively drawn in the "null" layer.
;;
;; Bit overflow
;;
;; The 8 bits available creates some restrictions on how deep we can
;; nest clippers and how many clipper siblings we can have within the
;; scopes. If too many bits are needed the engine will start printing
;; warnings and clipping will simply break. In the editor we try to
;; recover from this by clearing the stencil buffer between rendering
;; each "top level" clipper in the scene. This helps if we have too
;; many siblings on the top level, but we can't recover from an
;; individual top level clipper tree requiring too many bits. It's
;; debatable whether we should even try to recover since the engine
;; can't.
;;
(set! *warn-on-reflection* true)
(def ^:private stencil-bits 8)
(defn- visible-clipper? [scene]
(get-in scene [:renderable :user-data :clipping :visible]))
(defn- clipper-scene? [scene]
(contains? (-> scene :renderable :user-data) :clipping))
(defn- clipper-trees
([scene]
(clipper-trees scene []))
([scene path]
(let [child-clippers (into []
(comp (map-indexed (fn [i e] (clipper-trees e (conj path i))))
cat)
(:children scene))]
(if-let [clipping (get-in scene [:renderable :user-data :clipping])]
[{:node-id (:node-id scene) ; for error values
;; add for debugging
;; :id (g/node-value (:node-id scene) :id)
:clipping clipping
:path path
:children child-clippers}]
child-clippers))))
(defn- wrap-trees [clipper-trees]
{:children clipper-trees})
(defn- inverted? [clipper]
(= true (get-in clipper [:clipping :inverted])))
(defn- non-inverted? [clipper]
(= false (get-in clipper [:clipping :inverted])))
(defn- wrapper? [clipper]
(and (not (inverted? clipper))
(not (non-inverted? clipper))))
(defn- count-inverted-clipper-scope [clipper-tree]
(assert (inverted? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
;; Number of paths down from this clipper that lead to a
;; non-inverted clipper (via only inverted clippers!).
;; We use this to determine how many bits to allocate for
;; distinguishinging successor non-inverted clippers in the
;; ancestor non-inverted clipper.
:successor-non-inverted successor-non-inverted
;; Number of inverted clippers along the paths down to a
;; non-inverted clipper (or bottom) + this inverted clipper.
;; We use this to determine how many individual bits to
;; allocate for inverted clippers between the ancestor
;; non-inverted clipper and successor non-inverted
;; clippers (or bottom).
:inverted-since-non-inverted-or-bottom (inc inverted-since-non-inverted-or-bottom)
;; On every non-inverted clipper we accumulate a required
;; bit count from the required bit counts of successor
;; non-inverted scopes, the number of successor
;; non-inverted scopes, and the number of inverted
;; scopes passed between.
:max-successor-non-inverted-allocated-bits max-successor-non-inverted-allocated-bits)))
(defn- log2 [n] (/ (Math/log n) (Math/log 2)))
(defn- pow2 [n] (bit-shift-left 1 n))
(defn- n->bits [n] (int (+ 1 (log2 n))))
(defn- bits->mask [bits] (dec (pow2 bits)))
(defn- count-non-inverted-clipper-scope [clipper-tree]
(assert (non-inverted? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
non-inverted-ref-bits (if (= successor-non-inverted 0) 0 (n->bits successor-non-inverted))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
;; Contributes 1 successor to the ancestor non-inverted
;; scope.
:successor-non-inverted 1
;; Accumulated bits needed to distinguish successor
;; non-inverted clipper scopes. Used during assignment of
;; ref-val and mask.
:non-inverted-ref-bits non-inverted-ref-bits
;; see count-inverted-clipper-scope
:max-successor-non-inverted-allocated-bits (+ non-inverted-ref-bits
inverted-since-non-inverted-or-bottom
max-successor-non-inverted-allocated-bits))))
(defn- count-wrapper-scope [clipper-tree]
(assert (wrapper? clipper-tree))
(let [successor-non-inverted (apply + (keep :successor-non-inverted (:children clipper-tree)))
inverted-since-non-inverted-or-bottom (apply + (keep :inverted-since-non-inverted-or-bottom (:children clipper-tree)))
non-inverted-ref-bits (if (= successor-non-inverted 0) 0 (n->bits successor-non-inverted))
max-successor-non-inverted-allocated-bits (apply max 0 (map :max-successor-non-inverted-allocated-bits (:children clipper-tree)))]
(assoc clipper-tree
:non-inverted-ref-bits non-inverted-ref-bits
:allocated-bits (+ non-inverted-ref-bits inverted-since-non-inverted-or-bottom max-successor-non-inverted-allocated-bits))))
(defn- count-clipper-scopes [clipper-tree]
(let [clipper-tree' (update clipper-tree :children #(map count-clipper-scopes %))]
(cond
(inverted? clipper-tree')
(count-inverted-clipper-scope clipper-tree')
(non-inverted? clipper-tree')
(count-non-inverted-clipper-scope clipper-tree')
true
(count-wrapper-scope clipper-tree'))))
(declare assign-clipper-bits)
(defn- assign-inverted-clipper-bits [clipper-tree context]
(let [inverted-clipper-bit-mask (bit-shift-left 1 (- (dec stencil-bits) (:inverted-clipper-bits-used context)))
ref-val (bit-or (:ref-val context) inverted-clipper-bit-mask)
mask (:mask context)
child-ref-val (:ref-val context) ; bit for this clipper is already 0 in context ref
child-mask (bit-or mask inverted-clipper-bit-mask)
child-context (-> context
(update :inverted-clipper-bits-used inc)
(assoc :ref-val child-ref-val
:mask child-mask))
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))
clipper-tree' (assoc clipper-tree
:ref-val ref-val
:mask mask
:child-ref-val child-ref-val
:child-mask child-mask
:children children')
context' (assoc context
:non-inverted-ref-val-counter (:non-inverted-ref-val-counter child-context')
:inverted-clipper-bits-used (:inverted-clipper-bits-used child-context'))]
[clipper-tree' context']))
(defn- assign-non-inverted-clipper-bits [clipper-tree context]
(let [ref-val (bit-or (:ref-val context) (bit-shift-left (:non-inverted-ref-val-counter context) (:non-inverted-ref-bits-used context)))
mask (:mask context)
child-ref-val ref-val
child-mask (bit-or mask (bit-shift-left (bits->mask (:non-inverted-ref-bits context)) (:non-inverted-ref-bits-used context)))
child-context {:ref-val child-ref-val
:mask child-mask
:inverted-clipper-bits-used (:inverted-clipper-bits-used context)
:non-inverted-ref-val-counter 1
:non-inverted-ref-bits (:non-inverted-ref-bits clipper-tree)
:non-inverted-ref-bits-used (+ (:non-inverted-ref-bits-used context) (:non-inverted-ref-bits context))}
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))
clipper-tree' (assoc clipper-tree
:ref-val ref-val
:mask mask
:child-ref-val child-ref-val
:child-mask child-mask
:children children')
context' (update context :non-inverted-ref-val-counter inc)]
[clipper-tree' context']))
(defn- assign-wrapper-clipper-bits [clipper-tree]
(assert (wrapper? clipper-tree))
(let [allocated (:allocated-bits clipper-tree)]
(if (<= allocated stencil-bits)
(let [child-context {:ref-val 0
:mask 0
:inverted-clipper-bits-used 0
:non-inverted-ref-val-counter 1
:non-inverted-ref-bits (:non-inverted-ref-bits clipper-tree)
:non-inverted-ref-bits-used 0}
[children' child-context'] (reduce (fn [[new-children context] child]
(let [[child' context'] (assign-clipper-bits child context)]
[(conj new-children child') context']))
[[] child-context]
(:children clipper-tree))]
(assoc clipper-tree :children children'))
(let [wrapped-child-clipper-trees (map (comp count-wrapper-scope wrap-trees vector) (:children clipper-tree))]
;; If the clipper-tree (wrapper) requires more bits than
;; available in the stencil buffer, we try to recover
;; by inserting a clear betweeen each top level clipper.
;; This is only possible if each of the top level clippers
;; would fit on its own. Otherwise, we bail with an error.
(if-let [overflowing-child-clipper-tree (first (filter #(> (:allocated-bits %) stencil-bits) wrapped-child-clipper-trees))]
(g/error-fatal "bit overflow" {:type :bit-overflow :source-id (-> overflowing-child-clipper-tree :children first :node-id)})
;; Try recovering from the overflow by adding clear
;; flags. Note that the engine does not do this, so you
;; might be misled into building a gui in the editor that
;; will not work during runtime. Apparently the engine only
;; inserts clears between rendering different gui scenes.
(let [children' (into []
(comp
(mapcat (fn [wrapped-child-clipper-tree]
;; Each wrapped-child-clipper-tree has one child, and assign-wrapper-clipper-bits
;; leaves the tree structure unchanged.
(let [{:keys [children]} (assign-wrapper-clipper-bits wrapped-child-clipper-tree)]
(assert (= 1 (count children)))
children)))
(map #(assoc % :clear true)))
wrapped-child-clipper-trees)]
(assoc clipper-tree :children children')))))))
(defn- assign-clipper-bits
([clipper-tree]
(assign-wrapper-clipper-bits clipper-tree))
([clipper-tree context]
(cond
(inverted? clipper-tree)
(assign-inverted-clipper-bits clipper-tree context)
(non-inverted? clipper-tree)
(assign-non-inverted-clipper-bits clipper-tree context))))
(defn- make-visible-clipper-scene [scene]
;; The visible clipper scene for an inverted clipper needs a
;; different mask & ref than other nodes in the clippers scope to
;; make it draw *inside* rather than outside the clipper. For this
;; we tag it with :visible-clipper-scene?
(-> scene
(update-in [:renderable :user-data] dissoc :clipping) ; don't want to treat this node as a clipper
(assoc-in [:renderable :user-data :visible-clipper-scene?] true) ; tag it
(dissoc :children :transform :aabb)))
(defn- visible-clipper-scene? [scene]
(get-in scene [:renderable :user-data :visible-clipper-scene?]))
(defn- inject-visible-clipper-scenes [scene]
(cond-> (update scene :children #(map inject-visible-clipper-scenes %))
(visible-clipper? scene)
(update :children #(into [(make-visible-clipper-scene scene)] %))))
(defn- remove-clipper-renderable-tags
"We remove the renderable tags for all clipper scenes to make sure
the clipping state is drawn. Any visible clipper representation
retains the tags and can be hidden."
[scene]
(cond-> (update scene :children #(map remove-clipper-renderable-tags %))
(clipper-scene? scene)
(update-in [:renderable] dissoc :tags)))
(defn- clipper-tree->trie [clipper-tree]
(reduce (fn [trie clipper-tree]
(assoc-in trie (:path clipper-tree) (select-keys clipper-tree [:ref-val :mask :child-ref-val :child-mask :clear])))
(select-keys clipper-tree [:ref-val :mask :child-ref-val :child-mask :clear])
(rest (tree-seq :children :children clipper-tree))))
(defn- descendant-clipping-state [last-clipper-trie visible-clipper-scene?]
;; If this is the injected scene for showing the clipper contents, it should be drawn using the same
;; ref and mask as the clipper itself.
{:ref-val (if visible-clipper-scene? (:ref-val last-clipper-trie) (:child-ref-val last-clipper-trie))
:mask (if visible-clipper-scene? (:mask last-clipper-trie) (:child-mask last-clipper-trie))
:write-mask 0
:color-mask [true true true true]})
(defn- clipper-clipping-state [clipper-trie]
(cond-> {:ref-val (:ref-val clipper-trie)
:mask (:mask clipper-trie)
:write-mask 0xff
:color-mask [false false false false]}
(:clear clipper-trie)
(assoc :clear true)))
(defn- clipper-trie? [trie]
(contains? trie :ref-val))
(defn- lookup-clipping-state [trie last-clipper-trie step visible-clipper-scene?]
(if-let [next-trie (get trie step)]
(if (clipper-trie? next-trie)
;; trie represents clipper -> this is a clipper node
[next-trie next-trie (clipper-clipping-state next-trie)]
;; trie does not represent a clipper -> this is a descendant node of some earlier clipper
[next-trie last-clipper-trie (when last-clipper-trie (descendant-clipping-state last-clipper-trie visible-clipper-scene?))])
;; stepping outside the tree of clippers -> this is a descendant node of some earlier clipper
[nil last-clipper-trie (when last-clipper-trie (descendant-clipping-state last-clipper-trie visible-clipper-scene?))]))
(defn- add-clipping-state [scene clipping-state]
(-> scene
(assoc-in [:renderable :user-data :clipping-state] clipping-state)
(assoc-in [:renderable :batch-key :clipping-state] clipping-state)))
(defn- apply-clippers [clipper-tree scene]
(let [trie (clipper-tree->trie clipper-tree)]
(letfn [(apply-clipping [scene [trie last-clipper-trie clipping-state]]
(let [new-children (map-indexed (fn [index child]
(let [child-lookup-result (lookup-clipping-state trie last-clipper-trie index (visible-clipper-scene? child))]
(apply-clipping child child-lookup-result)))
(:children scene))]
(cond-> (assoc scene :children new-children)
(contains? scene :renderable)
(add-clipping-state clipping-state)
:because-gui-clipping-tests-need-it
(assoc-in [:renderable :user-data :clipping-child-state]
(nth (lookup-clipping-state trie last-clipper-trie :fake-child-step false) 2)))))]
(assert (not (clipper-trie? trie)))
(apply-clipping scene [trie nil nil]))))
#_(defn- bitstring
([n] (bitstring n stencil-bits))
([n total-bits] (cl-format nil (str "~" total-bits ",'0',B") n)))
#_(defn- print-clipper-tree
([clipper-tree] (print-clipper-tree clipper-tree ""))
([clipper-tree prefix]
(let [{:keys [id node-id clear max-successor-non-inverted-allocated-bits path ref-val mask child-ref-val child-mask]} clipper-tree]
(println prefix :id id
(cond (inverted? clipper-tree) :inverted
(non-inverted? clipper-tree) :non-inverted
:else :not-a-clipper)
:node-id node-id
:clear clear
:bits-allocated max-successor-non-inverted-allocated-bits
:path path
:ref-val (when ref-val (bitstring ref-val))
:mask (when mask (bitstring mask))
:child-ref-val (when child-ref-val (bitstring child-ref-val))
:child-mask (when child-mask (bitstring child-mask))))
(run! #(print-clipper-tree % (str prefix " ")) (:children clipper-tree))))
(defn setup-states [scene]
(let [scene-with-visible-clippers (-> scene
inject-visible-clipper-scenes
remove-clipper-renderable-tags)
clipper-tree (-> scene-with-visible-clippers
clipper-trees
wrap-trees
count-clipper-scopes
assign-clipper-bits)]
(cond
(g/error? clipper-tree)
clipper-tree
true
(apply-clippers clipper-tree scene-with-visible-clippers))))
(defn scene-key [scene]
[(:node-id scene) (get-in scene [:renderable :user-data :clipping-state])])
(defn- trickle-down-default-layers
"Perform inheritance of parent node layer to child nodes with no
layer assigned, and strip layer from clipper nodes."
([scene]
(trickle-down-default-layers nil scene))
([default-layer scene]
(let [layer (get-in scene [:renderable :layer-index])]
(if (and layer (>= layer 0))
(cond-> (update scene :children #(mapv (partial trickle-down-default-layers layer) %))
(clipper-scene? scene)
(assoc-in [:renderable :layer-index] nil)) ; clipper nodes render in the null layer (first)
(cond-> (update scene :children #(mapv (partial trickle-down-default-layers default-layer) %))
(not (clipper-scene? scene))
(assoc-in [:renderable :layer-index] default-layer))))))
(defn- scope-scenes
"Collect scenes in depth first pre order (parent visited before children), stopping at clipper nodes."
[scene]
(loop [children-stack (list (:children scene))
scenes []]
(cond
(not (seq children-stack))
scenes
(not (seq (first children-stack)))
(recur (rest children-stack) scenes)
true
(let [child (ffirst children-stack)
next-children (if (clipper-scene? child) [] (:children child))]
(recur (cons next-children (cons (rest (first children-stack)) (rest children-stack)))
(conj scenes child))))))
(defn- render-keys
([scene]
(render-keys {} (scope-scenes scene)))
([assignment unsorted-scenes]
(let [scenes (sort-by #(get-in % [:renderable :layer-index]) unsorted-scenes)]
(reduce (fn [assignment scene]
(if (clipper-scene? scene)
(-> assignment
(assoc (scene-key scene) (count assignment))
(render-keys (scope-scenes scene)))
(assoc assignment (scene-key scene) (count assignment))))
assignment
scenes))))
(defn scene->render-keys [scene]
(-> scene
trickle-down-default-layers
render-keys))
(defn setup-gl [^GL2 gl state]
(when state
(.glEnable gl GL/GL_STENCIL_TEST)
(.glStencilOp gl GL/GL_KEEP GL/GL_REPLACE GL/GL_REPLACE)
(.glStencilFunc gl GL2/GL_EQUAL (:ref-val state) (:mask state))
(.glStencilMask gl (:write-mask state))
(when (:clear state)
(.glClear gl GL/GL_STENCIL_BUFFER_BIT))
(let [[c0 c1 c2 c3] (:color-mask state)]
(.glColorMask gl c0 c1 c2 c3))))
(defn restore-gl [^GL2 gl state]
(when state
(.glDisable gl GL/GL_STENCIL_TEST)
(.glColorMask gl true true true true)))
|
[
{
"context": "n/is-this-a-bug-extending-protocol-on-js-object\n;; david nolan:\n;; You should never extend js/Object.\n;; It's un",
"end": 3474,
"score": 0.9993802905082703,
"start": 3463,
"tag": "NAME",
"value": "david nolan"
}
] |
src/pinkgorilla/ui/rendererCLJS.cljs
|
mauricioszabo/gorilla-renderable-ui
| 0 |
(ns pinkgorilla.ui.rendererCLJS
"equivalent to pinkgorilla.ui.renderer, but for clojurescript
renders clojurescript data structure to html"
(:require
[clojure.string :as string]
[pinkgorilla.ui.gorilla-renderable :refer [Renderable render]]))
;;; Helper functions
;; A lot of things render to an HTML span, with a class to mark the type of thing. This helper constructs the rendered
;; value in that case.
(defn- span-render
[thing class]
{:type :html
:content [:span {:class class} (pr-str thing)]
:value (pr-str thing)})
(defn- span
[class value]
[:span {:class class} value]
;; "<span class='clj-lazy-seq'>)</span>"
)
;;; ** Renderers for basic Clojure forms **
; nil values are a distinct thing of their own
(extend-type nil
Renderable
(render [self]
(span-render self "clj-nil")))
(extend-type cljs.core/Keyword
Renderable
(render [self]
(span-render self "clj-keyword")))
(extend-type cljs.core/Symbol
Renderable
(render [self]
(span-render self "clj-symbol")))
; would be cool to be able to use meta data to switch between
; if meta ^:br is set, then convert \n to [:br] otherwise render the string as it is.
; however clojure does not support meta data for strings
(extend-type string
Renderable
(render [self]
(span-render self "clj-string")))
#_(extend-type char
Renderable
(render [self]
(span-render self "clj-char")))
(extend-type number
Renderable
(render [self]
(span-render self "clj-long")))
(extend-type boolean
Renderable
(render [self]
(span-render self "clj-boolean")))
;; When we render a map we will map over its entries, which will yield key-value pairs represented as vectors. To render
;; the map we render each of these key-value pairs with this helper function. They are rendered as list-likes with no
;; bracketing. These will then be assembled in to a list-like for the whole map by the IPersistentMap render function.
(defn- render-map-entry
[entry]
{:type :list-like
:open nil
:close nil
:separator [:span " "]
:items (map render entry)
:value (pr-str entry)})
(extend-type cljs.core/PersistentArrayMap
Renderable
(render [self]
{:type :list-like
:open (span "clj-map" "{")
:close (span "clj-map" "}")
:separator [:span ", "]
:items (map render-map-entry self)
:value (pr-str self)}))
(extend-type cljs.core/LazySeq
Renderable
(render [self]
{:type :list-like
:open (span "clj-lazy-seq" "(")
:close (span "clj-lazy-seq" ")")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
(extend-type cljs.core/PersistentVector
Renderable
(render [self]
{:type :list-like
:open (span "clj-vector" "[")
:close (span "clj-vector" "]")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
(extend-type cljs.core/PersistentHashSet
Renderable
(render [self]
{:type :list-like
:open (span "clj-set" "#{")
:close (span "clj-set" "}")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
;; This still needs to be implemented:
;; cljs.core/Range
;; cljs.core/Var
;; cljs.core/List
;; cljs.core/PersistentTreeMap
;; A default, catch-all renderer that takes anything we don't know what to do with and calls str on it.
;; https://grokbase.com/t/gg/clojure/121d2w4vhn/is-this-a-bug-extending-protocol-on-js-object
;; david nolan:
;; You should never extend js/Object.
;; It's unfortunate since this means we can't currently use js/Object to
;; provide default protocol implementations as we do in Clojure w/o fear of
;; conflicts with JavaScript libraries.
#_(extend-type js/Object
Renderable
(render [self]
(span-render self "clj-unkown")))
(extend-type default
Renderable
(render [self]
(println "unkown type: " (type self))
(span-render self "clj-unknown")))
|
41744
|
(ns pinkgorilla.ui.rendererCLJS
"equivalent to pinkgorilla.ui.renderer, but for clojurescript
renders clojurescript data structure to html"
(:require
[clojure.string :as string]
[pinkgorilla.ui.gorilla-renderable :refer [Renderable render]]))
;;; Helper functions
;; A lot of things render to an HTML span, with a class to mark the type of thing. This helper constructs the rendered
;; value in that case.
(defn- span-render
[thing class]
{:type :html
:content [:span {:class class} (pr-str thing)]
:value (pr-str thing)})
(defn- span
[class value]
[:span {:class class} value]
;; "<span class='clj-lazy-seq'>)</span>"
)
;;; ** Renderers for basic Clojure forms **
; nil values are a distinct thing of their own
(extend-type nil
Renderable
(render [self]
(span-render self "clj-nil")))
(extend-type cljs.core/Keyword
Renderable
(render [self]
(span-render self "clj-keyword")))
(extend-type cljs.core/Symbol
Renderable
(render [self]
(span-render self "clj-symbol")))
; would be cool to be able to use meta data to switch between
; if meta ^:br is set, then convert \n to [:br] otherwise render the string as it is.
; however clojure does not support meta data for strings
(extend-type string
Renderable
(render [self]
(span-render self "clj-string")))
#_(extend-type char
Renderable
(render [self]
(span-render self "clj-char")))
(extend-type number
Renderable
(render [self]
(span-render self "clj-long")))
(extend-type boolean
Renderable
(render [self]
(span-render self "clj-boolean")))
;; When we render a map we will map over its entries, which will yield key-value pairs represented as vectors. To render
;; the map we render each of these key-value pairs with this helper function. They are rendered as list-likes with no
;; bracketing. These will then be assembled in to a list-like for the whole map by the IPersistentMap render function.
(defn- render-map-entry
[entry]
{:type :list-like
:open nil
:close nil
:separator [:span " "]
:items (map render entry)
:value (pr-str entry)})
(extend-type cljs.core/PersistentArrayMap
Renderable
(render [self]
{:type :list-like
:open (span "clj-map" "{")
:close (span "clj-map" "}")
:separator [:span ", "]
:items (map render-map-entry self)
:value (pr-str self)}))
(extend-type cljs.core/LazySeq
Renderable
(render [self]
{:type :list-like
:open (span "clj-lazy-seq" "(")
:close (span "clj-lazy-seq" ")")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
(extend-type cljs.core/PersistentVector
Renderable
(render [self]
{:type :list-like
:open (span "clj-vector" "[")
:close (span "clj-vector" "]")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
(extend-type cljs.core/PersistentHashSet
Renderable
(render [self]
{:type :list-like
:open (span "clj-set" "#{")
:close (span "clj-set" "}")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
;; This still needs to be implemented:
;; cljs.core/Range
;; cljs.core/Var
;; cljs.core/List
;; cljs.core/PersistentTreeMap
;; A default, catch-all renderer that takes anything we don't know what to do with and calls str on it.
;; https://grokbase.com/t/gg/clojure/121d2w4vhn/is-this-a-bug-extending-protocol-on-js-object
;; <NAME>:
;; You should never extend js/Object.
;; It's unfortunate since this means we can't currently use js/Object to
;; provide default protocol implementations as we do in Clojure w/o fear of
;; conflicts with JavaScript libraries.
#_(extend-type js/Object
Renderable
(render [self]
(span-render self "clj-unkown")))
(extend-type default
Renderable
(render [self]
(println "unkown type: " (type self))
(span-render self "clj-unknown")))
| true |
(ns pinkgorilla.ui.rendererCLJS
"equivalent to pinkgorilla.ui.renderer, but for clojurescript
renders clojurescript data structure to html"
(:require
[clojure.string :as string]
[pinkgorilla.ui.gorilla-renderable :refer [Renderable render]]))
;;; Helper functions
;; A lot of things render to an HTML span, with a class to mark the type of thing. This helper constructs the rendered
;; value in that case.
(defn- span-render
[thing class]
{:type :html
:content [:span {:class class} (pr-str thing)]
:value (pr-str thing)})
(defn- span
[class value]
[:span {:class class} value]
;; "<span class='clj-lazy-seq'>)</span>"
)
;;; ** Renderers for basic Clojure forms **
; nil values are a distinct thing of their own
(extend-type nil
Renderable
(render [self]
(span-render self "clj-nil")))
(extend-type cljs.core/Keyword
Renderable
(render [self]
(span-render self "clj-keyword")))
(extend-type cljs.core/Symbol
Renderable
(render [self]
(span-render self "clj-symbol")))
; would be cool to be able to use meta data to switch between
; if meta ^:br is set, then convert \n to [:br] otherwise render the string as it is.
; however clojure does not support meta data for strings
(extend-type string
Renderable
(render [self]
(span-render self "clj-string")))
#_(extend-type char
Renderable
(render [self]
(span-render self "clj-char")))
(extend-type number
Renderable
(render [self]
(span-render self "clj-long")))
(extend-type boolean
Renderable
(render [self]
(span-render self "clj-boolean")))
;; When we render a map we will map over its entries, which will yield key-value pairs represented as vectors. To render
;; the map we render each of these key-value pairs with this helper function. They are rendered as list-likes with no
;; bracketing. These will then be assembled in to a list-like for the whole map by the IPersistentMap render function.
(defn- render-map-entry
[entry]
{:type :list-like
:open nil
:close nil
:separator [:span " "]
:items (map render entry)
:value (pr-str entry)})
(extend-type cljs.core/PersistentArrayMap
Renderable
(render [self]
{:type :list-like
:open (span "clj-map" "{")
:close (span "clj-map" "}")
:separator [:span ", "]
:items (map render-map-entry self)
:value (pr-str self)}))
(extend-type cljs.core/LazySeq
Renderable
(render [self]
{:type :list-like
:open (span "clj-lazy-seq" "(")
:close (span "clj-lazy-seq" ")")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
(extend-type cljs.core/PersistentVector
Renderable
(render [self]
{:type :list-like
:open (span "clj-vector" "[")
:close (span "clj-vector" "]")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
(extend-type cljs.core/PersistentHashSet
Renderable
(render [self]
{:type :list-like
:open (span "clj-set" "#{")
:close (span "clj-set" "}")
:separator [:span " "]
:items (map render self)
:value (pr-str self)}))
;; This still needs to be implemented:
;; cljs.core/Range
;; cljs.core/Var
;; cljs.core/List
;; cljs.core/PersistentTreeMap
;; A default, catch-all renderer that takes anything we don't know what to do with and calls str on it.
;; https://grokbase.com/t/gg/clojure/121d2w4vhn/is-this-a-bug-extending-protocol-on-js-object
;; PI:NAME:<NAME>END_PI:
;; You should never extend js/Object.
;; It's unfortunate since this means we can't currently use js/Object to
;; provide default protocol implementations as we do in Clojure w/o fear of
;; conflicts with JavaScript libraries.
#_(extend-type js/Object
Renderable
(render [self]
(span-render self "clj-unkown")))
(extend-type default
Renderable
(render [self]
(println "unkown type: " (type self))
(span-render self "clj-unknown")))
|
[
{
"context": "' (function) lookup fromm signature.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-06-09\"\n :version \"2017-10-11\"}",
"end": 294,
"score": 0.9471161365509033,
"start": 258,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] |
src/main/clojure/palisades/lakes/multix/sets/signature.clj
|
palisades-lakes/multimethod-experiments
| 5 |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.signature
{:doc "Manual 'method' (function) lookup fromm signature."
:author "palisades dot lakes at gmail dot com"
:since "2017-06-09"
:version "2017-10-11"}
(:require [palisades.lakes.multimethods.core :as d])
(:import [java.util Collections Set]
[palisades.lakes.bench.java.sets
DoubleInterval IntegerInterval]
[palisades.lakes.multimethods.java Signature2]))
;;----------------------------------------------------------------
(defn- intersectsII? [^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(defn- intersectsID? [^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defn- intersectsIS? [^IntegerInterval s0 ^Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defn- intersectsDI? [^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defn- intersectsDD? [^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defn- intersectsDS? [^DoubleInterval s0 ^Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defn- intersectsSI? [^Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defn- intersectsSD? [^Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(defn- intersectsSS? [^Set s0 ^Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
(defn- cant-intersect-exception [s0 s1]
(UnsupportedOperationException.
(print-str
"can't intersect" (class s0) "and" (class s1))))
;;----------------------------------------------------------------
(let [II (d/to-signature IntegerInterval IntegerInterval)
ID (d/to-signature IntegerInterval DoubleInterval)
IS (d/to-signature IntegerInterval Set)
DI (d/to-signature DoubleInterval IntegerInterval)
DD (d/to-signature DoubleInterval DoubleInterval)
DS (d/to-signature DoubleInterval Set)
SI (d/to-signature Set IntegerInterval)
SD (d/to-signature Set DoubleInterval)
SS (d/to-signature Set Set)]
(defn intersects? [s0 s1]
(let [^Signature2 s (d/signature s0 s1)]
;; very arbitrary assumptions about what s0 and s1 might
;; be and how they are related to the 'method' definitions
(cond
(.equals II s) (intersectsII? s0 s1)
(.equals ID s) (intersectsID? s0 s1)
(.isAssignableFrom IS s) (intersectsIS? s0 s1)
(.equals DI s) (intersectsDI? s0 s1)
(.equals DD s) (intersectsDD? s0 s1)
(.isAssignableFrom DS s) (intersectsDS? s0 s1)
(.isAssignableFrom SI s) (intersectsSI? s0 s1)
(.isAssignableFrom SD s) (intersectsSD? s0 s1)
(.isAssignableFrom SS s) (intersectsSS? s0 s1)
:else
(throw (cant-intersect-exception s0 s1))))))
;;----------------------------------------------------------------
|
92169
|
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.signature
{:doc "Manual 'method' (function) lookup fromm signature."
:author "<EMAIL>"
:since "2017-06-09"
:version "2017-10-11"}
(:require [palisades.lakes.multimethods.core :as d])
(:import [java.util Collections Set]
[palisades.lakes.bench.java.sets
DoubleInterval IntegerInterval]
[palisades.lakes.multimethods.java Signature2]))
;;----------------------------------------------------------------
(defn- intersectsII? [^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(defn- intersectsID? [^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defn- intersectsIS? [^IntegerInterval s0 ^Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defn- intersectsDI? [^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defn- intersectsDD? [^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defn- intersectsDS? [^DoubleInterval s0 ^Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defn- intersectsSI? [^Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defn- intersectsSD? [^Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(defn- intersectsSS? [^Set s0 ^Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
(defn- cant-intersect-exception [s0 s1]
(UnsupportedOperationException.
(print-str
"can't intersect" (class s0) "and" (class s1))))
;;----------------------------------------------------------------
(let [II (d/to-signature IntegerInterval IntegerInterval)
ID (d/to-signature IntegerInterval DoubleInterval)
IS (d/to-signature IntegerInterval Set)
DI (d/to-signature DoubleInterval IntegerInterval)
DD (d/to-signature DoubleInterval DoubleInterval)
DS (d/to-signature DoubleInterval Set)
SI (d/to-signature Set IntegerInterval)
SD (d/to-signature Set DoubleInterval)
SS (d/to-signature Set Set)]
(defn intersects? [s0 s1]
(let [^Signature2 s (d/signature s0 s1)]
;; very arbitrary assumptions about what s0 and s1 might
;; be and how they are related to the 'method' definitions
(cond
(.equals II s) (intersectsII? s0 s1)
(.equals ID s) (intersectsID? s0 s1)
(.isAssignableFrom IS s) (intersectsIS? s0 s1)
(.equals DI s) (intersectsDI? s0 s1)
(.equals DD s) (intersectsDD? s0 s1)
(.isAssignableFrom DS s) (intersectsDS? s0 s1)
(.isAssignableFrom SI s) (intersectsSI? s0 s1)
(.isAssignableFrom SD s) (intersectsSD? s0 s1)
(.isAssignableFrom SS s) (intersectsSS? s0 s1)
:else
(throw (cant-intersect-exception s0 s1))))))
;;----------------------------------------------------------------
| true |
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.signature
{:doc "Manual 'method' (function) lookup fromm signature."
:author "PI:EMAIL:<EMAIL>END_PI"
:since "2017-06-09"
:version "2017-10-11"}
(:require [palisades.lakes.multimethods.core :as d])
(:import [java.util Collections Set]
[palisades.lakes.bench.java.sets
DoubleInterval IntegerInterval]
[palisades.lakes.multimethods.java Signature2]))
;;----------------------------------------------------------------
(defn- intersectsII? [^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(defn- intersectsID? [^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defn- intersectsIS? [^IntegerInterval s0 ^Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defn- intersectsDI? [^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defn- intersectsDD? [^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(defn- intersectsDS? [^DoubleInterval s0 ^Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(defn- intersectsSI? [^Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(defn- intersectsSD? [^Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(defn- intersectsSS? [^Set s0 ^Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
(defn- cant-intersect-exception [s0 s1]
(UnsupportedOperationException.
(print-str
"can't intersect" (class s0) "and" (class s1))))
;;----------------------------------------------------------------
(let [II (d/to-signature IntegerInterval IntegerInterval)
ID (d/to-signature IntegerInterval DoubleInterval)
IS (d/to-signature IntegerInterval Set)
DI (d/to-signature DoubleInterval IntegerInterval)
DD (d/to-signature DoubleInterval DoubleInterval)
DS (d/to-signature DoubleInterval Set)
SI (d/to-signature Set IntegerInterval)
SD (d/to-signature Set DoubleInterval)
SS (d/to-signature Set Set)]
(defn intersects? [s0 s1]
(let [^Signature2 s (d/signature s0 s1)]
;; very arbitrary assumptions about what s0 and s1 might
;; be and how they are related to the 'method' definitions
(cond
(.equals II s) (intersectsII? s0 s1)
(.equals ID s) (intersectsID? s0 s1)
(.isAssignableFrom IS s) (intersectsIS? s0 s1)
(.equals DI s) (intersectsDI? s0 s1)
(.equals DD s) (intersectsDD? s0 s1)
(.isAssignableFrom DS s) (intersectsDS? s0 s1)
(.isAssignableFrom SI s) (intersectsSI? s0 s1)
(.isAssignableFrom SD s) (intersectsSD? s0 s1)
(.isAssignableFrom SS s) (intersectsSS? s0 s1)
:else
(throw (cant-intersect-exception s0 s1))))))
;;----------------------------------------------------------------
|
[
{
"context": " ~@body)))\n\n(defn random-address\n []\n (format \"%[email protected]\" (java.util.UUID/randomUUID)))\n\n(defn tarayo-mess",
"end": 1379,
"score": 0.9775002598762512,
"start": 1364,
"tag": "EMAIL",
"value": "\"%[email protected]"
}
] |
test/tarayo/test_helper.clj
|
toyokumo/tarayo
| 34 |
(ns tarayo.test-helper
(:require
[tarayo.mail.session :as session])
(:import
(com.dumbster.smtp
SimpleSmtpServer
SmtpMessage)
(com.sun.mail.smtp
SMTPTransport)))
(defrecord TestConnection
[session transport]
tarayo.core.ISMTPConnection
(send! [_this message] {:fn :send! :message message})
(connected? [_this] true)
(close [_this] nil))
(def ^:private default-test-smtp-server
{:host "localhost" :port 1025})
(defn test-connection
([] (test-connection default-test-smtp-server))
([smtp-server]
(->TestConnection
(session/make-session smtp-server)
:dummy-transport)))
(defn get-received-emails
[^SimpleSmtpServer server]
(->> (seq (.getReceivedEmails server))
(map (fn [^SmtpMessage msg]
{:from (.getHeaderValue msg "From")
:to (.getHeaderValue msg "To")
:subject (.getHeaderValue msg "Subject")
:body (.getBody msg)}))))
(defn get-received-email-by-from
[^SimpleSmtpServer server ^String from-addr]
(->> (get-received-emails server)
(some #(when (= from-addr (:from %)) %))))
(defmacro with-test-smtp-server
[[server-sym port-sym] & body]
`(with-open [~server-sym (SimpleSmtpServer/start SimpleSmtpServer/AUTO_SMTP_PORT)]
(let [~port-sym (.getPort ~server-sym)]
~@body)))
(defn random-address
[]
(format "%[email protected]" (java.util.UUID/randomUUID)))
(defn tarayo-message-id?
[x]
(if (sequential? x)
(tarayo-message-id? (first x))
(some? (re-seq #"^<[0-9A-Za-z]+\.[0-9]+@tarayo\..+>$" x))))
(defn tarayo-user-agent?
[x]
(if (sequential? x)
(tarayo-user-agent? (first x))
(some? (re-seq #"^tarayo/.+$" x))))
(defn ^SMTPTransport test-transport
[]
(proxy [SMTPTransport] [(session/make-session) (jakarta.mail.URLName. "localhost")]
(connect
([] true)
([_ _] true)
([_ _ _] true)
([_ _ _ _] true))
(getLastReturnCode [] 250)
(getLastServerResponse [] "250 OK\n")
(sendMessage [msg addrs] {:message msg :addresses addrs})))
|
94734
|
(ns tarayo.test-helper
(:require
[tarayo.mail.session :as session])
(:import
(com.dumbster.smtp
SimpleSmtpServer
SmtpMessage)
(com.sun.mail.smtp
SMTPTransport)))
(defrecord TestConnection
[session transport]
tarayo.core.ISMTPConnection
(send! [_this message] {:fn :send! :message message})
(connected? [_this] true)
(close [_this] nil))
(def ^:private default-test-smtp-server
{:host "localhost" :port 1025})
(defn test-connection
([] (test-connection default-test-smtp-server))
([smtp-server]
(->TestConnection
(session/make-session smtp-server)
:dummy-transport)))
(defn get-received-emails
[^SimpleSmtpServer server]
(->> (seq (.getReceivedEmails server))
(map (fn [^SmtpMessage msg]
{:from (.getHeaderValue msg "From")
:to (.getHeaderValue msg "To")
:subject (.getHeaderValue msg "Subject")
:body (.getBody msg)}))))
(defn get-received-email-by-from
[^SimpleSmtpServer server ^String from-addr]
(->> (get-received-emails server)
(some #(when (= from-addr (:from %)) %))))
(defmacro with-test-smtp-server
[[server-sym port-sym] & body]
`(with-open [~server-sym (SimpleSmtpServer/start SimpleSmtpServer/AUTO_SMTP_PORT)]
(let [~port-sym (.getPort ~server-sym)]
~@body)))
(defn random-address
[]
(format <EMAIL>" (java.util.UUID/randomUUID)))
(defn tarayo-message-id?
[x]
(if (sequential? x)
(tarayo-message-id? (first x))
(some? (re-seq #"^<[0-9A-Za-z]+\.[0-9]+@tarayo\..+>$" x))))
(defn tarayo-user-agent?
[x]
(if (sequential? x)
(tarayo-user-agent? (first x))
(some? (re-seq #"^tarayo/.+$" x))))
(defn ^SMTPTransport test-transport
[]
(proxy [SMTPTransport] [(session/make-session) (jakarta.mail.URLName. "localhost")]
(connect
([] true)
([_ _] true)
([_ _ _] true)
([_ _ _ _] true))
(getLastReturnCode [] 250)
(getLastServerResponse [] "250 OK\n")
(sendMessage [msg addrs] {:message msg :addresses addrs})))
| true |
(ns tarayo.test-helper
(:require
[tarayo.mail.session :as session])
(:import
(com.dumbster.smtp
SimpleSmtpServer
SmtpMessage)
(com.sun.mail.smtp
SMTPTransport)))
(defrecord TestConnection
[session transport]
tarayo.core.ISMTPConnection
(send! [_this message] {:fn :send! :message message})
(connected? [_this] true)
(close [_this] nil))
(def ^:private default-test-smtp-server
{:host "localhost" :port 1025})
(defn test-connection
([] (test-connection default-test-smtp-server))
([smtp-server]
(->TestConnection
(session/make-session smtp-server)
:dummy-transport)))
(defn get-received-emails
[^SimpleSmtpServer server]
(->> (seq (.getReceivedEmails server))
(map (fn [^SmtpMessage msg]
{:from (.getHeaderValue msg "From")
:to (.getHeaderValue msg "To")
:subject (.getHeaderValue msg "Subject")
:body (.getBody msg)}))))
(defn get-received-email-by-from
[^SimpleSmtpServer server ^String from-addr]
(->> (get-received-emails server)
(some #(when (= from-addr (:from %)) %))))
(defmacro with-test-smtp-server
[[server-sym port-sym] & body]
`(with-open [~server-sym (SimpleSmtpServer/start SimpleSmtpServer/AUTO_SMTP_PORT)]
(let [~port-sym (.getPort ~server-sym)]
~@body)))
(defn random-address
[]
(format PI:EMAIL:<EMAIL>END_PI" (java.util.UUID/randomUUID)))
(defn tarayo-message-id?
[x]
(if (sequential? x)
(tarayo-message-id? (first x))
(some? (re-seq #"^<[0-9A-Za-z]+\.[0-9]+@tarayo\..+>$" x))))
(defn tarayo-user-agent?
[x]
(if (sequential? x)
(tarayo-user-agent? (first x))
(some? (re-seq #"^tarayo/.+$" x))))
(defn ^SMTPTransport test-transport
[]
(proxy [SMTPTransport] [(session/make-session) (jakarta.mail.URLName. "localhost")]
(connect
([] true)
([_ _] true)
([_ _ _] true)
([_ _ _ _] true))
(getLastReturnCode [] 250)
(getLastServerResponse [] "250 OK\n")
(sendMessage [msg addrs] {:message msg :addresses addrs})))
|
[
{
"context": "s brepl]))\n\n(defn say-hello []\n (js/alert \"Hello, Arlo!\"))\n\n(defn ^:export epoch\n \"Returns the epoch of",
"end": 174,
"score": 0.9950882196426392,
"start": 170,
"tag": "NAME",
"value": "Arlo"
}
] |
leiningen/src/cljs/arlo/rocks/core.cljs
|
junjiemars/clojurescript_lessons
| 1 |
(ns arlo.rocks.core
(:require [clojure.string :as s]
[clojure.set :as c]
[arlo.rocks.brepl :as brepl]))
(defn say-hello []
(js/alert "Hello, Arlo!"))
(defn ^:export epoch
"Returns the epoch of now."
([] (.getTime (js/Date.)))
([s] (.getTime (js/Date. s))))
(defn ^:export str-epoch
"Returns the string representation of epoch t."
[t]
(str (js/Date. t)))
(defn ^:export set-item [k v]
(.setItem js/localStorage k
(.stringify js/JSON (clj->js v))))
(defn ^:export get-item [k]
(when-let [i (.getItem js/localStorage k)]
(js->clj (.parse js/JSON i) :keywordize-keys true)))
(defn ^:export remove-item [k]
(.removeItem js/localStorage k))
(defn ^:export length []
(.-length js/localStorage))
(defn ^:export clear-items
"Clear all items"
[]
(.clear js/localStorage))
(defn ^:export item-key
"Returns the key via the zero based n."
[n]
(.key js/localStorage n))
(defn ^:export as-json
"Returns json of clojure object."
[o] (clj->js o))
(defn init []
(if (and js/document
(.-getElementById js/document))
(let [m "Hello, from core::->brepl/init..."]
(brepl/init))))
|
71133
|
(ns arlo.rocks.core
(:require [clojure.string :as s]
[clojure.set :as c]
[arlo.rocks.brepl :as brepl]))
(defn say-hello []
(js/alert "Hello, <NAME>!"))
(defn ^:export epoch
"Returns the epoch of now."
([] (.getTime (js/Date.)))
([s] (.getTime (js/Date. s))))
(defn ^:export str-epoch
"Returns the string representation of epoch t."
[t]
(str (js/Date. t)))
(defn ^:export set-item [k v]
(.setItem js/localStorage k
(.stringify js/JSON (clj->js v))))
(defn ^:export get-item [k]
(when-let [i (.getItem js/localStorage k)]
(js->clj (.parse js/JSON i) :keywordize-keys true)))
(defn ^:export remove-item [k]
(.removeItem js/localStorage k))
(defn ^:export length []
(.-length js/localStorage))
(defn ^:export clear-items
"Clear all items"
[]
(.clear js/localStorage))
(defn ^:export item-key
"Returns the key via the zero based n."
[n]
(.key js/localStorage n))
(defn ^:export as-json
"Returns json of clojure object."
[o] (clj->js o))
(defn init []
(if (and js/document
(.-getElementById js/document))
(let [m "Hello, from core::->brepl/init..."]
(brepl/init))))
| true |
(ns arlo.rocks.core
(:require [clojure.string :as s]
[clojure.set :as c]
[arlo.rocks.brepl :as brepl]))
(defn say-hello []
(js/alert "Hello, PI:NAME:<NAME>END_PI!"))
(defn ^:export epoch
"Returns the epoch of now."
([] (.getTime (js/Date.)))
([s] (.getTime (js/Date. s))))
(defn ^:export str-epoch
"Returns the string representation of epoch t."
[t]
(str (js/Date. t)))
(defn ^:export set-item [k v]
(.setItem js/localStorage k
(.stringify js/JSON (clj->js v))))
(defn ^:export get-item [k]
(when-let [i (.getItem js/localStorage k)]
(js->clj (.parse js/JSON i) :keywordize-keys true)))
(defn ^:export remove-item [k]
(.removeItem js/localStorage k))
(defn ^:export length []
(.-length js/localStorage))
(defn ^:export clear-items
"Clear all items"
[]
(.clear js/localStorage))
(defn ^:export item-key
"Returns the key via the zero based n."
[n]
(.key js/localStorage n))
(defn ^:export as-json
"Returns json of clojure object."
[o] (clj->js o))
(defn init []
(if (and js/document
(.-getElementById js/document))
(let [m "Hello, from core::->brepl/init..."]
(brepl/init))))
|
[
{
"context": ";; Copyright (c) 2010 Tom Crayford,\n;;\n;; Redistribution and use in source and binar",
"end": 34,
"score": 0.9998175501823425,
"start": 22,
"tag": "NAME",
"value": "Tom Crayford"
}
] |
src/clojure_refactoring/support/replace.clj
|
tcrayford/clojure-refactoring
| 6 |
;; Copyright (c) 2010 Tom Crayford,
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(ns clojure-refactoring.support.replace
(:use [clojure-refactoring.support
source core paths])
(:require [clojure-refactoring.ast :as ast]))
(defn map-to-alist [m]
"Converts a clojure map to an alist suitable for emacs"
(map (fn [[k v]] (list k v)) m))
(def line-from-var (comp :line meta))
(defn build-replacement-map [ns f]
"Builds a replacement map for emacs for a given namespace"
(let [replacement (map f (parsley-from-cache ns))]
(if (= (parsley-from-cache ns) replacement)
nil
{:file (filename-from-ns ns)
:new-source (ast/ast->string
replacement)})))
(defn replace-namespaces [namespaces f]
"Replaces vars by calling f on each one."
(remove empty?
(map #(map-to-alist (build-replacement-map % f)) namespaces)))
(defn replace-callers [v f]
"Replaces all callers of a var by calling a function on them."
(replace-namespaces (namespaces-who-refer-to v) f))
|
10449
|
;; Copyright (c) 2010 <NAME>,
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(ns clojure-refactoring.support.replace
(:use [clojure-refactoring.support
source core paths])
(:require [clojure-refactoring.ast :as ast]))
(defn map-to-alist [m]
"Converts a clojure map to an alist suitable for emacs"
(map (fn [[k v]] (list k v)) m))
(def line-from-var (comp :line meta))
(defn build-replacement-map [ns f]
"Builds a replacement map for emacs for a given namespace"
(let [replacement (map f (parsley-from-cache ns))]
(if (= (parsley-from-cache ns) replacement)
nil
{:file (filename-from-ns ns)
:new-source (ast/ast->string
replacement)})))
(defn replace-namespaces [namespaces f]
"Replaces vars by calling f on each one."
(remove empty?
(map #(map-to-alist (build-replacement-map % f)) namespaces)))
(defn replace-callers [v f]
"Replaces all callers of a var by calling a function on them."
(replace-namespaces (namespaces-who-refer-to v) f))
| true |
;; Copyright (c) 2010 PI:NAME:<NAME>END_PI,
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;;
;; Redistributions in binary form must reproduce the above
;; copyright notice, this list of conditions and the following
;; disclaimer in the documentation and/or other materials provided
;; with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
;; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
;; COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
;; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
;; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
;; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
;; OF THE POSSIBILITY OF SUCH DAMAGE.
(ns clojure-refactoring.support.replace
(:use [clojure-refactoring.support
source core paths])
(:require [clojure-refactoring.ast :as ast]))
(defn map-to-alist [m]
"Converts a clojure map to an alist suitable for emacs"
(map (fn [[k v]] (list k v)) m))
(def line-from-var (comp :line meta))
(defn build-replacement-map [ns f]
"Builds a replacement map for emacs for a given namespace"
(let [replacement (map f (parsley-from-cache ns))]
(if (= (parsley-from-cache ns) replacement)
nil
{:file (filename-from-ns ns)
:new-source (ast/ast->string
replacement)})))
(defn replace-namespaces [namespaces f]
"Replaces vars by calling f on each one."
(remove empty?
(map #(map-to-alist (build-replacement-map % f)) namespaces)))
(defn replace-callers [v f]
"Replaces all callers of a var by calling a function on them."
(replace-namespaces (namespaces-who-refer-to v) f))
|
[
{
"context": ";; Copyright 2017 Alliander NV\n\n;; Licensed under the Apache License, ",
"end": 20,
"score": 0.6052778959274292,
"start": 18,
"tag": "NAME",
"value": "Al"
}
] |
elastic/test/com/alliander/chainsaw/elastic_test.clj
|
Alliander/chainsaw
| 1 |
;; Copyright 2017 Alliander NV
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;; http://www.apache.org/licenses/LICENSE-2.0
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns com.alliander.chainsaw.elastic-test
(:require [clojure.test :refer (deftest testing is)]
[clojurewerkz.elastisch.native :as es]
[clojurewerkz.elastisch.native.document :as esd]
[clojurewerkz.elastisch.native.index :as esi]
[taoensso.timbre :as log]
[com.alliander.chainsaw.core :as logging]
[com.alliander.chainsaw.elastic :as sut])
(:import [java.util UUID]
[java.util.concurrent CountDownLatch TimeUnit]))
;;; Tests without ElasticSearch
(deftest timbre->document-test
(let [appended (atom [])
appender {:enabled? true
:fn #(swap! appended conj (sut/timbre->document %))}
exception (ex-info "BOOM!" {})
context {:kont "ext"}]
(log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic appender})
(log/with-context context
(logging/infod ::hi {:my-param "hello"})
(log/warn exception "bye")))
(is (= [{:level :info
:namespace "com.alliander.chainsaw.elastic-test"
:error nil
:context context
:event ::hi
:parameters {:my-param "hello"}}
{:level :warn
:namespace "com.alliander.chainsaw.elastic-test"
:error (logging/codify-throwable exception)
:context context
:message "bye"}]
(map #(dissoc % :timestamp) @appended)))))
;;; Tests with ElasticSearch
(defn connect []
(es/connect [["localhost" 9300]] {"cluster.name" "elasticsearch"}))
(deftest ^:integration elastic-appender-test
(with-open [client (connect)]
(let [index (format "tcs-test-%s-logs" (rand-int Integer/MAX_VALUE))
correlation (str (UUID/randomUUID))
appended (promise)
appender (sut/elastic-appender client index
{:base-doc {:base "root"}
:flush-interval-seconds 1
:bulk-listener-after (fn [& _] (deliver appended true))})]
(testing "Writing logs to ElasticSearch"
(log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic appender})
(log/with-context {:hellodata-correlation correlation}
(logging/infod ::hi {:my-param "hello"})
(logging/warnd ::hello {:request-id "971429"})
(log/error (ex-info "BOOM!" {:ex 'data}) "something bad happened!"))))
(is (deref appended 2000 false))
(esi/flush client (str index "-*"))
(testing "Checking written logs from ElasticSearch"
(let [indexed (esd/search client (str index "-*") "log")]
(is (= [{:base "root"
:level "info"
:namespace "com.alliander.chainsaw.elastic-test"
:error {}
:context {:hellodata-correlation correlation}
:event "com.alliander.chainsaw.elastic-test/hi"
:parameters {:my-param "hello"}}
{:base "root"
:level "warn"
:namespace "com.alliander.chainsaw.elastic-test"
:error {}
:context {:hellodata-correlation correlation}
:event "com.alliander.chainsaw.elastic-test/hello"
:parameters {:request-id "971429"}}
{:base "root"
:level "error"
:namespace "com.alliander.chainsaw.elastic-test"
:error {:cause nil
:class "clojure.lang.ExceptionInfo"
:message "BOOM!"
:root-cause nil
:ex-data {:ex "data"}}
:context {:hellodata-correlation correlation}
:message "something bad happened!"}]
(->> indexed :hits :hits
(map :_source)
(sort-by :timestamp)
(map #(dissoc % :timestamp))))))))))
(deftest ^:loadtest elastic-appender-load-test
(with-open [client (connect)]
(let [index (format "tcs-test-%s-logs" (rand-int Integer/MAX_VALUE))
correlation (str (UUID/randomUUID))
iterations 10000
written (CountDownLatch. iterations)
appender (sut/elastic-appender client index {:base-doc {:app "chainsaw"}})
appender-fn (:fn appender)
wrapped (assoc appender :fn (fn [data]
(appender-fn data)
(.countDown written)))]
(testing "Writing logs to ElasticSearch"
(time (log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic wrapped})
(log/with-context {:hellodata-correlation correlation}
(dotimes [i iterations]
(logging/infod ::load-start)
(logging/warnd ::load {:iteration i})
(logging/debugd ::load-end))))))
(testing "Waiting for all logs to be written"
(is (time (.await written 5 TimeUnit/SECONDS)))))))
|
71110
|
;; Copyright 2017 <NAME>liander NV
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;; http://www.apache.org/licenses/LICENSE-2.0
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns com.alliander.chainsaw.elastic-test
(:require [clojure.test :refer (deftest testing is)]
[clojurewerkz.elastisch.native :as es]
[clojurewerkz.elastisch.native.document :as esd]
[clojurewerkz.elastisch.native.index :as esi]
[taoensso.timbre :as log]
[com.alliander.chainsaw.core :as logging]
[com.alliander.chainsaw.elastic :as sut])
(:import [java.util UUID]
[java.util.concurrent CountDownLatch TimeUnit]))
;;; Tests without ElasticSearch
(deftest timbre->document-test
(let [appended (atom [])
appender {:enabled? true
:fn #(swap! appended conj (sut/timbre->document %))}
exception (ex-info "BOOM!" {})
context {:kont "ext"}]
(log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic appender})
(log/with-context context
(logging/infod ::hi {:my-param "hello"})
(log/warn exception "bye")))
(is (= [{:level :info
:namespace "com.alliander.chainsaw.elastic-test"
:error nil
:context context
:event ::hi
:parameters {:my-param "hello"}}
{:level :warn
:namespace "com.alliander.chainsaw.elastic-test"
:error (logging/codify-throwable exception)
:context context
:message "bye"}]
(map #(dissoc % :timestamp) @appended)))))
;;; Tests with ElasticSearch
(defn connect []
(es/connect [["localhost" 9300]] {"cluster.name" "elasticsearch"}))
(deftest ^:integration elastic-appender-test
(with-open [client (connect)]
(let [index (format "tcs-test-%s-logs" (rand-int Integer/MAX_VALUE))
correlation (str (UUID/randomUUID))
appended (promise)
appender (sut/elastic-appender client index
{:base-doc {:base "root"}
:flush-interval-seconds 1
:bulk-listener-after (fn [& _] (deliver appended true))})]
(testing "Writing logs to ElasticSearch"
(log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic appender})
(log/with-context {:hellodata-correlation correlation}
(logging/infod ::hi {:my-param "hello"})
(logging/warnd ::hello {:request-id "971429"})
(log/error (ex-info "BOOM!" {:ex 'data}) "something bad happened!"))))
(is (deref appended 2000 false))
(esi/flush client (str index "-*"))
(testing "Checking written logs from ElasticSearch"
(let [indexed (esd/search client (str index "-*") "log")]
(is (= [{:base "root"
:level "info"
:namespace "com.alliander.chainsaw.elastic-test"
:error {}
:context {:hellodata-correlation correlation}
:event "com.alliander.chainsaw.elastic-test/hi"
:parameters {:my-param "hello"}}
{:base "root"
:level "warn"
:namespace "com.alliander.chainsaw.elastic-test"
:error {}
:context {:hellodata-correlation correlation}
:event "com.alliander.chainsaw.elastic-test/hello"
:parameters {:request-id "971429"}}
{:base "root"
:level "error"
:namespace "com.alliander.chainsaw.elastic-test"
:error {:cause nil
:class "clojure.lang.ExceptionInfo"
:message "BOOM!"
:root-cause nil
:ex-data {:ex "data"}}
:context {:hellodata-correlation correlation}
:message "something bad happened!"}]
(->> indexed :hits :hits
(map :_source)
(sort-by :timestamp)
(map #(dissoc % :timestamp))))))))))
(deftest ^:loadtest elastic-appender-load-test
(with-open [client (connect)]
(let [index (format "tcs-test-%s-logs" (rand-int Integer/MAX_VALUE))
correlation (str (UUID/randomUUID))
iterations 10000
written (CountDownLatch. iterations)
appender (sut/elastic-appender client index {:base-doc {:app "chainsaw"}})
appender-fn (:fn appender)
wrapped (assoc appender :fn (fn [data]
(appender-fn data)
(.countDown written)))]
(testing "Writing logs to ElasticSearch"
(time (log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic wrapped})
(log/with-context {:hellodata-correlation correlation}
(dotimes [i iterations]
(logging/infod ::load-start)
(logging/warnd ::load {:iteration i})
(logging/debugd ::load-end))))))
(testing "Waiting for all logs to be written"
(is (time (.await written 5 TimeUnit/SECONDS)))))))
| true |
;; Copyright 2017 PI:NAME:<NAME>END_PIliander NV
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;; http://www.apache.org/licenses/LICENSE-2.0
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns com.alliander.chainsaw.elastic-test
(:require [clojure.test :refer (deftest testing is)]
[clojurewerkz.elastisch.native :as es]
[clojurewerkz.elastisch.native.document :as esd]
[clojurewerkz.elastisch.native.index :as esi]
[taoensso.timbre :as log]
[com.alliander.chainsaw.core :as logging]
[com.alliander.chainsaw.elastic :as sut])
(:import [java.util UUID]
[java.util.concurrent CountDownLatch TimeUnit]))
;;; Tests without ElasticSearch
(deftest timbre->document-test
(let [appended (atom [])
appender {:enabled? true
:fn #(swap! appended conj (sut/timbre->document %))}
exception (ex-info "BOOM!" {})
context {:kont "ext"}]
(log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic appender})
(log/with-context context
(logging/infod ::hi {:my-param "hello"})
(log/warn exception "bye")))
(is (= [{:level :info
:namespace "com.alliander.chainsaw.elastic-test"
:error nil
:context context
:event ::hi
:parameters {:my-param "hello"}}
{:level :warn
:namespace "com.alliander.chainsaw.elastic-test"
:error (logging/codify-throwable exception)
:context context
:message "bye"}]
(map #(dissoc % :timestamp) @appended)))))
;;; Tests with ElasticSearch
(defn connect []
(es/connect [["localhost" 9300]] {"cluster.name" "elasticsearch"}))
(deftest ^:integration elastic-appender-test
(with-open [client (connect)]
(let [index (format "tcs-test-%s-logs" (rand-int Integer/MAX_VALUE))
correlation (str (UUID/randomUUID))
appended (promise)
appender (sut/elastic-appender client index
{:base-doc {:base "root"}
:flush-interval-seconds 1
:bulk-listener-after (fn [& _] (deliver appended true))})]
(testing "Writing logs to ElasticSearch"
(log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic appender})
(log/with-context {:hellodata-correlation correlation}
(logging/infod ::hi {:my-param "hello"})
(logging/warnd ::hello {:request-id "971429"})
(log/error (ex-info "BOOM!" {:ex 'data}) "something bad happened!"))))
(is (deref appended 2000 false))
(esi/flush client (str index "-*"))
(testing "Checking written logs from ElasticSearch"
(let [indexed (esd/search client (str index "-*") "log")]
(is (= [{:base "root"
:level "info"
:namespace "com.alliander.chainsaw.elastic-test"
:error {}
:context {:hellodata-correlation correlation}
:event "com.alliander.chainsaw.elastic-test/hi"
:parameters {:my-param "hello"}}
{:base "root"
:level "warn"
:namespace "com.alliander.chainsaw.elastic-test"
:error {}
:context {:hellodata-correlation correlation}
:event "com.alliander.chainsaw.elastic-test/hello"
:parameters {:request-id "971429"}}
{:base "root"
:level "error"
:namespace "com.alliander.chainsaw.elastic-test"
:error {:cause nil
:class "clojure.lang.ExceptionInfo"
:message "BOOM!"
:root-cause nil
:ex-data {:ex "data"}}
:context {:hellodata-correlation correlation}
:message "something bad happened!"}]
(->> indexed :hits :hits
(map :_source)
(sort-by :timestamp)
(map #(dissoc % :timestamp))))))))))
(deftest ^:loadtest elastic-appender-load-test
(with-open [client (connect)]
(let [index (format "tcs-test-%s-logs" (rand-int Integer/MAX_VALUE))
correlation (str (UUID/randomUUID))
iterations 10000
written (CountDownLatch. iterations)
appender (sut/elastic-appender client index {:base-doc {:app "chainsaw"}})
appender-fn (:fn appender)
wrapped (assoc appender :fn (fn [data]
(appender-fn data)
(.countDown written)))]
(testing "Writing logs to ElasticSearch"
(time (log/with-config (assoc log/*config*
:middleware [logging/logd-middleware]
:appenders {:elastic wrapped})
(log/with-context {:hellodata-correlation correlation}
(dotimes [i iterations]
(logging/infod ::load-start)
(logging/warnd ::load {:iteration i})
(logging/debugd ::load-end))))))
(testing "Waiting for all logs to be written"
(is (time (.await written 5 TimeUnit/SECONDS)))))))
|
[
{
"context": ";; Copyright © 2015-2020 Esko Luontola\n;; This software is released under the Apache Lic",
"end": 38,
"score": 0.9998838305473328,
"start": 25,
"tag": "NAME",
"value": "Esko Luontola"
}
] |
src/territory_bro/events.clj
|
orfjackal/territory-bro
| 2 |
;; Copyright © 2015-2020 Esko Luontola
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.events
(:require [medley.core :refer [map-keys]]
[schema-refined.core :as refined]
[schema-tools.core :as tools]
[schema.coerce :as coerce]
[schema.core :as s]
[territory-bro.domain.congregation :as congregation]
[territory-bro.infra.json :as json])
(:import (java.time Instant)
(java.util UUID)))
(defn- enrich-event [event command current-time]
(let [{:command/keys [user system]} command]
(-> event
(assoc :event/time current-time)
(cond->
user (assoc :event/user user)
system (assoc :event/system system)))))
(defn enrich-events [command {:keys [now]} events]
(assert (some? now))
(let [current-time (now)]
(map #(enrich-event % command current-time) events)))
(def ^:private key-order
(->> [:event/type
:event/transient?
:event/user
:event/system
:event/time
:event/stream-id
:event/stream-revision
:event/global-revision]
(map-indexed (fn [idx k]
[k idx]))
(into {})))
(defn- key-comparator [x y]
(compare [(get key-order x 100) x]
[(get key-order y 100) y]))
(defn sorted-keys [event]
(when event
(into (sorted-map-by key-comparator)
event)))
;;;; Schemas
(s/defschema BaseEvent
{(s/optional-key :event/stream-id) UUID
(s/optional-key :event/stream-revision) s/Int
(s/optional-key :event/global-revision) s/Int
:event/type s/Keyword
(s/optional-key :event/time) Instant
(s/optional-key :event/user) UUID
(s/optional-key :event/system) s/Str})
(s/defschema GisSyncEvent
(assoc BaseEvent
(s/optional-key :gis-change/id) s/Int))
;;; Congregation
(s/defschema CongregationCreated
(assoc BaseEvent
:event/type (s/eq :congregation.event/congregation-created)
:congregation/id UUID
:congregation/name s/Str
:congregation/schema-name s/Str))
(s/defschema CongregationRenamed
(assoc BaseEvent
:event/type (s/eq :congregation.event/congregation-renamed)
:congregation/id UUID
:congregation/name s/Str))
(s/defschema PermissionId
(apply s/enum congregation/all-permissions))
(s/defschema PermissionGranted
(assoc BaseEvent
:event/type (s/eq :congregation.event/permission-granted)
:congregation/id UUID
:user/id UUID
:permission/id PermissionId))
(s/defschema PermissionRevoked
(assoc BaseEvent
:event/type (s/eq :congregation.event/permission-revoked)
:congregation/id UUID
:user/id UUID
:permission/id PermissionId))
(s/defschema GisUserCreated
(assoc BaseEvent
:event/type (s/eq :congregation.event/gis-user-created)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str
:gis-user/password s/Str))
(s/defschema GisUserDeleted
(assoc BaseEvent
:event/type (s/eq :congregation.event/gis-user-deleted)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
;;; Territory
(s/defschema TerritoryDefined
(assoc GisSyncEvent
:event/type (s/eq :territory.event/territory-defined)
:congregation/id UUID
:territory/id UUID
:territory/number s/Str
:territory/addresses s/Str
:territory/region s/Str
:territory/meta {s/Keyword json/Schema}
:territory/location s/Str))
(s/defschema TerritoryDeleted
(assoc GisSyncEvent
:event/type (s/eq :territory.event/territory-deleted)
:congregation/id UUID
:territory/id UUID))
;;; Region
(s/defschema RegionDefined
(assoc GisSyncEvent
:event/type (s/eq :region.event/region-defined)
:congregation/id UUID
:region/id UUID
:region/name s/Str
:region/location s/Str))
(s/defschema RegionDeleted
(assoc GisSyncEvent
:event/type (s/eq :region.event/region-deleted)
:congregation/id UUID
:region/id UUID))
;;; Congregation Boundary
(s/defschema CongregationBoundaryDefined
(assoc GisSyncEvent
:event/type (s/eq :congregation-boundary.event/congregation-boundary-defined)
:congregation/id UUID
:congregation-boundary/id UUID
:congregation-boundary/location s/Str))
(s/defschema CongregationBoundaryDeleted
(assoc GisSyncEvent
:event/type (s/eq :congregation-boundary.event/congregation-boundary-deleted)
:congregation/id UUID
:congregation-boundary/id UUID))
;;; Card Minimap Viewport
(s/defschema CardMinimapViewportDefined
(assoc GisSyncEvent
:event/type (s/eq :card-minimap-viewport.event/card-minimap-viewport-defined)
:congregation/id UUID
:card-minimap-viewport/id UUID
:card-minimap-viewport/location s/Str))
(s/defschema CardMinimapViewportDeleted
(assoc GisSyncEvent
:event/type (s/eq :card-minimap-viewport.event/card-minimap-viewport-deleted)
:congregation/id UUID
:card-minimap-viewport/id UUID))
;;; DB Admin
(s/defschema GisSchemaIsPresent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-schema-is-present)
:event/transient? (s/eq true)
:congregation/id UUID
:congregation/schema-name s/Str))
(s/defschema GisUserIsPresent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-user-is-present)
:event/transient? (s/eq true)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
(s/defschema GisUserIsAbsent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-user-is-absent)
:event/transient? (s/eq true)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
;;; Shares
(s/defschema ShareCreated
(assoc BaseEvent
:event/type (s/eq :share.event/share-created)
:share/id UUID
:share/key s/Str
:share/type (s/enum :link :qr-code)
:congregation/id UUID
:territory/id UUID))
(s/defschema ShareOpened
(assoc BaseEvent
:event/type (s/eq :share.event/share-opened)
:share/id UUID))
(def event-schemas
{:card-minimap-viewport.event/card-minimap-viewport-defined CardMinimapViewportDefined
:card-minimap-viewport.event/card-minimap-viewport-deleted CardMinimapViewportDeleted
:congregation-boundary.event/congregation-boundary-defined CongregationBoundaryDefined
:congregation-boundary.event/congregation-boundary-deleted CongregationBoundaryDeleted
:congregation.event/congregation-created CongregationCreated
:congregation.event/congregation-renamed CongregationRenamed
:congregation.event/gis-user-created GisUserCreated
:congregation.event/gis-user-deleted GisUserDeleted
:congregation.event/permission-granted PermissionGranted
:congregation.event/permission-revoked PermissionRevoked
:db-admin.event/gis-schema-is-present GisSchemaIsPresent
:db-admin.event/gis-user-is-absent GisUserIsAbsent
:db-admin.event/gis-user-is-present GisUserIsPresent
:region.event/region-defined RegionDefined
:region.event/region-deleted RegionDeleted
:share.event/share-created ShareCreated
:share.event/share-opened ShareOpened
:territory.event/territory-defined TerritoryDefined
:territory.event/territory-deleted TerritoryDeleted})
(s/defschema Event
(apply refined/dispatch-on :event/type (flatten (seq event-schemas))))
(defn- required-key [m k]
(map-keys #(if (= % (s/optional-key k))
k
%)
m))
(s/defschema EnrichedEvent
(-> BaseEvent
(required-key :event/time)
(assoc s/Any s/Any)))
;;;; Validation
(def ^:private event-validator (s/validator Event))
(defn validate-event [event]
(when-not (contains? event-schemas (:event/type event))
(throw (ex-info (str "Unknown event type " (pr-str (:event/type event)))
{:event event})))
(event-validator event))
(defn validate-events [events]
(doseq [event events]
(validate-event event))
events)
(def ^:private enriched-event-validator (s/validator EnrichedEvent))
(defn strict-validate-event [event]
(validate-event event)
(enriched-event-validator event))
(defn strict-validate-events [events]
(doseq [event events]
(strict-validate-event event))
events)
;;;; Serialization
(defn- string->instant [s]
(if (string? s)
(Instant/parse s)
s))
(def ^:private datestring-coercion-matcher
{Instant string->instant})
(defn- coercion-matcher [schema]
(or (datestring-coercion-matcher schema)
(coerce/string-coercion-matcher schema)))
(def ^:private coerce-event-commons
(coerce/coercer! (tools/open-schema BaseEvent) coercion-matcher))
(def ^:private coerce-event-specifics
(coerce/coercer! Event coercion-matcher))
(defn- coerce-event [event]
;; must coerce the common fields first, so that Event can
;; choose the right event schema based on the event type
(coerce-event-specifics (coerce-event-commons event)))
(defn json->event [json]
(when json
(coerce-event (json/read-value json))))
(defn event->json [event]
(json/write-value-as-string (strict-validate-event event)))
|
118217
|
;; Copyright © 2015-2020 <NAME>
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.events
(:require [medley.core :refer [map-keys]]
[schema-refined.core :as refined]
[schema-tools.core :as tools]
[schema.coerce :as coerce]
[schema.core :as s]
[territory-bro.domain.congregation :as congregation]
[territory-bro.infra.json :as json])
(:import (java.time Instant)
(java.util UUID)))
(defn- enrich-event [event command current-time]
(let [{:command/keys [user system]} command]
(-> event
(assoc :event/time current-time)
(cond->
user (assoc :event/user user)
system (assoc :event/system system)))))
(defn enrich-events [command {:keys [now]} events]
(assert (some? now))
(let [current-time (now)]
(map #(enrich-event % command current-time) events)))
(def ^:private key-order
(->> [:event/type
:event/transient?
:event/user
:event/system
:event/time
:event/stream-id
:event/stream-revision
:event/global-revision]
(map-indexed (fn [idx k]
[k idx]))
(into {})))
(defn- key-comparator [x y]
(compare [(get key-order x 100) x]
[(get key-order y 100) y]))
(defn sorted-keys [event]
(when event
(into (sorted-map-by key-comparator)
event)))
;;;; Schemas
(s/defschema BaseEvent
{(s/optional-key :event/stream-id) UUID
(s/optional-key :event/stream-revision) s/Int
(s/optional-key :event/global-revision) s/Int
:event/type s/Keyword
(s/optional-key :event/time) Instant
(s/optional-key :event/user) UUID
(s/optional-key :event/system) s/Str})
(s/defschema GisSyncEvent
(assoc BaseEvent
(s/optional-key :gis-change/id) s/Int))
;;; Congregation
(s/defschema CongregationCreated
(assoc BaseEvent
:event/type (s/eq :congregation.event/congregation-created)
:congregation/id UUID
:congregation/name s/Str
:congregation/schema-name s/Str))
(s/defschema CongregationRenamed
(assoc BaseEvent
:event/type (s/eq :congregation.event/congregation-renamed)
:congregation/id UUID
:congregation/name s/Str))
(s/defschema PermissionId
(apply s/enum congregation/all-permissions))
(s/defschema PermissionGranted
(assoc BaseEvent
:event/type (s/eq :congregation.event/permission-granted)
:congregation/id UUID
:user/id UUID
:permission/id PermissionId))
(s/defschema PermissionRevoked
(assoc BaseEvent
:event/type (s/eq :congregation.event/permission-revoked)
:congregation/id UUID
:user/id UUID
:permission/id PermissionId))
(s/defschema GisUserCreated
(assoc BaseEvent
:event/type (s/eq :congregation.event/gis-user-created)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str
:gis-user/password s/Str))
(s/defschema GisUserDeleted
(assoc BaseEvent
:event/type (s/eq :congregation.event/gis-user-deleted)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
;;; Territory
(s/defschema TerritoryDefined
(assoc GisSyncEvent
:event/type (s/eq :territory.event/territory-defined)
:congregation/id UUID
:territory/id UUID
:territory/number s/Str
:territory/addresses s/Str
:territory/region s/Str
:territory/meta {s/Keyword json/Schema}
:territory/location s/Str))
(s/defschema TerritoryDeleted
(assoc GisSyncEvent
:event/type (s/eq :territory.event/territory-deleted)
:congregation/id UUID
:territory/id UUID))
;;; Region
(s/defschema RegionDefined
(assoc GisSyncEvent
:event/type (s/eq :region.event/region-defined)
:congregation/id UUID
:region/id UUID
:region/name s/Str
:region/location s/Str))
(s/defschema RegionDeleted
(assoc GisSyncEvent
:event/type (s/eq :region.event/region-deleted)
:congregation/id UUID
:region/id UUID))
;;; Congregation Boundary
(s/defschema CongregationBoundaryDefined
(assoc GisSyncEvent
:event/type (s/eq :congregation-boundary.event/congregation-boundary-defined)
:congregation/id UUID
:congregation-boundary/id UUID
:congregation-boundary/location s/Str))
(s/defschema CongregationBoundaryDeleted
(assoc GisSyncEvent
:event/type (s/eq :congregation-boundary.event/congregation-boundary-deleted)
:congregation/id UUID
:congregation-boundary/id UUID))
;;; Card Minimap Viewport
(s/defschema CardMinimapViewportDefined
(assoc GisSyncEvent
:event/type (s/eq :card-minimap-viewport.event/card-minimap-viewport-defined)
:congregation/id UUID
:card-minimap-viewport/id UUID
:card-minimap-viewport/location s/Str))
(s/defschema CardMinimapViewportDeleted
(assoc GisSyncEvent
:event/type (s/eq :card-minimap-viewport.event/card-minimap-viewport-deleted)
:congregation/id UUID
:card-minimap-viewport/id UUID))
;;; DB Admin
(s/defschema GisSchemaIsPresent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-schema-is-present)
:event/transient? (s/eq true)
:congregation/id UUID
:congregation/schema-name s/Str))
(s/defschema GisUserIsPresent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-user-is-present)
:event/transient? (s/eq true)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
(s/defschema GisUserIsAbsent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-user-is-absent)
:event/transient? (s/eq true)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
;;; Shares
(s/defschema ShareCreated
(assoc BaseEvent
:event/type (s/eq :share.event/share-created)
:share/id UUID
:share/key s/Str
:share/type (s/enum :link :qr-code)
:congregation/id UUID
:territory/id UUID))
(s/defschema ShareOpened
(assoc BaseEvent
:event/type (s/eq :share.event/share-opened)
:share/id UUID))
(def event-schemas
{:card-minimap-viewport.event/card-minimap-viewport-defined CardMinimapViewportDefined
:card-minimap-viewport.event/card-minimap-viewport-deleted CardMinimapViewportDeleted
:congregation-boundary.event/congregation-boundary-defined CongregationBoundaryDefined
:congregation-boundary.event/congregation-boundary-deleted CongregationBoundaryDeleted
:congregation.event/congregation-created CongregationCreated
:congregation.event/congregation-renamed CongregationRenamed
:congregation.event/gis-user-created GisUserCreated
:congregation.event/gis-user-deleted GisUserDeleted
:congregation.event/permission-granted PermissionGranted
:congregation.event/permission-revoked PermissionRevoked
:db-admin.event/gis-schema-is-present GisSchemaIsPresent
:db-admin.event/gis-user-is-absent GisUserIsAbsent
:db-admin.event/gis-user-is-present GisUserIsPresent
:region.event/region-defined RegionDefined
:region.event/region-deleted RegionDeleted
:share.event/share-created ShareCreated
:share.event/share-opened ShareOpened
:territory.event/territory-defined TerritoryDefined
:territory.event/territory-deleted TerritoryDeleted})
(s/defschema Event
(apply refined/dispatch-on :event/type (flatten (seq event-schemas))))
(defn- required-key [m k]
(map-keys #(if (= % (s/optional-key k))
k
%)
m))
(s/defschema EnrichedEvent
(-> BaseEvent
(required-key :event/time)
(assoc s/Any s/Any)))
;;;; Validation
(def ^:private event-validator (s/validator Event))
(defn validate-event [event]
(when-not (contains? event-schemas (:event/type event))
(throw (ex-info (str "Unknown event type " (pr-str (:event/type event)))
{:event event})))
(event-validator event))
(defn validate-events [events]
(doseq [event events]
(validate-event event))
events)
(def ^:private enriched-event-validator (s/validator EnrichedEvent))
(defn strict-validate-event [event]
(validate-event event)
(enriched-event-validator event))
(defn strict-validate-events [events]
(doseq [event events]
(strict-validate-event event))
events)
;;;; Serialization
(defn- string->instant [s]
(if (string? s)
(Instant/parse s)
s))
(def ^:private datestring-coercion-matcher
{Instant string->instant})
(defn- coercion-matcher [schema]
(or (datestring-coercion-matcher schema)
(coerce/string-coercion-matcher schema)))
(def ^:private coerce-event-commons
(coerce/coercer! (tools/open-schema BaseEvent) coercion-matcher))
(def ^:private coerce-event-specifics
(coerce/coercer! Event coercion-matcher))
(defn- coerce-event [event]
;; must coerce the common fields first, so that Event can
;; choose the right event schema based on the event type
(coerce-event-specifics (coerce-event-commons event)))
(defn json->event [json]
(when json
(coerce-event (json/read-value json))))
(defn event->json [event]
(json/write-value-as-string (strict-validate-event event)))
| true |
;; Copyright © 2015-2020 PI:NAME:<NAME>END_PI
;; This software is released under the Apache License 2.0.
;; The license text is at http://www.apache.org/licenses/LICENSE-2.0
(ns territory-bro.events
(:require [medley.core :refer [map-keys]]
[schema-refined.core :as refined]
[schema-tools.core :as tools]
[schema.coerce :as coerce]
[schema.core :as s]
[territory-bro.domain.congregation :as congregation]
[territory-bro.infra.json :as json])
(:import (java.time Instant)
(java.util UUID)))
(defn- enrich-event [event command current-time]
(let [{:command/keys [user system]} command]
(-> event
(assoc :event/time current-time)
(cond->
user (assoc :event/user user)
system (assoc :event/system system)))))
(defn enrich-events [command {:keys [now]} events]
(assert (some? now))
(let [current-time (now)]
(map #(enrich-event % command current-time) events)))
(def ^:private key-order
(->> [:event/type
:event/transient?
:event/user
:event/system
:event/time
:event/stream-id
:event/stream-revision
:event/global-revision]
(map-indexed (fn [idx k]
[k idx]))
(into {})))
(defn- key-comparator [x y]
(compare [(get key-order x 100) x]
[(get key-order y 100) y]))
(defn sorted-keys [event]
(when event
(into (sorted-map-by key-comparator)
event)))
;;;; Schemas
(s/defschema BaseEvent
{(s/optional-key :event/stream-id) UUID
(s/optional-key :event/stream-revision) s/Int
(s/optional-key :event/global-revision) s/Int
:event/type s/Keyword
(s/optional-key :event/time) Instant
(s/optional-key :event/user) UUID
(s/optional-key :event/system) s/Str})
(s/defschema GisSyncEvent
(assoc BaseEvent
(s/optional-key :gis-change/id) s/Int))
;;; Congregation
(s/defschema CongregationCreated
(assoc BaseEvent
:event/type (s/eq :congregation.event/congregation-created)
:congregation/id UUID
:congregation/name s/Str
:congregation/schema-name s/Str))
(s/defschema CongregationRenamed
(assoc BaseEvent
:event/type (s/eq :congregation.event/congregation-renamed)
:congregation/id UUID
:congregation/name s/Str))
(s/defschema PermissionId
(apply s/enum congregation/all-permissions))
(s/defschema PermissionGranted
(assoc BaseEvent
:event/type (s/eq :congregation.event/permission-granted)
:congregation/id UUID
:user/id UUID
:permission/id PermissionId))
(s/defschema PermissionRevoked
(assoc BaseEvent
:event/type (s/eq :congregation.event/permission-revoked)
:congregation/id UUID
:user/id UUID
:permission/id PermissionId))
(s/defschema GisUserCreated
(assoc BaseEvent
:event/type (s/eq :congregation.event/gis-user-created)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str
:gis-user/password s/Str))
(s/defschema GisUserDeleted
(assoc BaseEvent
:event/type (s/eq :congregation.event/gis-user-deleted)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
;;; Territory
(s/defschema TerritoryDefined
(assoc GisSyncEvent
:event/type (s/eq :territory.event/territory-defined)
:congregation/id UUID
:territory/id UUID
:territory/number s/Str
:territory/addresses s/Str
:territory/region s/Str
:territory/meta {s/Keyword json/Schema}
:territory/location s/Str))
(s/defschema TerritoryDeleted
(assoc GisSyncEvent
:event/type (s/eq :territory.event/territory-deleted)
:congregation/id UUID
:territory/id UUID))
;;; Region
(s/defschema RegionDefined
(assoc GisSyncEvent
:event/type (s/eq :region.event/region-defined)
:congregation/id UUID
:region/id UUID
:region/name s/Str
:region/location s/Str))
(s/defschema RegionDeleted
(assoc GisSyncEvent
:event/type (s/eq :region.event/region-deleted)
:congregation/id UUID
:region/id UUID))
;;; Congregation Boundary
(s/defschema CongregationBoundaryDefined
(assoc GisSyncEvent
:event/type (s/eq :congregation-boundary.event/congregation-boundary-defined)
:congregation/id UUID
:congregation-boundary/id UUID
:congregation-boundary/location s/Str))
(s/defschema CongregationBoundaryDeleted
(assoc GisSyncEvent
:event/type (s/eq :congregation-boundary.event/congregation-boundary-deleted)
:congregation/id UUID
:congregation-boundary/id UUID))
;;; Card Minimap Viewport
(s/defschema CardMinimapViewportDefined
(assoc GisSyncEvent
:event/type (s/eq :card-minimap-viewport.event/card-minimap-viewport-defined)
:congregation/id UUID
:card-minimap-viewport/id UUID
:card-minimap-viewport/location s/Str))
(s/defschema CardMinimapViewportDeleted
(assoc GisSyncEvent
:event/type (s/eq :card-minimap-viewport.event/card-minimap-viewport-deleted)
:congregation/id UUID
:card-minimap-viewport/id UUID))
;;; DB Admin
(s/defschema GisSchemaIsPresent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-schema-is-present)
:event/transient? (s/eq true)
:congregation/id UUID
:congregation/schema-name s/Str))
(s/defschema GisUserIsPresent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-user-is-present)
:event/transient? (s/eq true)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
(s/defschema GisUserIsAbsent
(assoc BaseEvent
:event/type (s/eq :db-admin.event/gis-user-is-absent)
:event/transient? (s/eq true)
:congregation/id UUID
:user/id UUID
:gis-user/username s/Str))
;;; Shares
(s/defschema ShareCreated
(assoc BaseEvent
:event/type (s/eq :share.event/share-created)
:share/id UUID
:share/key s/Str
:share/type (s/enum :link :qr-code)
:congregation/id UUID
:territory/id UUID))
(s/defschema ShareOpened
(assoc BaseEvent
:event/type (s/eq :share.event/share-opened)
:share/id UUID))
(def event-schemas
{:card-minimap-viewport.event/card-minimap-viewport-defined CardMinimapViewportDefined
:card-minimap-viewport.event/card-minimap-viewport-deleted CardMinimapViewportDeleted
:congregation-boundary.event/congregation-boundary-defined CongregationBoundaryDefined
:congregation-boundary.event/congregation-boundary-deleted CongregationBoundaryDeleted
:congregation.event/congregation-created CongregationCreated
:congregation.event/congregation-renamed CongregationRenamed
:congregation.event/gis-user-created GisUserCreated
:congregation.event/gis-user-deleted GisUserDeleted
:congregation.event/permission-granted PermissionGranted
:congregation.event/permission-revoked PermissionRevoked
:db-admin.event/gis-schema-is-present GisSchemaIsPresent
:db-admin.event/gis-user-is-absent GisUserIsAbsent
:db-admin.event/gis-user-is-present GisUserIsPresent
:region.event/region-defined RegionDefined
:region.event/region-deleted RegionDeleted
:share.event/share-created ShareCreated
:share.event/share-opened ShareOpened
:territory.event/territory-defined TerritoryDefined
:territory.event/territory-deleted TerritoryDeleted})
(s/defschema Event
(apply refined/dispatch-on :event/type (flatten (seq event-schemas))))
(defn- required-key [m k]
(map-keys #(if (= % (s/optional-key k))
k
%)
m))
(s/defschema EnrichedEvent
(-> BaseEvent
(required-key :event/time)
(assoc s/Any s/Any)))
;;;; Validation
(def ^:private event-validator (s/validator Event))
(defn validate-event [event]
(when-not (contains? event-schemas (:event/type event))
(throw (ex-info (str "Unknown event type " (pr-str (:event/type event)))
{:event event})))
(event-validator event))
(defn validate-events [events]
(doseq [event events]
(validate-event event))
events)
(def ^:private enriched-event-validator (s/validator EnrichedEvent))
(defn strict-validate-event [event]
(validate-event event)
(enriched-event-validator event))
(defn strict-validate-events [events]
(doseq [event events]
(strict-validate-event event))
events)
;;;; Serialization
(defn- string->instant [s]
(if (string? s)
(Instant/parse s)
s))
(def ^:private datestring-coercion-matcher
{Instant string->instant})
(defn- coercion-matcher [schema]
(or (datestring-coercion-matcher schema)
(coerce/string-coercion-matcher schema)))
(def ^:private coerce-event-commons
(coerce/coercer! (tools/open-schema BaseEvent) coercion-matcher))
(def ^:private coerce-event-specifics
(coerce/coercer! Event coercion-matcher))
(defn- coerce-event [event]
;; must coerce the common fields first, so that Event can
;; choose the right event schema based on the event type
(coerce-event-specifics (coerce-event-commons event)))
(defn json->event [json]
(when json
(coerce-event (json/read-value json))))
(defn event->json [event]
(json/write-value-as-string (strict-validate-event event)))
|
[
{
"context": "ault \"grpc://localhost:50051\"]\n [nil \"--username USER\" \"Username\"\n :default \"test_user0\"]\n [nil \"-",
"end": 1151,
"score": 0.9728368520736694,
"start": 1147,
"tag": "USERNAME",
"value": "USER"
},
{
"context": "pc://localhost:50051\"]\n [nil \"--username USER\" \"Username\"\n :default \"test_user0\"]\n [nil \"--password P",
"end": 1162,
"score": 0.9084134101867676,
"start": 1154,
"tag": "USERNAME",
"value": "Username"
},
{
"context": " [nil \"--username USER\" \"Username\"\n :default \"test_user0\"]\n [nil \"--password PASS\" \"Password\"\n :defau",
"end": 1188,
"score": 0.9996551871299744,
"start": 1178,
"tag": "USERNAME",
"value": "test_user0"
},
{
"context": "me\"\n :default \"test_user0\"]\n [nil \"--password PASS\" \"Password\"\n :default \"MS9qrN8hFjlE\"]\n [\"-i\"",
"end": 1215,
"score": 0.9938334226608276,
"start": 1211,
"tag": "PASSWORD",
"value": "PASS"
},
{
"context": ":default \"test_user0\"]\n [nil \"--password PASS\" \"Password\"\n :default \"MS9qrN8hFjlE\"]\n [\"-i\" \"--id ID\" ",
"end": 1226,
"score": 0.9974338412284851,
"start": 1218,
"tag": "PASSWORD",
"value": "Password"
}
] |
examples/example02/client/cljs/src/example02/main.cljs
|
ghaskins/chaintool-gerrit
| 1 |
(ns example02.main
(:require [clojure.string :as string]
[cljs.nodejs :as nodejs]
[cljs.tools.cli :refer [parse-opts]]
[example02.core :as core]
[promesa.core :as p :include-macros true]))
(nodejs/enable-util-print!)
(def _commands
[["deploy"
{:fn core/deploy
:default-args #js {:partyA #js {:entity "foo"
:value 100}
:partyB #js {:entity "bar"
:value 100}}}]
["make-payment"
{:fn core/make-payment
:default-args #js {:partySrc "foo"
:partyDst "bar"
:amount 10}}]
["delete-account"
{:fn core/delete-account
:default-args #js {:id "foo"}}]
["check-balance"
{:fn core/check-balance
:default-args #js {:id "foo"}}]])
(def commands (into {} _commands))
(defn print-commands [] (->> commands keys vec print-str))
(def options
[[nil "--peer URL" "Peer URL"
:default "grpc://localhost:30303"]
[nil "--membersrvc URL" "Member services URL"
:default "grpc://localhost:50051"]
[nil "--username USER" "Username"
:default "test_user0"]
[nil "--password PASS" "Password"
:default "MS9qrN8hFjlE"]
["-i" "--id ID" "ChaincodeID as a path/url/name"]
["-c" "--command CMD" (str "One of " (print-commands))
:default "check-balance"
:validate [#(contains? commands %) (str "Supported commands: " (print-commands))]]
["-a" "--args ARGS" "JSON formatted arguments to submit"]
["-h" "--help"]])
(defn exit [status msg & rest]
(do
(apply println msg rest)
status))
(defn prep-usage [msg] (->> msg flatten (string/join \newline)))
(defn usage [options-summary]
(prep-usage ["Usage: example02 [options]"
""
"Options Summary:"
options-summary
""]))
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args options)
{:keys [id command args]} options]
(cond
(:help options)
(exit 0 (usage summary))
(not= errors nil)
(exit -1 "Error: " (string/join errors))
(nil? id)
(exit -1 "Error: Must specify a chaincodeID")
:else
(let [desc (commands command)
_args (if (nil? args) (:default-args desc) (.parse js/JSON args))]
(p/alet [{:keys [chain user]} (p/await (core/connect options))]
(println (str "Running " command "(" (.stringify js/JSON _args) ")"))
;; Run the subcommand funtion
((:fn desc) (assoc options :id id :args _args :chain chain :user user)))))))
(set! *main-cli-fn* -main)
|
34705
|
(ns example02.main
(:require [clojure.string :as string]
[cljs.nodejs :as nodejs]
[cljs.tools.cli :refer [parse-opts]]
[example02.core :as core]
[promesa.core :as p :include-macros true]))
(nodejs/enable-util-print!)
(def _commands
[["deploy"
{:fn core/deploy
:default-args #js {:partyA #js {:entity "foo"
:value 100}
:partyB #js {:entity "bar"
:value 100}}}]
["make-payment"
{:fn core/make-payment
:default-args #js {:partySrc "foo"
:partyDst "bar"
:amount 10}}]
["delete-account"
{:fn core/delete-account
:default-args #js {:id "foo"}}]
["check-balance"
{:fn core/check-balance
:default-args #js {:id "foo"}}]])
(def commands (into {} _commands))
(defn print-commands [] (->> commands keys vec print-str))
(def options
[[nil "--peer URL" "Peer URL"
:default "grpc://localhost:30303"]
[nil "--membersrvc URL" "Member services URL"
:default "grpc://localhost:50051"]
[nil "--username USER" "Username"
:default "test_user0"]
[nil "--password <PASSWORD>" "<PASSWORD>"
:default "MS9qrN8hFjlE"]
["-i" "--id ID" "ChaincodeID as a path/url/name"]
["-c" "--command CMD" (str "One of " (print-commands))
:default "check-balance"
:validate [#(contains? commands %) (str "Supported commands: " (print-commands))]]
["-a" "--args ARGS" "JSON formatted arguments to submit"]
["-h" "--help"]])
(defn exit [status msg & rest]
(do
(apply println msg rest)
status))
(defn prep-usage [msg] (->> msg flatten (string/join \newline)))
(defn usage [options-summary]
(prep-usage ["Usage: example02 [options]"
""
"Options Summary:"
options-summary
""]))
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args options)
{:keys [id command args]} options]
(cond
(:help options)
(exit 0 (usage summary))
(not= errors nil)
(exit -1 "Error: " (string/join errors))
(nil? id)
(exit -1 "Error: Must specify a chaincodeID")
:else
(let [desc (commands command)
_args (if (nil? args) (:default-args desc) (.parse js/JSON args))]
(p/alet [{:keys [chain user]} (p/await (core/connect options))]
(println (str "Running " command "(" (.stringify js/JSON _args) ")"))
;; Run the subcommand funtion
((:fn desc) (assoc options :id id :args _args :chain chain :user user)))))))
(set! *main-cli-fn* -main)
| true |
(ns example02.main
(:require [clojure.string :as string]
[cljs.nodejs :as nodejs]
[cljs.tools.cli :refer [parse-opts]]
[example02.core :as core]
[promesa.core :as p :include-macros true]))
(nodejs/enable-util-print!)
(def _commands
[["deploy"
{:fn core/deploy
:default-args #js {:partyA #js {:entity "foo"
:value 100}
:partyB #js {:entity "bar"
:value 100}}}]
["make-payment"
{:fn core/make-payment
:default-args #js {:partySrc "foo"
:partyDst "bar"
:amount 10}}]
["delete-account"
{:fn core/delete-account
:default-args #js {:id "foo"}}]
["check-balance"
{:fn core/check-balance
:default-args #js {:id "foo"}}]])
(def commands (into {} _commands))
(defn print-commands [] (->> commands keys vec print-str))
(def options
[[nil "--peer URL" "Peer URL"
:default "grpc://localhost:30303"]
[nil "--membersrvc URL" "Member services URL"
:default "grpc://localhost:50051"]
[nil "--username USER" "Username"
:default "test_user0"]
[nil "--password PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI"
:default "MS9qrN8hFjlE"]
["-i" "--id ID" "ChaincodeID as a path/url/name"]
["-c" "--command CMD" (str "One of " (print-commands))
:default "check-balance"
:validate [#(contains? commands %) (str "Supported commands: " (print-commands))]]
["-a" "--args ARGS" "JSON formatted arguments to submit"]
["-h" "--help"]])
(defn exit [status msg & rest]
(do
(apply println msg rest)
status))
(defn prep-usage [msg] (->> msg flatten (string/join \newline)))
(defn usage [options-summary]
(prep-usage ["Usage: example02 [options]"
""
"Options Summary:"
options-summary
""]))
(defn -main [& args]
(let [{:keys [options arguments errors summary]} (parse-opts args options)
{:keys [id command args]} options]
(cond
(:help options)
(exit 0 (usage summary))
(not= errors nil)
(exit -1 "Error: " (string/join errors))
(nil? id)
(exit -1 "Error: Must specify a chaincodeID")
:else
(let [desc (commands command)
_args (if (nil? args) (:default-args desc) (.parse js/JSON args))]
(p/alet [{:keys [chain user]} (p/await (core/connect options))]
(println (str "Running " command "(" (.stringify js/JSON _args) ")"))
;; Run the subcommand funtion
((:fn desc) (assoc options :id id :args _args :chain chain :user user)))))))
(set! *main-cli-fn* -main)
|
[
{
"context": "(println \"tjosan\")",
"end": 16,
"score": 0.9940678477287292,
"start": 10,
"tag": "NAME",
"value": "tjosan"
}
] |
Basics/ex01 - hello world/main.clj
|
hoppfull/Legacy-Clojure
| 0 |
(println "tjosan")
|
82973
|
(println "<NAME>")
| true |
(println "PI:NAME:<NAME>END_PI")
|
[
{
"context": ";; Copyright (c) 2011 Alfredo Di Napoli, https://github.com/CharlesStain/clj3D\n\n;; Permis",
"end": 39,
"score": 0.9998675584793091,
"start": 22,
"tag": "NAME",
"value": "Alfredo Di Napoli"
},
{
"context": "ht (c) 2011 Alfredo Di Napoli, https://github.com/CharlesStain/clj3D\n\n;; Permission is hereby granted, free of c",
"end": 72,
"score": 0.9963324069976807,
"start": 60,
"tag": "USERNAME",
"value": "CharlesStain"
}
] |
src/clj3D/fenvs.clj
|
adinapoli/clj3D
| 7 |
;; Copyright (c) 2011 Alfredo Di Napoli, https://github.com/CharlesStain/clj3D
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(ns clj3D.fenvs
(:refer-clojure :rename {+ core-+})
(:use
[matchure]
[clj3D curry math])
(:import
[clj3D Utilities]
[java.util LinkedList]
[com.jme3.math Vector3f Vector2f ColorRGBA Quaternion Transform]
[com.jme3.asset AssetManager]
[com.jme3.system JmeSystem]
[com.jme3.material Material RenderState$FaceCullMode]
[com.jme3.texture Texture]
[com.jme3.scene.shape Box Line Sphere Cylinder Torus Quad Dome]
[com.jme3.scene Node Geometry Spatial Mesh Mesh$Mode VertexBuffer VertexBuffer$Type]
[jme3tools.optimize GeometryBatchFactory]
[com.jme3.asset.plugins FileLocator]))
;;For performance tweaking. Just ignore this.
(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Graphics stuff.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} colors
{ :gray (ColorRGBA/Gray),
:green (ColorRGBA/Green),
:black (ColorRGBA/Black),
:blue (ColorRGBA/Blue),
:brown (ColorRGBA/Brown),
:cyan (ColorRGBA/Cyan),
:magenta (ColorRGBA/Magenta),
:orange (ColorRGBA/Orange),
:purple (ColorRGBA. 0.5 0.0 0.8 1.0),
:pink (ColorRGBA/Pink),
:white (ColorRGBA/White),
:red (ColorRGBA/Red),
:yellow (ColorRGBA/Yellow)})
(def ^{:private true} default-color (ColorRGBA/LightGray))
(def ^{:private true} asset-manager
(JmeSystem/newAssetManager
(.getResource (.getContextClassLoader (Thread/currentThread))
"com/jme3/asset/Desktop.cfg")))
(defn- default-material []
(doto (Material. asset-manager "Common/MatDefs/Light/Lighting.j3md")
(.setBoolean "UseMaterialColors" true)
(.setColor "Ambient" (get colors :black))
(.setColor "Diffuse" default-color)
(.setColor "Specular" (get colors :white))
(.setFloat "Shininess" 10)))
(defn- unlit-material []
(doto (Material. asset-manager "Common/MatDefs/Misc/Unshaded.j3md")
(.setColor "Color" default-color)))
(defn- textured-material [texture]
(doto (Material. asset-manager "Common/MatDefs/Misc/Unshaded.j3md")
(.setTexture "ColorMap" texture)))
(defn- colored-material
[color-keyword]
(doto (Material. asset-manager "Common/MatDefs/Light/Lighting.j3md")
(.setBoolean "UseMaterialColors" true)
(.setColor "Ambient" (get colors :black))
(.setColor "Diffuse" (get colors color-keyword))
(.setColor "Specular" (get colors :white))
(.setFloat "Shininess" 10)))
(defhigh color
"Change the color of the shape, then return the spatial itself."
[color-symbol ^Spatial object]
(.setMaterial object (colored-material color-symbol))
object)
;;For custom Obj files
(.registerLocator ^AssetManager asset-manager
(str (. System getProperty "user.dir") "/models")
"com.jme3.asset.plugins.FileLocator")
;;For user textures
(.registerLocator ^AssetManager asset-manager
(str (. System getProperty "user.dir") "/textures")
"com.jme3.asset.plugins.FileLocator")
(defn- optimize
"Optimize a Spatial. Internal use."
[spatial]
(doto ^Node (GeometryBatchFactory/optimize spatial)
(.setName "structured")))
(defhigh merge-geometries
[geom1 geom2]
(let [out-mesh (Mesh.)]
(GeometryBatchFactory/mergeGeometries [geom1 geom2] out-mesh)
(doto (Geometry. "structured" out-mesh)
(optimize)
(.setMaterial (default-material)))))
(extend-protocol Addable
Geometry
(+ [g1 g2] (merge-geometries g1 g2)))
(defn mknode
"It takes a list or an undefined number of geometries and put them into
a single node. Materials are preserverd."
[& objs]
(let [flattened-args (flatten objs)
new-node (Node. "node")]
(doseq [geom flattened-args] (.attachChild new-node geom))
(optimize new-node)))
(extend-protocol Addable
Node
(+ [nd1 nd2] (mknode nd1 nd2)))
;; i.e the original STRUCT from Plasm
(defn struct2
"Merge all the input given meshs into a single one.
It's a fairly powerful function, since its input can be
an arbitrary number of functions and geometrical object.
The input is visited from right to left, applying (if present)
the functions to the Geometry objects. The only constrain is
that the result must be a Geometry object. You can even pass a
sequence of transformation/geometries.
Usage:
(struct2 (cube 1) (t 1 1) (sphere 1) -> returns a translated sphere joined
with a cube.
(struct 2 [(color :red) (cube 1)]) -> returns a red cube."
[& args]
(let [flattened-args (flatten args)
rev-seq (reverse flattened-args)]
(reduce (fn [x y]
(cond-match
[[com.jme3.scene.Spatial com.jme3.scene.Spatial] [x y]] (+ x y)
[[com.jme3.scene.Spatial ?func] [x y]] (func x)
[[?func com.jme3.scene.Spatial] [x y]] (func x)
[? [x y]] (throw (IllegalArgumentException. "Invalid input for struct")))) rev-seq)))
(defhigh attach
"Attach a child to the given node."
[^Node node child]
(.attachChild node child))
(defhigh t
"Translate function. High order function.
Usage:
(t 1 2.0 (cube 1)) -> move the cube from <0,0,0> to <2.0,0,0>
(t [1 2] [3.0 2.0] (cube 1) -> move the cube to <3.0,2.0,0>"
[axes value geom]
(let [cloned ^Spatial (.clone ^Spatial geom)]
(doto ^Node cloned
(.move (jvector axes value)))))
(defhigh r
"Rotate function. High order function."
[axis rotation spatial]
(let [cloned ^Spatial (.clone ^Spatial spatial)
rotation-pivot (Node.)
quaternion (Quaternion.)]
(.attachChild rotation-pivot cloned)
(.setLocalTranslation rotation-pivot (Vector3f/ZERO))
(.fromAngleAxis quaternion rotation (jvector axis 1.0))
(.setLocalRotation rotation-pivot quaternion)
(let [world-transform ^Transform (.getWorldTransform rotation-pivot)
prev-transform ^Transform (.getLocalTransform ^Spatial cloned)]
(doto ^Spatial cloned
(.setLocalTransform (.combineWithParent prev-transform world-transform))))))
(defn- mirror
[axis node]
(let [children (.getChildren node)
queue (LinkedList.)]
(.addAll queue children)
(Utilities/traverseAndMirror axis queue)))
(defhigh s
"Scale function. High order function.
Usage:
(s 1 0.5 (cube 1)) -> scale 50% of cube x-side
(s [1 2] [0.5 0.7] (cube 1)) -> scale 50% x and 70% y."
[axes value geom]
(let [cloned ^Spatial (.clone ^Spatial geom)]
(cond-match
[-1 value]
(do
(mirror axes cloned)
cloned)
[java.lang.Integer axes]
(let [av-map (hash-map (dec axes) value)]
(doto ^Node cloned
(.scale (get av-map 0 1.0) (get av-map 1 1.0) (get av-map 2 1.0))))
[clojure.lang.IPersistentCollection axes]
(let [av-map (reduce into (map hash-map (map dec axes) value))]
(doto ^Node cloned
(.scale (get av-map 0 1.0) (get av-map 1 1.0) (get av-map 2 1.0))))
[? axes] (throw (IllegalArgumentException. "Invalid input for scale")))))
(defhigh skeleton
[dim geom]
(cond-match
[0 dim]
(let [mesh (.getMesh ^Geometry geom)]
(.setMode mesh Mesh$Mode/Points)
(.setPointSize mesh 5.0)
(.updateBound mesh)
(.setStatic mesh)
(doto ^Geometry (Geometry. "skeleton-0" mesh)
(.setMaterial (unlit-material))
(.. getMaterial (setColor "Color" ColorRGBA/Red))))
[1 dim]
(doto ^Geometry geom
(.setMaterial (unlit-material))
(.. getMaterial getAdditionalRenderState (setWireframe true)))
[? dim] geom))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; PRIMITIVES
;; NOTE: Apparently PLaSM and JMonkey use the same coordinate system, but in
;; jmonkey the camera is rotated. Need to fix this.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cuboid
"Returns a new x*y*z cuboid with bottom-left corner in (0,0,0)"
[x y z]
(let [[px py pz] (map #(/ %1 2.0) [x y z])
box (Box. (Vector3f. px py pz) px py pz)
cuboid (Geometry. "cuboid" box)]
(.setMaterial cuboid (default-material))
(mknode cuboid)))
(defn cube
"Returns a new n*n*n cube with bottom-left corner in (0,0,0)"
[side]
(mknode (cuboid side side side)))
(defn hexaedron [] (mknode (cube 1)))
(defn line
"New in clj3D. Draw a simple line from start to end"
[[x1 y1 & z1] [x2 y2 & z2]]
(let [z1 (if (seq z1) (first z1) 0)
z2 (if (seq z2) (first z2) 0)
line-mesh (Line. (Vector3f. x1 y1 z1) (Vector3f. x2 y2 z2))
line-geom (Geometry. "line" line-mesh)]
(.setMaterial line-geom (unlit-material))
(mknode line-geom)))
(defn sphere
"Returns a new sphere in (0,0,0).
(sphere radius) -> returns a sphere of the given radius
(sphere radius x y) -> returns a sphere composed by x and
y segment, of the given radius."
([radius]
(let [sphere-mesh (Sphere. 50 50 radius)
sphere (Geometry. "sphere" sphere-mesh)]
(.setMaterial sphere (default-material))
(mknode sphere)))
([radius z-seg r-seg]
(let [sphere-mesh (Sphere. z-seg r-seg radius)
sphere (Geometry. "sphere" sphere-mesh)]
(.setMaterial sphere (default-material))
(mknode sphere))))
(defn cylinder
"Returns a new cylinder in (0,0,0).
(cylinder radius height) -> returns a cylinder of the given radius and height
(cylinder radius height x y) -> returns a cylinder composed by x and
y segment, of the given radius and height."
([radius height]
(let [cylinder-mesh (Cylinder. 50 50 radius height true)
cylinder (Geometry. "cylinder" cylinder-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cylinder)
(.setMaterial (default-material))))))
([radius height z-seg r-seg]
(let [cylinder-mesh (Cylinder. z-seg r-seg radius height true)
cylinder (Geometry. "cylinder" cylinder-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cylinder)
(.setMaterial (default-material)))))))
(defn cone
"Returns a new cone in (0,0,0)"
([radius height]
(let [cone-mesh (Cylinder. 50 50 0 radius height true false)
cone (Geometry. "cone" cone-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cone)
(.setMaterial (default-material))))))
([radius height z-seg r-seg]
(let [cone-mesh (Cylinder. z-seg r-seg 0 radius height true false)
cone (Geometry. "cone" cone-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cone)
(.setMaterial (default-material)))))))
(defn torus
"Returns a new torus in (0,0,0).
(torus r1 r2) -> returns a torus of the given radius r1 and r2
(torus r1 r2 x y) -> returns a torus composed by x and
y segment, of the given radius r1 and r2."
([r1 r2]
(let [torus-mesh (Torus. 50 50 r1 r2)
torus (Geometry. "torus" torus-mesh)]
(mknode
(doto torus
(.setMaterial (default-material))))))
([r1 r2 z-seg r-seg]
(let [torus-mesh (Torus. z-seg r-seg r1 r2)
torus (Geometry. "torus" torus-mesh)]
(mknode
(doto torus
(.setMaterial (default-material)))))))
(defn triangle
"Returns a new 2D triangle in with vertexes v1 v2 v3."
[v1 v2 v3]
(let [v1 (when (= 2 (count v1)) (conj (vec v1) 0))
v2 (when (= 2 (count v2)) (conj (vec v2) 0))
v3 (when (= 2 (count v3)) (conj (vec v3) 0))
triangle-mesh (Mesh.)
vertices (float-array (flatten [v1 v2 v3]))
tex-cord (float-array [0 0 1 0 0 1])
indexes (int-array [2 0 1 1 0 2])
normals (float-array (flatten (repeat 3 [0 0 1])))]
(doto ^Mesh triangle-mesh
(.setBuffer VertexBuffer$Type/Position 3 vertices)
(.setBuffer VertexBuffer$Type/Normal 3 normals)
(.setBuffer VertexBuffer$Type/TexCoord 2 tex-cord)
(.setBuffer VertexBuffer$Type/Index 1 indexes)
(.updateBound))
(mknode
(doto (Geometry. "triangle" triangle-mesh)
(.setMaterial (default-material))))))
(defn trianglestripe
"Returns a new 2D trianglestripe."
[& points]
(let [stripe-mesh (Mesh.)
points (for [pt points] (if (= 2 (count pt)) (conj (vec pt) 0) pt))
size (count points)
vertices (float-array (flatten points))
tex-cord (float-array (flatten (repeat size [0 0 1])))
idx-triples (flatten
(map vector (repeat size 0) (range 1 (dec size)) (range 2 size)))
indexes (int-array (+ idx-triples (reverse idx-triples)))
normals (float-array (flatten (repeat (count points) [0 0 1])))]
(doto ^Mesh stripe-mesh
(.setBuffer VertexBuffer$Type/Position 3 vertices)
(.setBuffer VertexBuffer$Type/Normal 3 normals)
(.setBuffer VertexBuffer$Type/TexCoord 2 tex-cord)
(.setBuffer VertexBuffer$Type/Index 1 indexes)
(.updateBound))
(mknode
(doto (Geometry. "stripe" stripe-mesh)
(.setMaterial (default-material))))))
(defn quad
[width height]
(let [quad-mesh (Quad. width height)]
(mknode
(doto (Geometry. "quad" quad-mesh)
(.setMaterial (default-material))))))
(defn dome
"A hemisphere."
([radius]
(mknode ^Geometry
(doto ^Spatial (r 1 (/ PI 2) ^Geometry (Geometry. "dome" (Dome. 50 50 radius)))
(.setMaterial (default-material))))))
(defn load-obj
"Load an .obj file and makes it available for rendering.
Remember to load a single model with this function. For
example, in Maya, before exporting a model Combine the
meshes into a single one and triangulate the resulting object."
[filename]
(let [imported-model ^Geometry (.loadModel ^AssetManager asset-manager filename)]
(mknode ^Node
(doto ^Geometry imported-model
(.setMaterial (default-material))))))
(defhigh texture
"Apply a texture to a given spatial."
[filename spatial]
(let [tex ^Texture (.loadTexture ^AssetManager asset-manager filename)
material ^Material (textured-material tex)]
(doto ^Node spatial
(.setMaterial material))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Other operations
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defhigh mkpol
"Mk polyedra.
Vertices is a list of vertices, and dim is a keyword
representing the dimension of the shape been created.
Legal values for dim: :0 , :1, :2.
:0 -> Returns a 0 skeleton of the given points.
:1 -> Returns a 1D representation of the given points.
:2 -> Returns a 2D representation of the given points (for now only convex 'r supported)"
[vertices dim]
(cond-match
[:0 dim]
(let [result (struct2 (map #(line %1 %2) (butlast vertices) (next vertices)))]
(skeleton 0 result))
[:1 dim]
(doto ^Node (struct2 (map #(line %1 %2) (butlast vertices) (next vertices)))
(.setMaterial (unlit-material)))
[:2 dim]
(doto ^Node (apply trianglestripe vertices)
(.setMaterial (default-material)))
[? dim] (throw (IllegalArgumentException. (str "mkpol: " dim " is not a valid dimension.")))))
(defn quote
[& dash]
(println "TODO"))
|
81347
|
;; Copyright (c) 2011 <NAME>, https://github.com/CharlesStain/clj3D
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(ns clj3D.fenvs
(:refer-clojure :rename {+ core-+})
(:use
[matchure]
[clj3D curry math])
(:import
[clj3D Utilities]
[java.util LinkedList]
[com.jme3.math Vector3f Vector2f ColorRGBA Quaternion Transform]
[com.jme3.asset AssetManager]
[com.jme3.system JmeSystem]
[com.jme3.material Material RenderState$FaceCullMode]
[com.jme3.texture Texture]
[com.jme3.scene.shape Box Line Sphere Cylinder Torus Quad Dome]
[com.jme3.scene Node Geometry Spatial Mesh Mesh$Mode VertexBuffer VertexBuffer$Type]
[jme3tools.optimize GeometryBatchFactory]
[com.jme3.asset.plugins FileLocator]))
;;For performance tweaking. Just ignore this.
(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Graphics stuff.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} colors
{ :gray (ColorRGBA/Gray),
:green (ColorRGBA/Green),
:black (ColorRGBA/Black),
:blue (ColorRGBA/Blue),
:brown (ColorRGBA/Brown),
:cyan (ColorRGBA/Cyan),
:magenta (ColorRGBA/Magenta),
:orange (ColorRGBA/Orange),
:purple (ColorRGBA. 0.5 0.0 0.8 1.0),
:pink (ColorRGBA/Pink),
:white (ColorRGBA/White),
:red (ColorRGBA/Red),
:yellow (ColorRGBA/Yellow)})
(def ^{:private true} default-color (ColorRGBA/LightGray))
(def ^{:private true} asset-manager
(JmeSystem/newAssetManager
(.getResource (.getContextClassLoader (Thread/currentThread))
"com/jme3/asset/Desktop.cfg")))
(defn- default-material []
(doto (Material. asset-manager "Common/MatDefs/Light/Lighting.j3md")
(.setBoolean "UseMaterialColors" true)
(.setColor "Ambient" (get colors :black))
(.setColor "Diffuse" default-color)
(.setColor "Specular" (get colors :white))
(.setFloat "Shininess" 10)))
(defn- unlit-material []
(doto (Material. asset-manager "Common/MatDefs/Misc/Unshaded.j3md")
(.setColor "Color" default-color)))
(defn- textured-material [texture]
(doto (Material. asset-manager "Common/MatDefs/Misc/Unshaded.j3md")
(.setTexture "ColorMap" texture)))
(defn- colored-material
[color-keyword]
(doto (Material. asset-manager "Common/MatDefs/Light/Lighting.j3md")
(.setBoolean "UseMaterialColors" true)
(.setColor "Ambient" (get colors :black))
(.setColor "Diffuse" (get colors color-keyword))
(.setColor "Specular" (get colors :white))
(.setFloat "Shininess" 10)))
(defhigh color
"Change the color of the shape, then return the spatial itself."
[color-symbol ^Spatial object]
(.setMaterial object (colored-material color-symbol))
object)
;;For custom Obj files
(.registerLocator ^AssetManager asset-manager
(str (. System getProperty "user.dir") "/models")
"com.jme3.asset.plugins.FileLocator")
;;For user textures
(.registerLocator ^AssetManager asset-manager
(str (. System getProperty "user.dir") "/textures")
"com.jme3.asset.plugins.FileLocator")
(defn- optimize
"Optimize a Spatial. Internal use."
[spatial]
(doto ^Node (GeometryBatchFactory/optimize spatial)
(.setName "structured")))
(defhigh merge-geometries
[geom1 geom2]
(let [out-mesh (Mesh.)]
(GeometryBatchFactory/mergeGeometries [geom1 geom2] out-mesh)
(doto (Geometry. "structured" out-mesh)
(optimize)
(.setMaterial (default-material)))))
(extend-protocol Addable
Geometry
(+ [g1 g2] (merge-geometries g1 g2)))
(defn mknode
"It takes a list or an undefined number of geometries and put them into
a single node. Materials are preserverd."
[& objs]
(let [flattened-args (flatten objs)
new-node (Node. "node")]
(doseq [geom flattened-args] (.attachChild new-node geom))
(optimize new-node)))
(extend-protocol Addable
Node
(+ [nd1 nd2] (mknode nd1 nd2)))
;; i.e the original STRUCT from Plasm
(defn struct2
"Merge all the input given meshs into a single one.
It's a fairly powerful function, since its input can be
an arbitrary number of functions and geometrical object.
The input is visited from right to left, applying (if present)
the functions to the Geometry objects. The only constrain is
that the result must be a Geometry object. You can even pass a
sequence of transformation/geometries.
Usage:
(struct2 (cube 1) (t 1 1) (sphere 1) -> returns a translated sphere joined
with a cube.
(struct 2 [(color :red) (cube 1)]) -> returns a red cube."
[& args]
(let [flattened-args (flatten args)
rev-seq (reverse flattened-args)]
(reduce (fn [x y]
(cond-match
[[com.jme3.scene.Spatial com.jme3.scene.Spatial] [x y]] (+ x y)
[[com.jme3.scene.Spatial ?func] [x y]] (func x)
[[?func com.jme3.scene.Spatial] [x y]] (func x)
[? [x y]] (throw (IllegalArgumentException. "Invalid input for struct")))) rev-seq)))
(defhigh attach
"Attach a child to the given node."
[^Node node child]
(.attachChild node child))
(defhigh t
"Translate function. High order function.
Usage:
(t 1 2.0 (cube 1)) -> move the cube from <0,0,0> to <2.0,0,0>
(t [1 2] [3.0 2.0] (cube 1) -> move the cube to <3.0,2.0,0>"
[axes value geom]
(let [cloned ^Spatial (.clone ^Spatial geom)]
(doto ^Node cloned
(.move (jvector axes value)))))
(defhigh r
"Rotate function. High order function."
[axis rotation spatial]
(let [cloned ^Spatial (.clone ^Spatial spatial)
rotation-pivot (Node.)
quaternion (Quaternion.)]
(.attachChild rotation-pivot cloned)
(.setLocalTranslation rotation-pivot (Vector3f/ZERO))
(.fromAngleAxis quaternion rotation (jvector axis 1.0))
(.setLocalRotation rotation-pivot quaternion)
(let [world-transform ^Transform (.getWorldTransform rotation-pivot)
prev-transform ^Transform (.getLocalTransform ^Spatial cloned)]
(doto ^Spatial cloned
(.setLocalTransform (.combineWithParent prev-transform world-transform))))))
(defn- mirror
[axis node]
(let [children (.getChildren node)
queue (LinkedList.)]
(.addAll queue children)
(Utilities/traverseAndMirror axis queue)))
(defhigh s
"Scale function. High order function.
Usage:
(s 1 0.5 (cube 1)) -> scale 50% of cube x-side
(s [1 2] [0.5 0.7] (cube 1)) -> scale 50% x and 70% y."
[axes value geom]
(let [cloned ^Spatial (.clone ^Spatial geom)]
(cond-match
[-1 value]
(do
(mirror axes cloned)
cloned)
[java.lang.Integer axes]
(let [av-map (hash-map (dec axes) value)]
(doto ^Node cloned
(.scale (get av-map 0 1.0) (get av-map 1 1.0) (get av-map 2 1.0))))
[clojure.lang.IPersistentCollection axes]
(let [av-map (reduce into (map hash-map (map dec axes) value))]
(doto ^Node cloned
(.scale (get av-map 0 1.0) (get av-map 1 1.0) (get av-map 2 1.0))))
[? axes] (throw (IllegalArgumentException. "Invalid input for scale")))))
(defhigh skeleton
[dim geom]
(cond-match
[0 dim]
(let [mesh (.getMesh ^Geometry geom)]
(.setMode mesh Mesh$Mode/Points)
(.setPointSize mesh 5.0)
(.updateBound mesh)
(.setStatic mesh)
(doto ^Geometry (Geometry. "skeleton-0" mesh)
(.setMaterial (unlit-material))
(.. getMaterial (setColor "Color" ColorRGBA/Red))))
[1 dim]
(doto ^Geometry geom
(.setMaterial (unlit-material))
(.. getMaterial getAdditionalRenderState (setWireframe true)))
[? dim] geom))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; PRIMITIVES
;; NOTE: Apparently PLaSM and JMonkey use the same coordinate system, but in
;; jmonkey the camera is rotated. Need to fix this.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cuboid
"Returns a new x*y*z cuboid with bottom-left corner in (0,0,0)"
[x y z]
(let [[px py pz] (map #(/ %1 2.0) [x y z])
box (Box. (Vector3f. px py pz) px py pz)
cuboid (Geometry. "cuboid" box)]
(.setMaterial cuboid (default-material))
(mknode cuboid)))
(defn cube
"Returns a new n*n*n cube with bottom-left corner in (0,0,0)"
[side]
(mknode (cuboid side side side)))
(defn hexaedron [] (mknode (cube 1)))
(defn line
"New in clj3D. Draw a simple line from start to end"
[[x1 y1 & z1] [x2 y2 & z2]]
(let [z1 (if (seq z1) (first z1) 0)
z2 (if (seq z2) (first z2) 0)
line-mesh (Line. (Vector3f. x1 y1 z1) (Vector3f. x2 y2 z2))
line-geom (Geometry. "line" line-mesh)]
(.setMaterial line-geom (unlit-material))
(mknode line-geom)))
(defn sphere
"Returns a new sphere in (0,0,0).
(sphere radius) -> returns a sphere of the given radius
(sphere radius x y) -> returns a sphere composed by x and
y segment, of the given radius."
([radius]
(let [sphere-mesh (Sphere. 50 50 radius)
sphere (Geometry. "sphere" sphere-mesh)]
(.setMaterial sphere (default-material))
(mknode sphere)))
([radius z-seg r-seg]
(let [sphere-mesh (Sphere. z-seg r-seg radius)
sphere (Geometry. "sphere" sphere-mesh)]
(.setMaterial sphere (default-material))
(mknode sphere))))
(defn cylinder
"Returns a new cylinder in (0,0,0).
(cylinder radius height) -> returns a cylinder of the given radius and height
(cylinder radius height x y) -> returns a cylinder composed by x and
y segment, of the given radius and height."
([radius height]
(let [cylinder-mesh (Cylinder. 50 50 radius height true)
cylinder (Geometry. "cylinder" cylinder-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cylinder)
(.setMaterial (default-material))))))
([radius height z-seg r-seg]
(let [cylinder-mesh (Cylinder. z-seg r-seg radius height true)
cylinder (Geometry. "cylinder" cylinder-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cylinder)
(.setMaterial (default-material)))))))
(defn cone
"Returns a new cone in (0,0,0)"
([radius height]
(let [cone-mesh (Cylinder. 50 50 0 radius height true false)
cone (Geometry. "cone" cone-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cone)
(.setMaterial (default-material))))))
([radius height z-seg r-seg]
(let [cone-mesh (Cylinder. z-seg r-seg 0 radius height true false)
cone (Geometry. "cone" cone-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cone)
(.setMaterial (default-material)))))))
(defn torus
"Returns a new torus in (0,0,0).
(torus r1 r2) -> returns a torus of the given radius r1 and r2
(torus r1 r2 x y) -> returns a torus composed by x and
y segment, of the given radius r1 and r2."
([r1 r2]
(let [torus-mesh (Torus. 50 50 r1 r2)
torus (Geometry. "torus" torus-mesh)]
(mknode
(doto torus
(.setMaterial (default-material))))))
([r1 r2 z-seg r-seg]
(let [torus-mesh (Torus. z-seg r-seg r1 r2)
torus (Geometry. "torus" torus-mesh)]
(mknode
(doto torus
(.setMaterial (default-material)))))))
(defn triangle
"Returns a new 2D triangle in with vertexes v1 v2 v3."
[v1 v2 v3]
(let [v1 (when (= 2 (count v1)) (conj (vec v1) 0))
v2 (when (= 2 (count v2)) (conj (vec v2) 0))
v3 (when (= 2 (count v3)) (conj (vec v3) 0))
triangle-mesh (Mesh.)
vertices (float-array (flatten [v1 v2 v3]))
tex-cord (float-array [0 0 1 0 0 1])
indexes (int-array [2 0 1 1 0 2])
normals (float-array (flatten (repeat 3 [0 0 1])))]
(doto ^Mesh triangle-mesh
(.setBuffer VertexBuffer$Type/Position 3 vertices)
(.setBuffer VertexBuffer$Type/Normal 3 normals)
(.setBuffer VertexBuffer$Type/TexCoord 2 tex-cord)
(.setBuffer VertexBuffer$Type/Index 1 indexes)
(.updateBound))
(mknode
(doto (Geometry. "triangle" triangle-mesh)
(.setMaterial (default-material))))))
(defn trianglestripe
"Returns a new 2D trianglestripe."
[& points]
(let [stripe-mesh (Mesh.)
points (for [pt points] (if (= 2 (count pt)) (conj (vec pt) 0) pt))
size (count points)
vertices (float-array (flatten points))
tex-cord (float-array (flatten (repeat size [0 0 1])))
idx-triples (flatten
(map vector (repeat size 0) (range 1 (dec size)) (range 2 size)))
indexes (int-array (+ idx-triples (reverse idx-triples)))
normals (float-array (flatten (repeat (count points) [0 0 1])))]
(doto ^Mesh stripe-mesh
(.setBuffer VertexBuffer$Type/Position 3 vertices)
(.setBuffer VertexBuffer$Type/Normal 3 normals)
(.setBuffer VertexBuffer$Type/TexCoord 2 tex-cord)
(.setBuffer VertexBuffer$Type/Index 1 indexes)
(.updateBound))
(mknode
(doto (Geometry. "stripe" stripe-mesh)
(.setMaterial (default-material))))))
(defn quad
[width height]
(let [quad-mesh (Quad. width height)]
(mknode
(doto (Geometry. "quad" quad-mesh)
(.setMaterial (default-material))))))
(defn dome
"A hemisphere."
([radius]
(mknode ^Geometry
(doto ^Spatial (r 1 (/ PI 2) ^Geometry (Geometry. "dome" (Dome. 50 50 radius)))
(.setMaterial (default-material))))))
(defn load-obj
"Load an .obj file and makes it available for rendering.
Remember to load a single model with this function. For
example, in Maya, before exporting a model Combine the
meshes into a single one and triangulate the resulting object."
[filename]
(let [imported-model ^Geometry (.loadModel ^AssetManager asset-manager filename)]
(mknode ^Node
(doto ^Geometry imported-model
(.setMaterial (default-material))))))
(defhigh texture
"Apply a texture to a given spatial."
[filename spatial]
(let [tex ^Texture (.loadTexture ^AssetManager asset-manager filename)
material ^Material (textured-material tex)]
(doto ^Node spatial
(.setMaterial material))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Other operations
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defhigh mkpol
"Mk polyedra.
Vertices is a list of vertices, and dim is a keyword
representing the dimension of the shape been created.
Legal values for dim: :0 , :1, :2.
:0 -> Returns a 0 skeleton of the given points.
:1 -> Returns a 1D representation of the given points.
:2 -> Returns a 2D representation of the given points (for now only convex 'r supported)"
[vertices dim]
(cond-match
[:0 dim]
(let [result (struct2 (map #(line %1 %2) (butlast vertices) (next vertices)))]
(skeleton 0 result))
[:1 dim]
(doto ^Node (struct2 (map #(line %1 %2) (butlast vertices) (next vertices)))
(.setMaterial (unlit-material)))
[:2 dim]
(doto ^Node (apply trianglestripe vertices)
(.setMaterial (default-material)))
[? dim] (throw (IllegalArgumentException. (str "mkpol: " dim " is not a valid dimension.")))))
(defn quote
[& dash]
(println "TODO"))
| true |
;; Copyright (c) 2011 PI:NAME:<NAME>END_PI, https://github.com/CharlesStain/clj3D
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(ns clj3D.fenvs
(:refer-clojure :rename {+ core-+})
(:use
[matchure]
[clj3D curry math])
(:import
[clj3D Utilities]
[java.util LinkedList]
[com.jme3.math Vector3f Vector2f ColorRGBA Quaternion Transform]
[com.jme3.asset AssetManager]
[com.jme3.system JmeSystem]
[com.jme3.material Material RenderState$FaceCullMode]
[com.jme3.texture Texture]
[com.jme3.scene.shape Box Line Sphere Cylinder Torus Quad Dome]
[com.jme3.scene Node Geometry Spatial Mesh Mesh$Mode VertexBuffer VertexBuffer$Type]
[jme3tools.optimize GeometryBatchFactory]
[com.jme3.asset.plugins FileLocator]))
;;For performance tweaking. Just ignore this.
(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Graphics stuff.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} colors
{ :gray (ColorRGBA/Gray),
:green (ColorRGBA/Green),
:black (ColorRGBA/Black),
:blue (ColorRGBA/Blue),
:brown (ColorRGBA/Brown),
:cyan (ColorRGBA/Cyan),
:magenta (ColorRGBA/Magenta),
:orange (ColorRGBA/Orange),
:purple (ColorRGBA. 0.5 0.0 0.8 1.0),
:pink (ColorRGBA/Pink),
:white (ColorRGBA/White),
:red (ColorRGBA/Red),
:yellow (ColorRGBA/Yellow)})
(def ^{:private true} default-color (ColorRGBA/LightGray))
(def ^{:private true} asset-manager
(JmeSystem/newAssetManager
(.getResource (.getContextClassLoader (Thread/currentThread))
"com/jme3/asset/Desktop.cfg")))
(defn- default-material []
(doto (Material. asset-manager "Common/MatDefs/Light/Lighting.j3md")
(.setBoolean "UseMaterialColors" true)
(.setColor "Ambient" (get colors :black))
(.setColor "Diffuse" default-color)
(.setColor "Specular" (get colors :white))
(.setFloat "Shininess" 10)))
(defn- unlit-material []
(doto (Material. asset-manager "Common/MatDefs/Misc/Unshaded.j3md")
(.setColor "Color" default-color)))
(defn- textured-material [texture]
(doto (Material. asset-manager "Common/MatDefs/Misc/Unshaded.j3md")
(.setTexture "ColorMap" texture)))
(defn- colored-material
[color-keyword]
(doto (Material. asset-manager "Common/MatDefs/Light/Lighting.j3md")
(.setBoolean "UseMaterialColors" true)
(.setColor "Ambient" (get colors :black))
(.setColor "Diffuse" (get colors color-keyword))
(.setColor "Specular" (get colors :white))
(.setFloat "Shininess" 10)))
(defhigh color
"Change the color of the shape, then return the spatial itself."
[color-symbol ^Spatial object]
(.setMaterial object (colored-material color-symbol))
object)
;;For custom Obj files
(.registerLocator ^AssetManager asset-manager
(str (. System getProperty "user.dir") "/models")
"com.jme3.asset.plugins.FileLocator")
;;For user textures
(.registerLocator ^AssetManager asset-manager
(str (. System getProperty "user.dir") "/textures")
"com.jme3.asset.plugins.FileLocator")
(defn- optimize
"Optimize a Spatial. Internal use."
[spatial]
(doto ^Node (GeometryBatchFactory/optimize spatial)
(.setName "structured")))
(defhigh merge-geometries
[geom1 geom2]
(let [out-mesh (Mesh.)]
(GeometryBatchFactory/mergeGeometries [geom1 geom2] out-mesh)
(doto (Geometry. "structured" out-mesh)
(optimize)
(.setMaterial (default-material)))))
(extend-protocol Addable
Geometry
(+ [g1 g2] (merge-geometries g1 g2)))
(defn mknode
"It takes a list or an undefined number of geometries and put them into
a single node. Materials are preserverd."
[& objs]
(let [flattened-args (flatten objs)
new-node (Node. "node")]
(doseq [geom flattened-args] (.attachChild new-node geom))
(optimize new-node)))
(extend-protocol Addable
Node
(+ [nd1 nd2] (mknode nd1 nd2)))
;; i.e the original STRUCT from Plasm
(defn struct2
"Merge all the input given meshs into a single one.
It's a fairly powerful function, since its input can be
an arbitrary number of functions and geometrical object.
The input is visited from right to left, applying (if present)
the functions to the Geometry objects. The only constrain is
that the result must be a Geometry object. You can even pass a
sequence of transformation/geometries.
Usage:
(struct2 (cube 1) (t 1 1) (sphere 1) -> returns a translated sphere joined
with a cube.
(struct 2 [(color :red) (cube 1)]) -> returns a red cube."
[& args]
(let [flattened-args (flatten args)
rev-seq (reverse flattened-args)]
(reduce (fn [x y]
(cond-match
[[com.jme3.scene.Spatial com.jme3.scene.Spatial] [x y]] (+ x y)
[[com.jme3.scene.Spatial ?func] [x y]] (func x)
[[?func com.jme3.scene.Spatial] [x y]] (func x)
[? [x y]] (throw (IllegalArgumentException. "Invalid input for struct")))) rev-seq)))
(defhigh attach
"Attach a child to the given node."
[^Node node child]
(.attachChild node child))
(defhigh t
"Translate function. High order function.
Usage:
(t 1 2.0 (cube 1)) -> move the cube from <0,0,0> to <2.0,0,0>
(t [1 2] [3.0 2.0] (cube 1) -> move the cube to <3.0,2.0,0>"
[axes value geom]
(let [cloned ^Spatial (.clone ^Spatial geom)]
(doto ^Node cloned
(.move (jvector axes value)))))
(defhigh r
"Rotate function. High order function."
[axis rotation spatial]
(let [cloned ^Spatial (.clone ^Spatial spatial)
rotation-pivot (Node.)
quaternion (Quaternion.)]
(.attachChild rotation-pivot cloned)
(.setLocalTranslation rotation-pivot (Vector3f/ZERO))
(.fromAngleAxis quaternion rotation (jvector axis 1.0))
(.setLocalRotation rotation-pivot quaternion)
(let [world-transform ^Transform (.getWorldTransform rotation-pivot)
prev-transform ^Transform (.getLocalTransform ^Spatial cloned)]
(doto ^Spatial cloned
(.setLocalTransform (.combineWithParent prev-transform world-transform))))))
(defn- mirror
[axis node]
(let [children (.getChildren node)
queue (LinkedList.)]
(.addAll queue children)
(Utilities/traverseAndMirror axis queue)))
(defhigh s
"Scale function. High order function.
Usage:
(s 1 0.5 (cube 1)) -> scale 50% of cube x-side
(s [1 2] [0.5 0.7] (cube 1)) -> scale 50% x and 70% y."
[axes value geom]
(let [cloned ^Spatial (.clone ^Spatial geom)]
(cond-match
[-1 value]
(do
(mirror axes cloned)
cloned)
[java.lang.Integer axes]
(let [av-map (hash-map (dec axes) value)]
(doto ^Node cloned
(.scale (get av-map 0 1.0) (get av-map 1 1.0) (get av-map 2 1.0))))
[clojure.lang.IPersistentCollection axes]
(let [av-map (reduce into (map hash-map (map dec axes) value))]
(doto ^Node cloned
(.scale (get av-map 0 1.0) (get av-map 1 1.0) (get av-map 2 1.0))))
[? axes] (throw (IllegalArgumentException. "Invalid input for scale")))))
(defhigh skeleton
[dim geom]
(cond-match
[0 dim]
(let [mesh (.getMesh ^Geometry geom)]
(.setMode mesh Mesh$Mode/Points)
(.setPointSize mesh 5.0)
(.updateBound mesh)
(.setStatic mesh)
(doto ^Geometry (Geometry. "skeleton-0" mesh)
(.setMaterial (unlit-material))
(.. getMaterial (setColor "Color" ColorRGBA/Red))))
[1 dim]
(doto ^Geometry geom
(.setMaterial (unlit-material))
(.. getMaterial getAdditionalRenderState (setWireframe true)))
[? dim] geom))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; PRIMITIVES
;; NOTE: Apparently PLaSM and JMonkey use the same coordinate system, but in
;; jmonkey the camera is rotated. Need to fix this.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cuboid
"Returns a new x*y*z cuboid with bottom-left corner in (0,0,0)"
[x y z]
(let [[px py pz] (map #(/ %1 2.0) [x y z])
box (Box. (Vector3f. px py pz) px py pz)
cuboid (Geometry. "cuboid" box)]
(.setMaterial cuboid (default-material))
(mknode cuboid)))
(defn cube
"Returns a new n*n*n cube with bottom-left corner in (0,0,0)"
[side]
(mknode (cuboid side side side)))
(defn hexaedron [] (mknode (cube 1)))
(defn line
"New in clj3D. Draw a simple line from start to end"
[[x1 y1 & z1] [x2 y2 & z2]]
(let [z1 (if (seq z1) (first z1) 0)
z2 (if (seq z2) (first z2) 0)
line-mesh (Line. (Vector3f. x1 y1 z1) (Vector3f. x2 y2 z2))
line-geom (Geometry. "line" line-mesh)]
(.setMaterial line-geom (unlit-material))
(mknode line-geom)))
(defn sphere
"Returns a new sphere in (0,0,0).
(sphere radius) -> returns a sphere of the given radius
(sphere radius x y) -> returns a sphere composed by x and
y segment, of the given radius."
([radius]
(let [sphere-mesh (Sphere. 50 50 radius)
sphere (Geometry. "sphere" sphere-mesh)]
(.setMaterial sphere (default-material))
(mknode sphere)))
([radius z-seg r-seg]
(let [sphere-mesh (Sphere. z-seg r-seg radius)
sphere (Geometry. "sphere" sphere-mesh)]
(.setMaterial sphere (default-material))
(mknode sphere))))
(defn cylinder
"Returns a new cylinder in (0,0,0).
(cylinder radius height) -> returns a cylinder of the given radius and height
(cylinder radius height x y) -> returns a cylinder composed by x and
y segment, of the given radius and height."
([radius height]
(let [cylinder-mesh (Cylinder. 50 50 radius height true)
cylinder (Geometry. "cylinder" cylinder-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cylinder)
(.setMaterial (default-material))))))
([radius height z-seg r-seg]
(let [cylinder-mesh (Cylinder. z-seg r-seg radius height true)
cylinder (Geometry. "cylinder" cylinder-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cylinder)
(.setMaterial (default-material)))))))
(defn cone
"Returns a new cone in (0,0,0)"
([radius height]
(let [cone-mesh (Cylinder. 50 50 0 radius height true false)
cone (Geometry. "cone" cone-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cone)
(.setMaterial (default-material))))))
([radius height z-seg r-seg]
(let [cone-mesh (Cylinder. z-seg r-seg 0 radius height true false)
cone (Geometry. "cone" cone-mesh)]
(mknode
(doto ^Geometry (t 3 (/ height 2.0) cone)
(.setMaterial (default-material)))))))
(defn torus
"Returns a new torus in (0,0,0).
(torus r1 r2) -> returns a torus of the given radius r1 and r2
(torus r1 r2 x y) -> returns a torus composed by x and
y segment, of the given radius r1 and r2."
([r1 r2]
(let [torus-mesh (Torus. 50 50 r1 r2)
torus (Geometry. "torus" torus-mesh)]
(mknode
(doto torus
(.setMaterial (default-material))))))
([r1 r2 z-seg r-seg]
(let [torus-mesh (Torus. z-seg r-seg r1 r2)
torus (Geometry. "torus" torus-mesh)]
(mknode
(doto torus
(.setMaterial (default-material)))))))
(defn triangle
"Returns a new 2D triangle in with vertexes v1 v2 v3."
[v1 v2 v3]
(let [v1 (when (= 2 (count v1)) (conj (vec v1) 0))
v2 (when (= 2 (count v2)) (conj (vec v2) 0))
v3 (when (= 2 (count v3)) (conj (vec v3) 0))
triangle-mesh (Mesh.)
vertices (float-array (flatten [v1 v2 v3]))
tex-cord (float-array [0 0 1 0 0 1])
indexes (int-array [2 0 1 1 0 2])
normals (float-array (flatten (repeat 3 [0 0 1])))]
(doto ^Mesh triangle-mesh
(.setBuffer VertexBuffer$Type/Position 3 vertices)
(.setBuffer VertexBuffer$Type/Normal 3 normals)
(.setBuffer VertexBuffer$Type/TexCoord 2 tex-cord)
(.setBuffer VertexBuffer$Type/Index 1 indexes)
(.updateBound))
(mknode
(doto (Geometry. "triangle" triangle-mesh)
(.setMaterial (default-material))))))
(defn trianglestripe
"Returns a new 2D trianglestripe."
[& points]
(let [stripe-mesh (Mesh.)
points (for [pt points] (if (= 2 (count pt)) (conj (vec pt) 0) pt))
size (count points)
vertices (float-array (flatten points))
tex-cord (float-array (flatten (repeat size [0 0 1])))
idx-triples (flatten
(map vector (repeat size 0) (range 1 (dec size)) (range 2 size)))
indexes (int-array (+ idx-triples (reverse idx-triples)))
normals (float-array (flatten (repeat (count points) [0 0 1])))]
(doto ^Mesh stripe-mesh
(.setBuffer VertexBuffer$Type/Position 3 vertices)
(.setBuffer VertexBuffer$Type/Normal 3 normals)
(.setBuffer VertexBuffer$Type/TexCoord 2 tex-cord)
(.setBuffer VertexBuffer$Type/Index 1 indexes)
(.updateBound))
(mknode
(doto (Geometry. "stripe" stripe-mesh)
(.setMaterial (default-material))))))
(defn quad
[width height]
(let [quad-mesh (Quad. width height)]
(mknode
(doto (Geometry. "quad" quad-mesh)
(.setMaterial (default-material))))))
(defn dome
"A hemisphere."
([radius]
(mknode ^Geometry
(doto ^Spatial (r 1 (/ PI 2) ^Geometry (Geometry. "dome" (Dome. 50 50 radius)))
(.setMaterial (default-material))))))
(defn load-obj
"Load an .obj file and makes it available for rendering.
Remember to load a single model with this function. For
example, in Maya, before exporting a model Combine the
meshes into a single one and triangulate the resulting object."
[filename]
(let [imported-model ^Geometry (.loadModel ^AssetManager asset-manager filename)]
(mknode ^Node
(doto ^Geometry imported-model
(.setMaterial (default-material))))))
(defhigh texture
"Apply a texture to a given spatial."
[filename spatial]
(let [tex ^Texture (.loadTexture ^AssetManager asset-manager filename)
material ^Material (textured-material tex)]
(doto ^Node spatial
(.setMaterial material))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Other operations
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defhigh mkpol
"Mk polyedra.
Vertices is a list of vertices, and dim is a keyword
representing the dimension of the shape been created.
Legal values for dim: :0 , :1, :2.
:0 -> Returns a 0 skeleton of the given points.
:1 -> Returns a 1D representation of the given points.
:2 -> Returns a 2D representation of the given points (for now only convex 'r supported)"
[vertices dim]
(cond-match
[:0 dim]
(let [result (struct2 (map #(line %1 %2) (butlast vertices) (next vertices)))]
(skeleton 0 result))
[:1 dim]
(doto ^Node (struct2 (map #(line %1 %2) (butlast vertices) (next vertices)))
(.setMaterial (unlit-material)))
[:2 dim]
(doto ^Node (apply trianglestripe vertices)
(.setMaterial (default-material)))
[? dim] (throw (IllegalArgumentException. (str "mkpol: " dim " is not a valid dimension.")))))
(defn quote
[& dash]
(println "TODO"))
|
[
{
"context": "ure)\n\n(deftest resource-api-test\n (let [api-key \"42\"\n user-id \"owner\"]\n (testing \"get\"\n ",
"end": 413,
"score": 0.9974338412284851,
"start": 411,
"tag": "KEY",
"value": "42"
},
{
"context": " (testing \"with wrong api key\"\n (let [api-key \"1\"\n user-id \"owner\"]\n (let [response ",
"end": 2317,
"score": 0.8280721306800842,
"start": 2316,
"tag": "KEY",
"value": "1"
},
{
"context": "api key\"\n (let [api-key \"1\"\n user-id \"owner\"]\n (let [response (-> (request :get \"/api/re",
"end": 2343,
"score": 0.9247027635574341,
"start": 2338,
"tag": "USERNAME",
"value": "owner"
},
{
"context": " (testing \"without owner role\"\n (let [api-key \"42\"\n user-id \"alice\"]\n (let [response ",
"end": 2925,
"score": 0.9967261552810669,
"start": 2923,
"tag": "KEY",
"value": "42"
},
{
"context": "r role\"\n (let [api-key \"42\"\n user-id \"alice\"]\n (let [response (-> (request :get \"/api/re",
"end": 2951,
"score": 0.9833682179450989,
"start": 2946,
"tag": "USERNAME",
"value": "alice"
}
] |
test/clj/rems/test/api/resource.clj
|
JerryTraskelin/rems
| 0 |
(ns ^:integration rems.test.api.resource
(:require [clojure.string :as str]
[clojure.test :refer :all]
[rems.handler :refer [app]]
[rems.test.api :refer :all]
[rems.test.tempura :refer [fake-tempura-fixture]]
[ring.mock.request :refer :all]))
(use-fixtures
:once
fake-tempura-fixture
api-fixture)
(deftest resource-api-test
(let [api-key "42"
user-id "owner"]
(testing "get"
;; just a basic smoke test for now
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)
data (read-body response)]
(is (= 200 (:status response)))
(is (seq? data))
(is (not (empty? data)))
(is (= #{:id :modifieruserid :prefix :resid :start :end :licenses} (set (keys (first data)))))))
(testing "create"
(let [licid 1
resid "RESOURCE-API-TEST"]
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid resid
:prefix "TEST-PREFIX"
:licenses [licid]})
app)]
(is (= 200 (:status response))))
(testing "and fetch"
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)
data (read-body response)
resource (some #(when (= resid (:resid %)) %) data)]
(is (= 200 (:status response)))
(is resource)
(is (= [licid] (map :id (:licenses resource))))))))))
(deftest resource-api-security-test
(testing "without authentication"
(let [response (-> (request :get "/api/resource")
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (.contains (:body response) "Invalid anti-forgery token"))))
(testing "with wrong api key"
(let [api-key "1"
user-id "owner"]
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (= 401 (:status response))))))
(testing "without owner role"
(let [api-key "42"
user-id "alice"]
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (= 401 (:status response)))))))
|
26333
|
(ns ^:integration rems.test.api.resource
(:require [clojure.string :as str]
[clojure.test :refer :all]
[rems.handler :refer [app]]
[rems.test.api :refer :all]
[rems.test.tempura :refer [fake-tempura-fixture]]
[ring.mock.request :refer :all]))
(use-fixtures
:once
fake-tempura-fixture
api-fixture)
(deftest resource-api-test
(let [api-key "<KEY>"
user-id "owner"]
(testing "get"
;; just a basic smoke test for now
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)
data (read-body response)]
(is (= 200 (:status response)))
(is (seq? data))
(is (not (empty? data)))
(is (= #{:id :modifieruserid :prefix :resid :start :end :licenses} (set (keys (first data)))))))
(testing "create"
(let [licid 1
resid "RESOURCE-API-TEST"]
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid resid
:prefix "TEST-PREFIX"
:licenses [licid]})
app)]
(is (= 200 (:status response))))
(testing "and fetch"
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)
data (read-body response)
resource (some #(when (= resid (:resid %)) %) data)]
(is (= 200 (:status response)))
(is resource)
(is (= [licid] (map :id (:licenses resource))))))))))
(deftest resource-api-security-test
(testing "without authentication"
(let [response (-> (request :get "/api/resource")
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (.contains (:body response) "Invalid anti-forgery token"))))
(testing "with wrong api key"
(let [api-key "<KEY>"
user-id "owner"]
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (= 401 (:status response))))))
(testing "without owner role"
(let [api-key "<KEY>"
user-id "alice"]
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (= 401 (:status response)))))))
| true |
(ns ^:integration rems.test.api.resource
(:require [clojure.string :as str]
[clojure.test :refer :all]
[rems.handler :refer [app]]
[rems.test.api :refer :all]
[rems.test.tempura :refer [fake-tempura-fixture]]
[ring.mock.request :refer :all]))
(use-fixtures
:once
fake-tempura-fixture
api-fixture)
(deftest resource-api-test
(let [api-key "PI:KEY:<KEY>END_PI"
user-id "owner"]
(testing "get"
;; just a basic smoke test for now
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)
data (read-body response)]
(is (= 200 (:status response)))
(is (seq? data))
(is (not (empty? data)))
(is (= #{:id :modifieruserid :prefix :resid :start :end :licenses} (set (keys (first data)))))))
(testing "create"
(let [licid 1
resid "RESOURCE-API-TEST"]
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid resid
:prefix "TEST-PREFIX"
:licenses [licid]})
app)]
(is (= 200 (:status response))))
(testing "and fetch"
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)
data (read-body response)
resource (some #(when (= resid (:resid %)) %) data)]
(is (= 200 (:status response)))
(is resource)
(is (= [licid] (map :id (:licenses resource))))))))))
(deftest resource-api-security-test
(testing "without authentication"
(let [response (-> (request :get "/api/resource")
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (.contains (:body response) "Invalid anti-forgery token"))))
(testing "with wrong api key"
(let [api-key "PI:KEY:<KEY>END_PI"
user-id "owner"]
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (= 401 (:status response))))))
(testing "without owner role"
(let [api-key "PI:KEY:<KEY>END_PI"
user-id "alice"]
(let [response (-> (request :get "/api/resource")
(authenticate api-key user-id)
app)]
(is (= 401 (:status response))))
(let [response (-> (request :put "/api/resource/create")
(authenticate api-key user-id)
(json-body {:resid "r"
:prefix "p"
:licenses []})
app)]
(is (= 401 (:status response)))))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998689293861389,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "ice, or any other, from this software.\n\n; Authors: Frantisek Sodomka, Stuart Halloway\n\n(ns clojure.test-clojure.ns-lib",
"end": 492,
"score": 0.9998764991760254,
"start": 475,
"tag": "NAME",
"value": "Frantisek Sodomka"
},
{
"context": "from this software.\n\n; Authors: Frantisek Sodomka, Stuart Halloway\n\n(ns clojure.test-clojure.ns-libs\n (:use clojure",
"end": 509,
"score": 0.9998779296875,
"start": 494,
"tag": "NAME",
"value": "Stuart Halloway"
}
] |
Chapter 07 Code/niko/clojure/test/clojure/test_clojure/ns_libs.clj
|
PacktPublishing/Clojure-Programming-Cookbook
| 14 |
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Authors: Frantisek Sodomka, Stuart Halloway
(ns clojure.test-clojure.ns-libs
(:use clojure.test))
; http://clojure.org/namespaces
; in-ns ns create-ns
; alias import intern refer
; all-ns find-ns
; ns-name ns-aliases ns-imports ns-interns ns-map ns-publics ns-refers
; resolve ns-resolve namespace
; ns-unalias ns-unmap remove-ns
; http://clojure.org/libs
; require use
; loaded-libs
(deftest test-alias
(is (thrown-with-msg? Exception #"No namespace: epicfail found" (alias 'bogus 'epicfail))))
(deftest test-require
(is (thrown? Exception (require :foo)))
(is (thrown? Exception (require))))
(deftest test-use
(is (thrown? Exception (use :foo)))
(is (thrown? Exception (use))))
(deftest reimporting-deftypes
(let [inst1 (binding [*ns* *ns*]
(eval '(do (ns exporter)
(defrecord ReimportMe [a])
(ns importer)
(import exporter.ReimportMe)
(ReimportMe. 1))))
inst2 (binding [*ns* *ns*]
(eval '(do (ns exporter)
(defrecord ReimportMe [a b])
(ns importer)
(import exporter.ReimportMe)
(ReimportMe. 1 2))))]
(testing "you can reimport a changed class and see the changes"
(is (= [:a] (keys inst1)))
(is (= [:a :b] (keys inst2))))
;fragile tests, please fix
#_(testing "you cannot import same local name from a different namespace"
(is (thrown? clojure.lang.Compiler$CompilerException
#"ReimportMe already refers to: class exporter.ReimportMe in namespace: importer"
(binding [*ns* *ns*]
(eval '(do (ns exporter-2)
(defrecord ReimportMe [a b])
(ns importer)
(import exporter-2.ReimportMe)
(ReimportMe. 1 2)))))))))
(deftest naming-types
(testing "you cannot use a name already referred from another namespace"
(is (thrown-with-msg? IllegalStateException
#"String already refers to: class java.lang.String"
(definterface String)))
(is (thrown-with-msg? IllegalStateException
#"StringBuffer already refers to: class java.lang.StringBuffer"
(deftype StringBuffer [])))
(is (thrown-with-msg? IllegalStateException
#"Integer already refers to: class java.lang.Integer"
(defrecord Integer [])))))
(deftest resolution
(let [s (gensym)]
(are [result expr] (= result expr)
#'clojure.core/first (ns-resolve 'clojure.core 'first)
nil (ns-resolve 'clojure.core s)
nil (ns-resolve 'clojure.core {'first :local-first} 'first)
nil (ns-resolve 'clojure.core {'first :local-first} s))))
(deftest refer-error-messages
(let [temp-ns (gensym)]
(binding [*ns* *ns*]
(in-ns temp-ns)
(eval '(def ^{:private true} hidden-var)))
(testing "referring to something that does not exist"
(is (thrown-with-msg? IllegalAccessError #"nonexistent-var does not exist"
(refer temp-ns :only '(nonexistent-var)))))
(testing "referring to something non-public"
(is (thrown-with-msg? IllegalAccessError #"hidden-var is not public"
(refer temp-ns :only '(hidden-var)))))))
(deftest test-defrecord-deftype-err-msg
(is (thrown-with-msg? clojure.lang.Compiler$CompilerException
#"defrecord and deftype fields must be symbols, user\.MyRecord had: :shutdown-fn, compiling:"
(eval '(defrecord MyRecord [:shutdown-fn]))))
(is (thrown-with-msg? clojure.lang.Compiler$CompilerException
#"defrecord and deftype fields must be symbols, user\.MyType had: :key1, compiling:"
(eval '(deftype MyType [:key1])))))
|
113366
|
; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Authors: <NAME>, <NAME>
(ns clojure.test-clojure.ns-libs
(:use clojure.test))
; http://clojure.org/namespaces
; in-ns ns create-ns
; alias import intern refer
; all-ns find-ns
; ns-name ns-aliases ns-imports ns-interns ns-map ns-publics ns-refers
; resolve ns-resolve namespace
; ns-unalias ns-unmap remove-ns
; http://clojure.org/libs
; require use
; loaded-libs
(deftest test-alias
(is (thrown-with-msg? Exception #"No namespace: epicfail found" (alias 'bogus 'epicfail))))
(deftest test-require
(is (thrown? Exception (require :foo)))
(is (thrown? Exception (require))))
(deftest test-use
(is (thrown? Exception (use :foo)))
(is (thrown? Exception (use))))
(deftest reimporting-deftypes
(let [inst1 (binding [*ns* *ns*]
(eval '(do (ns exporter)
(defrecord ReimportMe [a])
(ns importer)
(import exporter.ReimportMe)
(ReimportMe. 1))))
inst2 (binding [*ns* *ns*]
(eval '(do (ns exporter)
(defrecord ReimportMe [a b])
(ns importer)
(import exporter.ReimportMe)
(ReimportMe. 1 2))))]
(testing "you can reimport a changed class and see the changes"
(is (= [:a] (keys inst1)))
(is (= [:a :b] (keys inst2))))
;fragile tests, please fix
#_(testing "you cannot import same local name from a different namespace"
(is (thrown? clojure.lang.Compiler$CompilerException
#"ReimportMe already refers to: class exporter.ReimportMe in namespace: importer"
(binding [*ns* *ns*]
(eval '(do (ns exporter-2)
(defrecord ReimportMe [a b])
(ns importer)
(import exporter-2.ReimportMe)
(ReimportMe. 1 2)))))))))
(deftest naming-types
(testing "you cannot use a name already referred from another namespace"
(is (thrown-with-msg? IllegalStateException
#"String already refers to: class java.lang.String"
(definterface String)))
(is (thrown-with-msg? IllegalStateException
#"StringBuffer already refers to: class java.lang.StringBuffer"
(deftype StringBuffer [])))
(is (thrown-with-msg? IllegalStateException
#"Integer already refers to: class java.lang.Integer"
(defrecord Integer [])))))
(deftest resolution
(let [s (gensym)]
(are [result expr] (= result expr)
#'clojure.core/first (ns-resolve 'clojure.core 'first)
nil (ns-resolve 'clojure.core s)
nil (ns-resolve 'clojure.core {'first :local-first} 'first)
nil (ns-resolve 'clojure.core {'first :local-first} s))))
(deftest refer-error-messages
(let [temp-ns (gensym)]
(binding [*ns* *ns*]
(in-ns temp-ns)
(eval '(def ^{:private true} hidden-var)))
(testing "referring to something that does not exist"
(is (thrown-with-msg? IllegalAccessError #"nonexistent-var does not exist"
(refer temp-ns :only '(nonexistent-var)))))
(testing "referring to something non-public"
(is (thrown-with-msg? IllegalAccessError #"hidden-var is not public"
(refer temp-ns :only '(hidden-var)))))))
(deftest test-defrecord-deftype-err-msg
(is (thrown-with-msg? clojure.lang.Compiler$CompilerException
#"defrecord and deftype fields must be symbols, user\.MyRecord had: :shutdown-fn, compiling:"
(eval '(defrecord MyRecord [:shutdown-fn]))))
(is (thrown-with-msg? clojure.lang.Compiler$CompilerException
#"defrecord and deftype fields must be symbols, user\.MyType had: :key1, compiling:"
(eval '(deftype MyType [:key1])))))
| true |
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
; Authors: PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
(ns clojure.test-clojure.ns-libs
(:use clojure.test))
; http://clojure.org/namespaces
; in-ns ns create-ns
; alias import intern refer
; all-ns find-ns
; ns-name ns-aliases ns-imports ns-interns ns-map ns-publics ns-refers
; resolve ns-resolve namespace
; ns-unalias ns-unmap remove-ns
; http://clojure.org/libs
; require use
; loaded-libs
(deftest test-alias
(is (thrown-with-msg? Exception #"No namespace: epicfail found" (alias 'bogus 'epicfail))))
(deftest test-require
(is (thrown? Exception (require :foo)))
(is (thrown? Exception (require))))
(deftest test-use
(is (thrown? Exception (use :foo)))
(is (thrown? Exception (use))))
(deftest reimporting-deftypes
(let [inst1 (binding [*ns* *ns*]
(eval '(do (ns exporter)
(defrecord ReimportMe [a])
(ns importer)
(import exporter.ReimportMe)
(ReimportMe. 1))))
inst2 (binding [*ns* *ns*]
(eval '(do (ns exporter)
(defrecord ReimportMe [a b])
(ns importer)
(import exporter.ReimportMe)
(ReimportMe. 1 2))))]
(testing "you can reimport a changed class and see the changes"
(is (= [:a] (keys inst1)))
(is (= [:a :b] (keys inst2))))
;fragile tests, please fix
#_(testing "you cannot import same local name from a different namespace"
(is (thrown? clojure.lang.Compiler$CompilerException
#"ReimportMe already refers to: class exporter.ReimportMe in namespace: importer"
(binding [*ns* *ns*]
(eval '(do (ns exporter-2)
(defrecord ReimportMe [a b])
(ns importer)
(import exporter-2.ReimportMe)
(ReimportMe. 1 2)))))))))
(deftest naming-types
(testing "you cannot use a name already referred from another namespace"
(is (thrown-with-msg? IllegalStateException
#"String already refers to: class java.lang.String"
(definterface String)))
(is (thrown-with-msg? IllegalStateException
#"StringBuffer already refers to: class java.lang.StringBuffer"
(deftype StringBuffer [])))
(is (thrown-with-msg? IllegalStateException
#"Integer already refers to: class java.lang.Integer"
(defrecord Integer [])))))
(deftest resolution
(let [s (gensym)]
(are [result expr] (= result expr)
#'clojure.core/first (ns-resolve 'clojure.core 'first)
nil (ns-resolve 'clojure.core s)
nil (ns-resolve 'clojure.core {'first :local-first} 'first)
nil (ns-resolve 'clojure.core {'first :local-first} s))))
(deftest refer-error-messages
(let [temp-ns (gensym)]
(binding [*ns* *ns*]
(in-ns temp-ns)
(eval '(def ^{:private true} hidden-var)))
(testing "referring to something that does not exist"
(is (thrown-with-msg? IllegalAccessError #"nonexistent-var does not exist"
(refer temp-ns :only '(nonexistent-var)))))
(testing "referring to something non-public"
(is (thrown-with-msg? IllegalAccessError #"hidden-var is not public"
(refer temp-ns :only '(hidden-var)))))))
(deftest test-defrecord-deftype-err-msg
(is (thrown-with-msg? clojure.lang.Compiler$CompilerException
#"defrecord and deftype fields must be symbols, user\.MyRecord had: :shutdown-fn, compiling:"
(eval '(defrecord MyRecord [:shutdown-fn]))))
(is (thrown-with-msg? clojure.lang.Compiler$CompilerException
#"defrecord and deftype fields must be symbols, user\.MyType had: :key1, compiling:"
(eval '(deftype MyType [:key1])))))
|
[
{
"context": " :Value \"[email protected]\" }]}}\n {:ShortName \"S",
"end": 9769,
"score": 0.9998181462287903,
"start": 9754,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :LastName \"Smith\"}]\n :ContactInformat",
"end": 10211,
"score": 0.9991922378540039,
"start": 10206,
"tag": "NAME",
"value": "Smith"
},
{
"context": " :Value \"[email protected]\" }]}}\n {:ShortName \"NewShor",
"end": 12473,
"score": 0.9999001622200012,
"start": 12458,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :LastName \"Smith\"}]\n :ContactInformation {:",
"end": 13153,
"score": 0.9994891881942749,
"start": 13148,
"tag": "NAME",
"value": "Smith"
},
{
"context": " :Value \"[email protected]\" }]}}\n {:ShortName \"S",
"end": 14969,
"score": 0.999928891658783,
"start": 14954,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :LastName \"Smith\"}]\n :ContactInformat",
"end": 15411,
"score": 0.9998161196708679,
"start": 15406,
"tag": "NAME",
"value": "Smith"
},
{
"context": " :Value \"[email protected]\" }]}}\n {:ShortName \"NewShor",
"end": 17424,
"score": 0.9999129772186279,
"start": 17409,
"tag": "EMAIL",
"value": "[email protected]"
},
{
"context": " :LastName \"Smith\"}]}]}))))\n\n(deftest platform-instrument-name-upda",
"end": 17848,
"score": 0.9998010396957397,
"start": 17843,
"tag": "NAME",
"value": "Smith"
}
] |
umm-spec-lib/test/cmr/umm_spec/test/field_update.clj
|
ccuadrado/Common-Metadata-Repository
| 0 |
(ns cmr.umm-spec.test.field-update
"Unit tests for UMM field update functionality"
(:require
[clojure.test :refer :all]
[cmr.common.util :refer [are3]]
[cmr.umm-spec.field-update :as field-update]))
(deftest science-keyword-field-updates
(testing "Existing science keywords"
(let [umm {:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES" :Topic "topic" :Term "term"
:VariableLevel1 "var 1" :VariableLevel2 "var 2"
:VariableLevel3 "var 3" :DetailedVariable "detailed"}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:ScienceKeywords] update-value find-value)))
"Clear and replace"
:clear-all-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Add to existing"
:add-to-existing
[{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}]
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES" :Topic "topic" :Term "term"
:VariableLevel1 "var 1" :VariableLevel2 "var 2"
:VariableLevel3 "var 3" :DetailedVariable "detailed"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Find and remove"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}]}
"Find and remove, not found"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil
"Find and update"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"
:VariableLevel1 "var 1",
:VariableLevel2 "var 2",
:VariableLevel3 "var 3",
:DetailedVariable "detailed"}]}
"Find and update, not found"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil
"Find and replace"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Find and replace, not found"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil)))
(testing "No science keywords"
(let [umm {:EntryTitle "Test"}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:ScienceKeywords] update-value find-value)))
"Clear and replace"
:clear-all-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Add to existing"
:add-to-existing
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
;; In order to filter out the concepts in the bulk update that's not found through find-value,
;; apply-update code is modified to return nil for all the find operations
;; when the concept is not found.
"Find and remove"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"}
nil
"Find and update"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
nil
"Find and replace"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
nil))))
(deftest location-keyword-updates-test
(let [umm {:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:LocationKeywords] update-value find-value)))
"Add to existing"
:add-to-existing
[{:Category "CONTINENT"
:Type "EUROPE"}
{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]
nil
{:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}
{:Category "CONTINENT"
:Type "EUROPE"}]}
"Clear all and replace"
:clear-all-and-replace
{:Category "CONTINENT"
:Type "EUROPE"}
nil
{:LocationKeywords [{:Category "CONTINENT"
:Type "EUROPE"}]}
"Find and update"
:find-and-update
{:Subregion1 "EASTERN ASIA"}
{:Subregion1 "WESTERN ASIA"}
{:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "EASTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]}
"Find and replace"
:find-and-replace
{:Subregion1 "EASTERN ASIA"}
{:Subregion1 "WESTERN ASIA"}
{:LocationKeywords [{:Subregion1 "EASTERN ASIA"}]})))
(deftest data-center-home-page-url-updates
(testing "DataCenter home page url updates when home page url is present in the update-value."
(let [umm {:DataCenters [{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "[email protected]" }]}}
{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER"]}
{:ShortName "ShortName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "Smith"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}]}}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:DataCenters] update-value find-value)))
"Find and update home page url"
:find-and-update-home-page-url
{:ShortName "NewShortName" :LongName nil :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "ShortName"}
{:DataCenters [{:ShortName "NewShortName"
:LongName nil
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "[email protected]" }]}}
{:ShortName "NewShortName"
:LongName nil
:Roles ["ARCHIVER"]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "NewShortName"
:LongName nil
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "Smith"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}]})))
(testing "DataCenter home page url updates when home page url is NOT present in the update-value."
(let [umm {:DataCenters [{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "[email protected]" }]}}
{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER"]}
{:ShortName "ShortName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "Smith"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}]}}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:DataCenters] update-value find-value)))
"Find and update home page url"
:find-and-update-home-page-url
{:ShortName "NewShortName" :LongName "NewLongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "NOT A HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "ShortName"}
{:DataCenters [{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "[email protected]" }]}}
{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["ARCHIVER"]}
{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "Smith"}]}]}))))
(deftest platform-instrument-name-updates
(testing "Platform name updates"
(let [umm {:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:Platforms] update-value find-value)))
"Find and update short name"
:find-and-update
{:ShortName "A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and update long and short names"
:find-and-update
{:ShortName "A340-600"
:LongName "Airbus A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Airbus A340-600"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and update nil long name"
:find-and-update
{:ShortName "A340-600"
:LongName nil}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName nil
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and replace short name"
:find-and-replace
{:ShortName "A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"}]}
"Find and replace long and short names"
:find-and-replace
{:ShortName "A340-600"
:LongName "Airbus A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Airbus A340-600"}]}))
(testing "Instrument updates"
(let [umm {:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:Instruments] update-value find-value)))
"Add instrument to existing"
:add-to-existing
{:ShortName "Inst X"}
nil
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}
{:ShortName "Inst X"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}
{:ShortName "Inst X"}]}]}
"Clear all and replace"
:clear-all-and-replace
{:ShortName "Inst X"}
nil
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"}]}]}
"Find and update - multiple instances"
:find-and-update
{:ShortName "Inst X" :LongName nil}
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"
:LongName nil}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"
:LongName nil}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and update - multiple instances"
:find-and-update
{:ShortName "Inst X"}
{:ShortName "Inst 2"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst X"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]})
"Find and replace - multiple instances"
:find-and-replace
{:ShortName "Inst X"}
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and replace - multiple instances"
:find-and-replace
{:ShortName "Inst X"}
{:ShortName "Inst 2"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and remove"
:find-and-remove
nil
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}]}]}))))
|
110745
|
(ns cmr.umm-spec.test.field-update
"Unit tests for UMM field update functionality"
(:require
[clojure.test :refer :all]
[cmr.common.util :refer [are3]]
[cmr.umm-spec.field-update :as field-update]))
(deftest science-keyword-field-updates
(testing "Existing science keywords"
(let [umm {:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES" :Topic "topic" :Term "term"
:VariableLevel1 "var 1" :VariableLevel2 "var 2"
:VariableLevel3 "var 3" :DetailedVariable "detailed"}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:ScienceKeywords] update-value find-value)))
"Clear and replace"
:clear-all-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Add to existing"
:add-to-existing
[{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}]
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES" :Topic "topic" :Term "term"
:VariableLevel1 "var 1" :VariableLevel2 "var 2"
:VariableLevel3 "var 3" :DetailedVariable "detailed"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Find and remove"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}]}
"Find and remove, not found"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil
"Find and update"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"
:VariableLevel1 "var 1",
:VariableLevel2 "var 2",
:VariableLevel3 "var 3",
:DetailedVariable "detailed"}]}
"Find and update, not found"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil
"Find and replace"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Find and replace, not found"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil)))
(testing "No science keywords"
(let [umm {:EntryTitle "Test"}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:ScienceKeywords] update-value find-value)))
"Clear and replace"
:clear-all-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Add to existing"
:add-to-existing
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
;; In order to filter out the concepts in the bulk update that's not found through find-value,
;; apply-update code is modified to return nil for all the find operations
;; when the concept is not found.
"Find and remove"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"}
nil
"Find and update"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
nil
"Find and replace"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
nil))))
(deftest location-keyword-updates-test
(let [umm {:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:LocationKeywords] update-value find-value)))
"Add to existing"
:add-to-existing
[{:Category "CONTINENT"
:Type "EUROPE"}
{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]
nil
{:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}
{:Category "CONTINENT"
:Type "EUROPE"}]}
"Clear all and replace"
:clear-all-and-replace
{:Category "CONTINENT"
:Type "EUROPE"}
nil
{:LocationKeywords [{:Category "CONTINENT"
:Type "EUROPE"}]}
"Find and update"
:find-and-update
{:Subregion1 "EASTERN ASIA"}
{:Subregion1 "WESTERN ASIA"}
{:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "EASTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]}
"Find and replace"
:find-and-replace
{:Subregion1 "EASTERN ASIA"}
{:Subregion1 "WESTERN ASIA"}
{:LocationKeywords [{:Subregion1 "EASTERN ASIA"}]})))
(deftest data-center-home-page-url-updates
(testing "DataCenter home page url updates when home page url is present in the update-value."
(let [umm {:DataCenters [{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "<EMAIL>" }]}}
{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER"]}
{:ShortName "ShortName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "<NAME>"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}]}}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:DataCenters] update-value find-value)))
"Find and update home page url"
:find-and-update-home-page-url
{:ShortName "NewShortName" :LongName nil :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "ShortName"}
{:DataCenters [{:ShortName "NewShortName"
:LongName nil
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "<EMAIL>" }]}}
{:ShortName "NewShortName"
:LongName nil
:Roles ["ARCHIVER"]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "NewShortName"
:LongName nil
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "<NAME>"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}]})))
(testing "DataCenter home page url updates when home page url is NOT present in the update-value."
(let [umm {:DataCenters [{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "<EMAIL>" }]}}
{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER"]}
{:ShortName "ShortName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "<NAME>"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}]}}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:DataCenters] update-value find-value)))
"Find and update home page url"
:find-and-update-home-page-url
{:ShortName "NewShortName" :LongName "NewLongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "NOT A HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "ShortName"}
{:DataCenters [{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "<EMAIL>" }]}}
{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["ARCHIVER"]}
{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "<NAME>"}]}]}))))
(deftest platform-instrument-name-updates
(testing "Platform name updates"
(let [umm {:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:Platforms] update-value find-value)))
"Find and update short name"
:find-and-update
{:ShortName "A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and update long and short names"
:find-and-update
{:ShortName "A340-600"
:LongName "Airbus A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Airbus A340-600"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and update nil long name"
:find-and-update
{:ShortName "A340-600"
:LongName nil}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName nil
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and replace short name"
:find-and-replace
{:ShortName "A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"}]}
"Find and replace long and short names"
:find-and-replace
{:ShortName "A340-600"
:LongName "Airbus A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Airbus A340-600"}]}))
(testing "Instrument updates"
(let [umm {:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:Instruments] update-value find-value)))
"Add instrument to existing"
:add-to-existing
{:ShortName "Inst X"}
nil
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}
{:ShortName "Inst X"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}
{:ShortName "Inst X"}]}]}
"Clear all and replace"
:clear-all-and-replace
{:ShortName "Inst X"}
nil
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"}]}]}
"Find and update - multiple instances"
:find-and-update
{:ShortName "Inst X" :LongName nil}
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"
:LongName nil}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"
:LongName nil}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and update - multiple instances"
:find-and-update
{:ShortName "Inst X"}
{:ShortName "Inst 2"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst X"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]})
"Find and replace - multiple instances"
:find-and-replace
{:ShortName "Inst X"}
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and replace - multiple instances"
:find-and-replace
{:ShortName "Inst X"}
{:ShortName "Inst 2"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and remove"
:find-and-remove
nil
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}]}]}))))
| true |
(ns cmr.umm-spec.test.field-update
"Unit tests for UMM field update functionality"
(:require
[clojure.test :refer :all]
[cmr.common.util :refer [are3]]
[cmr.umm-spec.field-update :as field-update]))
(deftest science-keyword-field-updates
(testing "Existing science keywords"
(let [umm {:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES" :Topic "topic" :Term "term"
:VariableLevel1 "var 1" :VariableLevel2 "var 2"
:VariableLevel3 "var 3" :DetailedVariable "detailed"}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:ScienceKeywords] update-value find-value)))
"Clear and replace"
:clear-all-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Add to existing"
:add-to-existing
[{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}]
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES" :Topic "topic" :Term "term"
:VariableLevel1 "var 1" :VariableLevel2 "var 2"
:VariableLevel3 "var 3" :DetailedVariable "detailed"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Find and remove"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}]}
"Find and remove, not found"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil
"Find and update"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"
:VariableLevel1 "var 1",
:VariableLevel2 "var 2",
:VariableLevel3 "var 3",
:DetailedVariable "detailed"}]}
"Find and update, not found"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil
"Find and replace"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE" :Topic "top" :Term "ter"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Find and replace, not found"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"
:Topic "Topic"}
nil)))
(testing "No science keywords"
(let [umm {:EntryTitle "Test"}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:ScienceKeywords] update-value find-value)))
"Clear and replace"
:clear-all-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
"Add to existing"
:add-to-existing
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
nil
{:EntryTitle "Test"
:ScienceKeywords [{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}]}
;; In order to filter out the concepts in the bulk update that's not found through find-value,
;; apply-update code is modified to return nil for all the find operations
;; when the concept is not found.
"Find and remove"
:find-and-remove
nil
{:Category "EARTH SCIENCE SERVICES"}
nil
"Find and update"
:find-and-update
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
nil
"Find and replace"
:find-and-replace
{:Category "EARTH SCIENCE SERVICES"
:Topic "DATA ANALYSIS AND VISUALIZATION"
:Term "GEOGRAPHIC INFORMATION SYSTEMS"}
{:Category "EARTH SCIENCE SERVICES"}
nil))))
(deftest location-keyword-updates-test
(let [umm {:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:LocationKeywords] update-value find-value)))
"Add to existing"
:add-to-existing
[{:Category "CONTINENT"
:Type "EUROPE"}
{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]
nil
{:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "WESTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}
{:Category "CONTINENT"
:Type "EUROPE"}]}
"Clear all and replace"
:clear-all-and-replace
{:Category "CONTINENT"
:Type "EUROPE"}
nil
{:LocationKeywords [{:Category "CONTINENT"
:Type "EUROPE"}]}
"Find and update"
:find-and-update
{:Subregion1 "EASTERN ASIA"}
{:Subregion1 "WESTERN ASIA"}
{:LocationKeywords [{:Category "CONTINENT"
:Type "ASIA"
:Subregion1 "EASTERN ASIA"
:Subregion2 "MIDDLE EAST"
:Subregion3 "GAZA STRIP"}]}
"Find and replace"
:find-and-replace
{:Subregion1 "EASTERN ASIA"}
{:Subregion1 "WESTERN ASIA"}
{:LocationKeywords [{:Subregion1 "EASTERN ASIA"}]})))
(deftest data-center-home-page-url-updates
(testing "DataCenter home page url updates when home page url is present in the update-value."
(let [umm {:DataCenters [{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "PI:EMAIL:<EMAIL>END_PI" }]}}
{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER"]}
{:ShortName "ShortName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "PI:NAME:<NAME>END_PI"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}]}}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:DataCenters] update-value find-value)))
"Find and update home page url"
:find-and-update-home-page-url
{:ShortName "NewShortName" :LongName nil :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "ShortName"}
{:DataCenters [{:ShortName "NewShortName"
:LongName nil
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "PI:EMAIL:<EMAIL>END_PI" }]}}
{:ShortName "NewShortName"
:LongName nil
:Roles ["ARCHIVER"]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "NewShortName"
:LongName nil
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "PI:NAME:<NAME>END_PI"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}]})))
(testing "DataCenter home page url updates when home page url is NOT present in the update-value."
(let [umm {:DataCenters [{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}
{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "PI:EMAIL:<EMAIL>END_PI" }]}}
{:ShortName "ShortName"
:LongName "Hydrogeophysics Group, Aarhus University "
:Roles ["ARCHIVER"]}
{:ShortName "ShortName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "PI:NAME:<NAME>END_PI"}]
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "HOME PAGE"
:URL "http://nsidc.org/daac/index.html"}]}}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:DataCenters] update-value find-value)))
"Find and update home page url"
:find-and-update-home-page-url
{:ShortName "NewShortName" :LongName "NewLongName" :ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "NOT A HOME PAGE"
:URL "http://nsidc.org/daac/newindex.html"}]}}
{:ShortName "ShortName"}
{:DataCenters [{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["ARCHIVER", "DISTRIBUTOR"]
:Uuid "ef941ad9-1662-400d-a24a-c300a72c1531"
:ContactInformation {:RelatedUrls [{:URLContentType "DataCenterURL"
:Type "PROJECT HOME PAGE"
:URL "http://nsidc.org/daac/index.html"} ]
:ContactMechanisms [{:Type "Telephone"
:Value "1 303 492 6199 x" }
{:Type "Fax"
:Value "1 303 492 2468 x" }
{:Type "Email"
:Value "PI:EMAIL:<EMAIL>END_PI" }]}}
{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["ARCHIVER"]}
{:ShortName "NewShortName"
:LongName "NewLongName"
:Roles ["PROCESSOR"]
:ContactPersons [{:Roles ["Data Center Contact"]
:LastName "PI:NAME:<NAME>END_PI"}]}]}))))
(deftest platform-instrument-name-updates
(testing "Platform name updates"
(let [umm {:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:Platforms] update-value find-value)))
"Find and update short name"
:find-and-update
{:ShortName "A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and update long and short names"
:find-and-update
{:ShortName "A340-600"
:LongName "Airbus A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Airbus A340-600"
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and update nil long name"
:find-and-update
{:ShortName "A340-600"
:LongName nil}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName nil
:Type "Aircraft"
:Instruments [{:ShortName "An Instrument"
:LongName "The Full Name of An Instrument v123.4"
:Technique "Two cans and a string"
:NumberOfInstruments 0}]}]}
"Find and replace short name"
:find-and-replace
{:ShortName "A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"}]}
"Find and replace long and short names"
:find-and-replace
{:ShortName "A340-600"
:LongName "Airbus A340-600"}
{:ShortName "Platform 1"}
{:Platforms [{:ShortName "A340-600"
:LongName "Airbus A340-600"}]}))
(testing "Instrument updates"
(let [umm {:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}]
(are3 [update-type update-value find-value result]
(is (= result
(field-update/apply-update update-type umm [:Instruments] update-value find-value)))
"Add instrument to existing"
:add-to-existing
{:ShortName "Inst X"}
nil
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}
{:ShortName "Inst X"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}
{:ShortName "Inst X"}]}]}
"Clear all and replace"
:clear-all-and-replace
{:ShortName "Inst X"}
nil
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"}]}]}
"Find and update - multiple instances"
:find-and-update
{:ShortName "Inst X" :LongName nil}
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"
:LongName nil}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst X"
:LongName nil}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and update - multiple instances"
:find-and-update
{:ShortName "Inst X"}
{:ShortName "Inst 2"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst X"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]})
"Find and replace - multiple instances"
:find-and-replace
{:ShortName "Inst X"}
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"}
{:ShortName "Inst 2"
:LongName "Instrument 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and replace - multiple instances"
:find-and-replace
{:ShortName "Inst X"}
{:ShortName "Inst 2"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 2"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}
{:ShortName "Inst 3"
:LongName "Instrument 3"}]}]}
"Find and remove"
:find-and-remove
nil
{:ShortName "Inst 1"}
{:Platforms [{:ShortName "Platform 1"
:LongName "Example Platform Long Name 1"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}]}
{:ShortName "Platform 2"
:LongName "Example Platform Long Name 2"
:Type "Aircraft"
:Instruments [{:ShortName "Inst 1"
:LongName "Instrument 1"}]}]}))))
|
[
{
"context": "p this))))))\n (render [this] (dom/div #js {:key \"placeholder\" :ref (fn [r] (set! (.-doc-element this) r))})))\n",
"end": 38864,
"score": 0.5882934927940369,
"start": 38853,
"tag": "KEY",
"value": "placeholder"
}
] |
src/main/fulcro/ui/bootstrap3.cljc
|
d4hines/fulcro
| 0 |
(ns fulcro.ui.bootstrap3
(:require [fulcro.client.dom :as dom]
[fulcro.client.primitives :as prim :refer [defui defsc]]
[fulcro.ui.elements :as ele]
[fulcro.events :as evt]
[fulcro.ui.html-entities :as ent]
[fulcro.i18n :refer [tr tr-unsafe]]
[fulcro.client.mutations :as m :refer [defmutation]]
#?(:clj
[clojure.future :refer :all])
[clojure.string :as str]
[clojure.set :as set]
[fulcro.client :as fc]
[fulcro.logging :as log]
[fulcro.client.util :as util]))
#?(:clj (defn- clj->js [m] m))
;; Bootstrap CSS and Components for Fulcro
(defn- dom-with-class [dom-factory cls attrs children]
(let [attrs (-> attrs
#_(update :key (fnil identity "placeholder-key"))
(update :className #(str cls " " %)))]
(apply dom-factory (clj->js attrs) children)))
(defn- div-with-class [cls attrs children] (dom-with-class dom/div cls attrs children))
(defn- p-with-class [cls attrs children] (dom-with-class dom/p cls attrs children))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; BASE CSS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn container
"Top-level container for bootstrap grid content. This is a responsive fixed-width container. See also container-fluid."
[attrs & children] (div-with-class "container" attrs children))
(defn container-fluid
"Top-level container for bootstrap grid content. This is a responsive full-width container. See also container."
[attrs & children] (div-with-class "container-fluid" attrs children))
(defn row
"Generate a layout row. This is a div container for a row in a 12-wide grid responsive layout.
Rows should contain layout columns generated with the `col` function of this namespace.
The properties are normal DOM attributes as a cljs map and can include standard React DOM properties.
"
[props & children]
(div-with-class "row" props children))
(defn col
"Output a div that represents a column in the 12-column responsive grid.
Any React props are allowed. The following special one pertain to the column:
xs The width of the column on xs screens
sm The width of the column on sm screens
md The width of the column on md screens
lg The width of the column on lg screens
xs-offset The offset of the column on xs screens
sm-offset The offset of the column on sm screens
md-offset The offset of the column on md screens
lg-offset The offset of the column on lg screens
"
[{:keys [className xs sm md lg xs-offset sm-offset md-offset lg-offset] :as props} & children]
(let [classes (cond-> (:className props)
xs (str " col-xs-" xs)
sm (str " col-sm-" sm)
md (str " col-md-" md)
lg (str " col-lg-" lg)
xs-offset (str " col-xs-offset-" xs-offset)
sm-offset (str " col-sm-offset-" sm-offset)
md-offset (str " col-md-offset-" md-offset)
lg-offset (str " col-lg-offset-" lg-offset))
attrs (-> props
(dissoc :xs :sm :md :lg :xs-offset :sm-offset :md-offset :lg-offset)
(assoc :className classes)
clj->js)]
(apply dom/div attrs children)))
(defn lead
"Generates a lead paragraph with an increased font size."
[attrs & children]
(p-with-class "lead" attrs children))
(defn address
"Formats an address"
[name & {:keys [street street2 city-state phone email]}]
(let [brs (repeatedly #(dom/br nil))
children (cond-> (vec (keep identity (list street street2 city-state)))
phone (conj (dom/span nil (dom/abbr #js {:title "Phone"} "P:") phone)))]
(apply dom/address nil
(dom/strong nil name) (dom/br nil)
(vec (interleave children brs)))))
(defn quotation
"Render a block quotation with optional citation and source.
align - :right or :left (default)
credit - The name of the person.
source - The place where it was said/written, you supply the joining preposition.
children - The DOM element(s) (typicaly a p) that represent the body of the quotation
"
[{:keys [align credit source] :as attrs} & children]
(let [attrs (cond-> (dissoc attrs :align :credit :source)
(= :right align) (assoc :className (str "blockquote-reverse " (:className attrs))))
content (concat children [(dom/footer nil credit " " (dom/cite nil source))])]
(apply dom/blockquote (clj->js attrs) content)))
(defn plain-ul
"Render an unstyled unordered list"
[attrs & children]
(let [attrs (update attrs :className #(str " list-unstyled"))]
(apply dom/ul (clj->js attrs) children)))
(defn inline-ul
"Render an inline unordered list"
[attrs & children]
(let [attrs (update attrs :className #(str " list-inline"))]
(apply dom/ul (clj->js attrs) children)))
(def table-styles #{:striped :bordered :condensed :hover})
(defn table
"Renders a table. attrs can contain any normal react attributes, including :className.
Extended attributes that you can include are:
styles - A set of one or more of: #{:striped :bordered :condensed :hover}
"
[{:keys [className styles] :as attrs} & children]
(let [style-classes (str/join " " (map #(str "table-" (name %)) (set/intersection table-styles styles)))
classes (str (when className (str className " ")) "table " style-classes)
attrs (-> attrs
(dissoc :styles)
(assoc :className classes)
clj->js)]
(apply dom/table attrs children)))
(defn form-horizontal
"Set up a container for labeled inputs (which should have :split) to render the labels beside the fields."
[attrs & children]
(div-with-class "form-horizontal" attrs children))
(defn labeled-input
"An input with a label. All of the attrs apply to the input itself. You must supply a type and id for the
field to work correctly. DO NOT USE for checkbox or radio.
The additional attributes are supported:
:split - A number from 1 to 11. The number of `sm` columns to allocate to the field label. If not specified, the
label will be above the input. The parent must use the `.form-horizontal` class.
:help - A string. If supplied, displayed as the help text for the field. NOT shown if warning, error, or success are set.
:input-generator An (optional) function of `props -> input` to be called to generate the DOM input. It will receive a clj map
of properties and should return an input that has those minimum properties. It can, of course, augment those.
You should only ever supply zero or one of the following:
:warning - A boolean or string. If set as a string, that content replaces the help text.
:error - A boolean or string. If set as a string, that content replaces the help text.
:success - A boolean or string. If set as a string, that content replaces the help text.
"
[{:keys [id type className placeholder split help warning error success
input-generator] :as attrs} label]
(let [state-class (cond
error " has-error"
warning " has-warning"
success " has-success"
:else "")
form-group-classes (str "form-group" state-class)
help (first (keep identity [error warning success help]))
split-right (- 12 split)
help-id (str id "-help")
attrs (cond-> (dissoc attrs :split :help :warning :error :success :input-generator)
help (assoc :aria-describedby help-id)
:always (update :className #(str % " form-control")))]
(cond
(int? split) (dom/div #js {:className form-group-classes}
(dom/label #js {:className (str "control-label col-sm-" split) :htmlFor id} label)
(dom/div #js {:className (str "col-sm-" split-right)}
(if input-generator
(input-generator attrs)
(dom/input (clj->js attrs)))
(when help (dom/span #js {:id help-id :className "help-block"} help))))
:else (dom/div #js {:className form-group-classes}
(dom/label #js {:className "control-label" :htmlFor id} label)
(if input-generator
(input-generator attrs)
(dom/input (clj->js attrs)))
(when help (dom/span #js {:id help-id :className "help-block"} help))))))
(defn button
"Render a button with optional styling
kind - Optional. One of :primary, :success, :info, :warning, or :danger. Defaults to none (default).
size - Optional. One of :xs, :sm, or :lg. Defaults to a normal size.
as-block - Optional. Boolean. When true makes the button a block element.
"
[{:keys [kind size as-block] :as attrs} & children]
{:pre [(or (nil? kind) (contains? #{:primary :success :info :warning :danger} kind))
(or (nil? size) (contains? #{:xs :sm :lg} size))]}
(let [incoming-classes (:className attrs)
button-classes (cond-> "btn"
kind (str " btn-" (name kind))
size (str " btn-" (name size))
(not kind) (str " btn-default")
as-block (str " btn-block")
incoming-classes (str " " incoming-classes))
attrs (-> attrs
(dissoc :kind :size :as-block)
(assoc :className button-classes)
clj->js)]
(apply dom/button attrs children)))
(defn close-button [attrs]
(let [addl-classes (:className attrs)
classes (cond-> "close"
addl-classes (str " " addl-classes))
attrs (assoc attrs :type "button" :aria-label "Close" :className classes)]
(dom/button (clj->js attrs)
(dom/span #js {:aria-hidden true} "\u00D7"))))
(defn img
"Render an img tag with bootstrap classes.
is-responsive - Boolean. Marks the image so that it scales to its container.
shape - Optional. One of :rounded, :circle, or :thumbnail
All other normal react attributes (including className) are allowed."
[{:keys [is-responsive shape] :as attrs}]
{:pre [(or (nil? shape) (contains? #{:rounded :circle :thumbnail} shape))]}
(let [incoming-classes (:className attrs)
button-classes (cond-> ""
shape (str " " "img-" (name shape))
is-responsive (str " img-responsive")
incoming-classes (str " " incoming-classes))
attrs (-> attrs
(dissoc :is-responsive :shape)
(assoc :className button-classes)
clj->js)]
(dom/img attrs)))
;; raw classes (for docstrings and autocomplete
(def text-left "A CSS class for Left aligned text." "text-left")
(def text-center "A CSS class for Center aligned text." "text-center")
(def text-right "A CSS class for Right aligned text." "text-right")
(def text-justify "A CSS class for Justified text." "text-justify")
(def text-nowrap "A CSS class for No wrap text." "text-nowrap")
(def text-lowercase "A css transform that will change encosed text to lowercased text." "text-lowercase")
(def text-uppercase "A css transform that will change encosed text to uppercased text." "text-uppercase")
(def text-capitalize "A css transform that will change encosed text to capitalized text." "text-capitalize")
(def text-muted "CSS class for a muted text color" "text-muted")
(def text-primary "A CSS classname for a primary text color" "text-primary")
(def text-success "A CSS classname for a success text color" "text-success")
(def text-info "A CSS classname for a info text color" "text-info")
(def text-warning "A CSS classname for a warning text color" "text-warning")
(def text-danger "A CSS classname for a danger text color" "text-danger")
(def bg-primary "A CSS classname for a contextual primary background color" "bg-primary")
(def bg-success "A CSS classname for a contextual success background color" "bg-success")
(def bg-info "A CSS classname for a contextual info background color" "bg-info")
(def bg-warning "A CSS classname for a contextual warning background color" "bg-warning")
(def bg-danger "A CSS classname for a contextual danger background color" "bg-danger")
(def pull-left "A CSS class for forcing a float" "pull-left")
(def pull-right "A CSS class for forcing a float" "pull-right")
(def center-block "A CSS class for centering a block element" "center-block")
(def clearfix "A CSS class used on the PARENT to clear floats within that parent." "clearfix")
(def show "A CSS class for BLOCK-level elements. Element affects flow and is visible." "show")
(def hidden "A CSS class for BLOCK-level elements. Element is not in flow." "hidden")
(def invisible "A CSS class for BLOCK-level elements. Element still affects flow." "invisible")
(def visible-xs-block "A responsive CSS class to show element according to screen size" "visible-xs-block")
(def visible-xs-inline "A responsive CSS class to show element according to screen size" "visible-xs-inline")
(def visible-xs-inline-block "A responsive CSS class to show element according to screen size" "visible-xs-inline-block")
(def visible-sm-block "A responsive CSS class to show element according to screen size" "visible-sm-block")
(def visible-sm-inline "A responsive CSS class to show element according to screen size" "visible-sm-inline")
(def visible-sm-inline-block "A responsive CSS class to show element according to screen size" "visible-sm-inline-block")
(def visible-md-block "A responsive CSS class to show element according to screen size" "visible-md-block")
(def visible-md-inline "A responsive CSS class to show element according to screen size" "visible-md-inline")
(def visible-md-inline-block "A responsive CSS class to show element according to screen size" "visible-md-inline-block")
(def visible-lg-block "A responsive CSS class to show element according to screen size" "visible-lg-block")
(def visible-lg-inline "A responsive CSS class to show element according to screen size" "visible-lg-inline")
(def visible-lg-inline-block "A responsive CSS class to show element according to screen size" "visible-lg-inline-block")
(def hidden-xs "A CSS class to hide the element according to screen size" "hidden-xs")
(def hidden-sm "A CSS class to hide the element according to screen size" "hidden-sm")
(def hidden-md "A CSS class to hide the element according to screen size" "hidden-md")
(def hidden-lg "A CSS class to hide the element according to screen size" "hidden-lg")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Bootstrap Components
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def glyph-icons #{:asterisk :plus :euro :eur :minus :cloud :envelope :pencil :glass :music :search :heart
:star :star-empty :user :film :th-large :th :th-list :ok :remove :zoom-in :zoom-out :off :signal
:cog :trash :home :file :time :road :download-alt :download :upload :inbox :play-circle
:repeat :refresh :list-alt :lock :flag :headphones :volume-off :volume-down :volume-up :qrcode
:barcode :tag :tags :book :bookmark :print :camera :font :bold :italic :text-height
:text-width :align-left :align-center :align-right :align-justify :list :indent-left :indent-right
:facetime-video :picture :map-marker :adjust :tint :edit :share :check :move :step-backward
:fast-backward :backward :play :pause :stop :forward :fast-forward :step-forward :eject
:chevron-left :chevron-right :plus-sign :minus-sign :remove-sign :ok-sign :question-sign
:info-sign :screenshot :remove-circle :ok-circle :ban-circle :arrow-left :arrow-right :arrow-up
:arrow-down :share-alt :resize-full :resize-small :exclamation-sign :gift :leaf :fire :eye-open
:eye-close :warning-sign :plane :calendar :random :comment :magnet :chevron-up :chevron-down
:retweet :shopping-cart :folder-close :folder-open :resize-vertical :resize-horizontal :hdd :bullhorn :bell
:certificate :thumbs-up :thumbs-down :hand-right :hand-left :hand-up :hand-down :circle-arrow-right :circle-arrow-left
:circle-arrow-up :circle-arrow-down :globe :wrench :tasks :filter :briefcase :fullscreen :dashboard
:paperclip :heart-empty :link :phone :pushpin :usd :gbp :sort :sort-by-alphabet
:sort-by-alphabet-alt :sort-by-order :sort-by-order-alt :sort-by-attributes :sort-by-attributes-alt :unchecked
:expand :collapse-down :collapse-up :log-in :flash :log-out :new-window :record :save :open :saved :import
:export :send :floppy-disk :floppy-saved :floppy-remove :floppy-save :floppy-open :credit-card :transfer
:cutlery :header :compressed :earphone :phone-alt :tower :stats :sd-video :hd-video
:subtitles :sound-stereo :sound-dolby :sound-5-1 :sound-6-1 :sound-7-1 :copyright-mark :registration-mark :cloud-download
:cloud-upload :tree-conifer :tree-deciduous :cd :save-file :open-file :level-up :copy :paste
:alert :equalizer :king :queen :pawn :bishop :knight :baby-formula :tent
:blackboard :bed :apple :erase :hourglass :lamp :duplicate :piggy-bank :scissors
:bitcoin :btc :xbt :yen :jpy :ruble :rub :scale :ice-lolly
:ice-lolly-tasted :education :option-horizontal :option-vertical :menu-hamburger :modal-window :oil :grain :sunglasses
:text-size :text-color :text-background :object-align-top :object-align-bottom :object-align-horizontal :object-align-left
:object-align-vertical :object-align-right :triangle-right :triangle-left :triangle-bottom :triangle-top
:console :superscript :subscript :menu-left :menu-right :menu-down :menu-up})
(defn glyphicon
"Render a glyphicon in a span. Legal icon names are in b/glyph-icons.
attrs will be added to the span's attributes.
size - The size of the icon font. Defaults to 10pt.
"
[{:keys [size] :or {size "10pt"} :as attrs} icon]
{:pre [(contains? glyph-icons icon)]}
(let [attrs (-> attrs
(dissoc :size)
(assoc :aria-hidden true)
(assoc :style #js {:fontSize size})
(update :className #(str % " glyphicon glyphicon-" (name icon)))
clj->js)]
(dom/span attrs "")))
(defn button-group
"Groups nested buttons together in a horizontal row.
`size` - (optional) can be :xs, :sm, or :lg.
`kind` - (optional) can be :vertical or :justified"
[{:keys [size kind] :as attrs} & children]
(let [justified? (= kind :justified)
vertical? (= kind :vertical)
cls (cond-> "btn-group"
justified? (str " btn-group-justified")
vertical? (str "-vertical")
size (str " btn-group-" (name size)))
wrap-button (fn [ele] (if (ele/react-instance? "button" ele) (button-group {} ele) ele))
attrs (-> attrs (dissoc :size :kind) (assoc :role "group"))
children (if justified? (map #(wrap-button %) children) children)]
(div-with-class cls attrs children)))
(defn button-toolbar
"Groups button groups together as a toolbar, and a bit of space between each group"
[attrs & children]
(div-with-class "btn-toolbar" (assoc attrs :role "toolbar") children))
(defn breadcrumb-item
"Define a breadcrumb.
label - The label to show. You should internationalize this yourself.
onClick - A function. What to do when the item is clicked. Not needed for the last item."
([label] {:label label :onClick identity})
([label onClick] {:label label :onClick onClick}))
(defn breadcrumbs
"props - Properties to place on the top-level `ol`.
items - a list of breadcrumb-item"
[props & items]
(let [attrs (update props :className #(str " breadcrumb"))]
(dom/ol (clj->js attrs)
(conj
(mapv (fn [item] (dom/li #js {:key (:label item)} (dom/a #js {:onClick (:onClick item)} (:label item)))) (butlast items))
(dom/li #js {:key (:label (last items)) :className "active"} (:label (last items)))))))
(defn pagination
"Render a pagination control.
props - A map of properties.
size - One of :sm or :lg
pagination-entries - One or more `pagination-entry`"
[{:keys [size] :as props} & pagination-entries]
(let [classes (cond-> (get props :className "")
:always (str "pagination")
size (str " pagination-" (name size)))
attrs (assoc props :className classes)]
(dom/nav #js {:aria-label "Page Navigation"}
(apply dom/ul (clj->js attrs) pagination-entries))))
(defn pagination-entry
"Create an entry in a pagination control. Forward and back buttons can be rendered at either end with any label, but
the fulcro.ui.html-entities/raqao and laqao defs give a nicely sized font-based arrow."
[{:keys [label disabled active onClick] :as props}]
(let [onClick (if (and onClick (not disabled)) onClick identity)
classes (cond-> (:className props)
disabled (str " disabled")
active (str " active"))
attrs (-> props
(assoc :className classes)
(dissoc :active :label :disabled :onClick))]
(dom/li (clj->js attrs)
(if (or (= label ent/raqao) (= label ent/laqao))
(dom/a #js {:onClick onClick :aria-label (if (= ent/raqao label) "Next" "Previous")}
(dom/span #js {:aria-hidden "true"} label))
(dom/a #js {:onClick onClick}
label (when active (dom/span #js {:className "sr-only"} " (current)")))))))
(defn pager
"A light next/previous pair of controls. Use `pager-next` and `pager-previous` as the children of this."
[props & children]
(let [attrs (-> props
(update :className #(str " pager"))
clj->js)]
(dom/nav #js {:aria-label "Page Navigation"}
(apply dom/ul attrs children))))
(defn pager-next
"Render a next button in a pager"
[{:keys [onClick disabled]} & label-children]
(dom/li #js {:key "next" :className (str "next" (when disabled " disabled"))} (apply dom/a #js {:onClick (or onClick identity)} label-children)))
(defn pager-previous
"Render a previous button in a pager"
[{:keys [onClick disabled]} & label-children]
(dom/li #js {:key "prior" :className (str "previous" (when disabled " disabled"))} (apply dom/a #js {:onClick (or onClick identity)} label-children)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dropdowns
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def dropdown-table :bootstrap.dropdown/by-id)
(def dropdown-item-table :bootstrap.dropdown-item/by-id)
(defn dropdown-item
"Define the state for an item of a dropdown."
[id label] {::id id ::label label})
(defn dropdown-divider
"Creates a divider between items. Must have a unique ID"
[id] {::id id ::label ::divider})
(defn dropdown
"Creates a dropdown's state. Create items with dropdown-item or dropdown-divider."
[id label items] {::id id ::active-item nil ::label label ::items items ::open? false :type dropdown-table})
(defn dropdown-ident [id-or-props]
(if (map? id-or-props)
[(:type id-or-props) (::id id-or-props)]
[dropdown-table id-or-props]))
(defn dropdown-item-ident [id-or-props]
(if (map? id-or-props)
(dropdown-item-ident (::id id-or-props))
[dropdown-item-table id-or-props]))
(m/defmutation set-dropdown-open
"Mutation. Set the open flag to true/false to open/close the dropdown."
[{:keys [id open?]}]
(action [{:keys [state]}]
(let [kpath (conj (dropdown-ident id) ::open?)]
(swap! state assoc-in kpath open?))))
(defn set-dropdown-item-active* [state-map dropdown-id item-id]
(assoc-in state-map (conj (dropdown-ident dropdown-id) ::active-item) item-id))
(m/defmutation set-dropdown-item-active
"Mutation. Set one of the items in a dropdown to active.
id - the ID of the dropdown
item-id - the ID of the dropdown item
"
[{:keys [id item-id]}]
(action [{:keys [state]}]
(swap! state set-dropdown-item-active* id item-id)))
(defn- close-all-dropdowns-impl [dropdown-map]
(reduce (fn [m id] (assoc-in m [id ::open?] false)) dropdown-map (keys dropdown-map)))
(m/defmutation close-all-dropdowns
"Mutations: Close all dropdowns (globally)"
[ignored]
(action [{:keys [state]}]
(swap! state update dropdown-table close-all-dropdowns-impl)))
(defui ^:once DropdownItem
static prim/IQuery
(query [this] [::id ::label ::active? ::disabled? :type])
static prim/Ident
(ident [this props] (dropdown-item-ident props))
Object
(render [this]
(let [{:keys [::label ::id ::disabled?]} (prim/props this)
active? (prim/get-computed this :active?)
onSelect (or (prim/get-computed this :onSelect) identity)]
(if (= ::divider label)
(dom/li #js {:key id :role "separator" :className "divider"})
(dom/li #js {:key id :className (cond-> ""
disabled? (str " disabled")
active? (str " active"))}
(dom/a #js {:onClick (fn [evt]
(.stopPropagation evt)
(onSelect id)
false)} (tr-unsafe label)))))))
(let [ui-dropdown-item-factory (prim/factory DropdownItem {:keyfn ::id})]
(defn ui-dropdown-item
"Render a dropdown item. The props are the state props of the dropdown item. The additional by-name
arguments:
onSelect - The function to call when a menu item is selected
active? - render this item as active
"
[props & {:keys [onSelect active?]}]
(ui-dropdown-item-factory (prim/computed props {:onSelect onSelect :active? active?}))))
(defui ^:once Dropdown
static prim/IQuery
(query [this] [::id ::active-item ::label ::open? {::items (prim/get-query DropdownItem)} :type])
static prim/Ident
(ident [this props] (dropdown-ident props))
Object
(render [this]
(let [{:keys [::id ::label ::active-item ::items ::open?]} (prim/props this)
{:keys [onSelect kind stateful? value]} (prim/get-computed this)
active-item-label (->> items
(some #(and (= active-item (::id %)) %))
::label)
value-label (->> items
(some #(and (= value (::id %)) %))
::label)
label (cond
(and value value-label) value-label
(and active-item-label stateful?) active-item-label
:otherwise label)
onSelect (fn [item-id]
(prim/transact! this `[(close-all-dropdowns {}) (set-dropdown-item-active ~{:id id :item-id item-id})])
(when onSelect (onSelect item-id)))
open-menu (fn [evt]
(.stopPropagation evt)
(prim/transact! this `[(close-all-dropdowns {}) (set-dropdown-open ~{:id id :open? (not open?)})])
false)]
(button-group {:className (if open? "open" "")}
(button {:className (cond-> "dropdown-toggle"
kind (str " btn-" (name kind))) :aria-haspopup true :aria-expanded open? :onClick open-menu}
(tr-unsafe label) " " (dom/span #js {:className "caret"}))
(dom/ul #js {:className "dropdown-menu"}
(map #(ui-dropdown-item % :onSelect onSelect :active? (cond
stateful? (= (::id %) active-item)
value (= value (::id %)))) items))))))
(let [ui-dropdown-factory (prim/factory Dropdown {:keyfn ::id})]
(defn ui-dropdown
"Render a dropdown. The props are the state props of the dropdown. The additional by-name
arguments:
onSelect - The function to call when a menu item is selected
stateful? - If set to true, the dropdown will remember the selection and show it.
kind - The kind of dropdown. See `button`."
[props & {:keys [onSelect kind value stateful?] :as attrs}]
(ui-dropdown-factory (prim/computed props attrs))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NAV (tabs/pills)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def nav-table :bootstrap.nav/by-id)
(def nav-link-table :bootstrap.navitem/by-id)
(defn nav-link
"Creates a navigation link. ID must be globally unique. The label will be run through `tr-unsafe`, so it can be
internationalized. "
[id label disabled?]
{::id id ::label label ::disbled? disabled? :type nav-link-table})
(defn nav-link-ident [id-or-props]
(if (map? id-or-props)
[(:type id-or-props) (::id id-or-props)]
[nav-link-table id-or-props]))
(defn nav-ident [id-or-props]
(if (map? id-or-props)
[nav-table (::id id-or-props)]
[nav-table id-or-props]))
(defn nav
"Creates a navigation control.
- kind - One of :tabs or :pills
- layout - One of :normal, :stacked or :justified
- active-link-id - Which of the nested links is the active one
- links - A vector of `nav-link` or `dropdown` instances."
[id kind layout active-link-id links]
{::id id ::kind kind ::layout layout ::active-link-id active-link-id ::links links})
(defui ^:once NavLink
static prim/IQuery
(query [this] [::id ::label ::disabled? :type])
static prim/Ident
(ident [this props] (nav-link-ident props))
Object
(render [this]
(let [{:keys [::id ::label ::disabled?]} (prim/props this)
{:keys [onSelect active?]} (prim/get-computed this)]
(dom/li #js {:role "presentation" :className (cond-> ""
active? (str " active")
disabled? (str " disabled"))}
(dom/a #js {:onClick #(when onSelect (onSelect id))} (tr-unsafe label))))))
(def ui-nav-link (prim/factory NavLink {:keyfn ::id}))
(defui ^:once NavItemUnion
static prim/Ident
(ident [this {:keys [::id type]}] [type id])
static prim/IQuery
(query [this] {dropdown-table (prim/get-query Dropdown) nav-link-table (prim/get-query NavLink)})
Object
(render [this]
(let [{:keys [type ::items] :as child} (prim/props this)
{:keys [onSelect active-id active?] :as computed} (prim/get-computed this)
stateful? (some #(= active-id (::id %)) items)]
(case type
:bootstrap.navitem/by-id (ui-nav-link (prim/computed child computed))
:bootstrap.dropdown/by-id (ui-dropdown child :onSelect onSelect :stateful? stateful?)
(dom/p nil "Unknown link type!")))))
(def ui-nav-item (prim/factory NavItemUnion {:keyfn ::id}))
(defn set-active-nav-link*
[state-map nav-id link-id]
(update-in state-map (nav-ident nav-id) assoc ::active-link-id link-id))
(m/defmutation set-active-nav-link
"Mutation: Set the active navigation link"
[{:keys [id target]}]
(action [{:keys [state]}]
(swap! state set-active-nav-link* id target)))
(defui ^:once Nav
static prim/Ident
(ident [this props] (nav-ident props))
static prim/IQuery
(query [this] [::id ::kind ::layout ::active-link-id {::links (prim/get-query NavItemUnion)}])
Object
(render [this]
(let [{:keys [::id ::kind ::layout ::active-link-id ::links]} (prim/props this)
{:keys [onSelect]} (prim/get-computed this)
onSelect (fn [nav-id] (when onSelect (onSelect nav-id))
(prim/transact! this `[(set-active-nav-link ~{:id id :target nav-id})]))]
(dom/ul #js {:className (str "nav nav-" (name kind) (case layout :justified " nav-justified" :stacked " nav-stacked" ""))}
(map #(ui-nav-item (prim/computed % {:onSelect onSelect :active-id active-link-id :active? (= (::id %) active-link-id)})) links)))))
(let [nav-factory (prim/factory Nav {:keyfn ::id})]
(defn ui-nav
"Render a nav, which should have state declared with `nav`.
props - a cljs map of the data props
onSelect - an optional named parameter to supply a function that is called when navigation is done.
"
[props & {:keys [onSelect]}]
(nav-factory (prim/computed props {:onSelect onSelect}))))
(defn label
"Wraps children in an (inline) bootstrap label.
props are standard DOM props, with support for the additional:
kind - One of :primary, :success, :warning, :info, :danger. Defaults to :default."
[{:keys [kind] :as props :or {kind :default}} & children]
(let [classes (str "label label-" (name kind) " " (get props :className ""))
attrs (-> (dissoc props :kind)
(assoc :className classes))]
(apply dom/span (clj->js attrs) children)))
(defn badge
"Wraps children in an (inline) bootstrap badge.
props are standard DOM props."
[props & children]
(let [classes (str "badge " (get props :className ""))
attrs (assoc props :className classes)]
(apply dom/span (clj->js attrs) children)))
(defn jumbotron
"Wraps children in a jumbotron"
[props & children]
(div-with-class "jumbotron" props children))
(defn alert
"Renders an alert.
Props can contain normal DOM props, and additionally:
kind - The kind of alert: :info, :success, :warning, or :danger. Defaults to `:danger`.
onClose - What to do when the close button is pressed. If nil, close will not be rendered."
[{:keys [kind onClose] :as props} & children]
(let [classes (str (:className props) " alert alert-dismissable alert-" (if kind (name kind) "danger"))
attrs (-> props
(dissoc :kind :onClose)
(assoc :role "alert" :className classes)
clj->js)]
(apply dom/div attrs (if onClose
(close-button {:onClick onClose})
"") children)))
(defn caption
"Renders content that has padding and a lightened color for the font."
[props & children]
(div-with-class "caption" props children))
(defn thumbnail
"Renders a box around content. Typically used to double-box and image or generate Pinterest-style blocks."
[props & children]
(div-with-class "thumbnail" props children))
(defn progress-bar
"Render's a progress bar from an input of the current progress (a number from 0 to 100).
:current - The current value of progress (0 to 100)
:animated? - Should the bar have a striped animation?
:kind - One of :success, :warning, :danger, or :info
Any classname or other properties included will be placed on the top-level div of the progress bar.
"
[{:keys [current kind animated?] :or {kind :info} :as props}]
(let [attrs (dissoc props :current :kind :animated?)]
(div-with-class "progress" attrs
[(dom/div #js {:className (str "progress-bar progress-bar-" (name kind)
(when animated? " progress-bar-striped active")) :role "progressbar" :aria-valuenow current
:aria-valuemin 0 :aria-valuemax 100 :style #js {:width (str current "%")}})])))
(defn panel
"Render a panel. Use `panel-heading`, `panel-title`, `panel-body`, and `panel-footer` for elements of the panel.
:kind is one of :primary, :success, :info, :warning, or :danger"
[{:keys [kind] :or {kind :default} :as props} & children]
(div-with-class (str "panel panel-" (name kind)) props children))
(defn panel-group
"A wrapper for panels that visually groups them together."
[props & children]
(div-with-class "panel-group" props children))
(defn panel-heading
"Render a heading area in a panel. Must be first. Optional."
[props & children]
(div-with-class "panel-heading" props children))
(defn panel-title
"Render a title in a panel. Must be in a `panel-heading`."
[props & children]
(div-with-class "panel-title" props children))
(defn panel-body
"Render children in the body of a panel. Not needed for tables or list groups. Should come after (optional) panel-heading."
[props & children]
(div-with-class "panel-body" props children))
(defn panel-footer
"Render children in a footer of a panel."
[props & children]
(div-with-class "panel-footer" props children))
(defn well
"Inset content.
size - Optional to increase or decrease size. Can be :sm or :lg"
[{:keys [size] :as props} & children]
(div-with-class (str "well " (when size (str "well-" (name size)))) (dissoc props :size) children))
(defn get-abs-position
"Get a map (with the keys :left and :top) that has the absolute position of the given DOM element."
[ele]
#?(:clj {}
:cljs (let [doc (.-ownerDocument ele)
win (or (.-defaultView doc) js/window)
box (.getBoundingClientRect ele)]
{:width (.-width box)
:height (.-height box)
:left (+ (.-left box) (.-scrollX win))
:top (+ (.-top box) (.-scrollY win))})))
; we're using owner document to make sure this works in iframes, where js/document would be wrong
(defui RenderInBody
Object
(renderLayer [this]
#?(:cljs (let [child (first (prim/children this))
popup (.-popup this)]
(.render js/ReactDOM child popup))))
(componentDidMount [this]
#?(:cljs (let [doc (some-> (.-doc-element this) .-ownerDocument)
popup (when doc (.createElement doc "div"))]
(set! (.-popup this) popup)
(when doc (.appendChild (.-body doc) popup))
(.renderLayer this))))
(componentDidUpdate [this np ns] (.renderLayer this))
(shouldComponentUpdate [this np ns] true)
(componentWillUnmount [this]
#?(:cljs (let [doc (some-> (.-doc-element this) .-ownerDocument)
popup (.-popup this)]
(.unmountComponentAtNode js/ReactDOM (.-popup this))
(when doc
(.removeChild (.-body doc) (.-popup this))))))
(render [this] (dom/div #js {:key "placeholder" :ref (fn [r] (set! (.-doc-element this) r))})))
(def ui-render-in-body (prim/factory RenderInBody {:keyfn :key}))
(defsc PopOverContent [this props] (dom-with-class dom/div "popover-content" props (prim/children this)))
(def ui-popover-content (prim/factory PopOverContent))
(defsc PopOverTitle [this props] (dom-with-class dom/h3 "popover-title" props (prim/children this)))
(def ui-popover-title (prim/factory PopOverTitle))
(defsc PopOverTarget [this props] (dom-with-class dom/span "" props (prim/children this)))
(def ui-popover-target (prim/factory PopOverTarget))
(defsc PopOver [this {:keys [active orientation] :or {orientation :top}}]
{:componentWillUpdate (fn [new-props new-state]
(let [old-props (prim/props this)
becoming-active? (and (:active new-props) (not (:active old-props)))]
(when becoming-active? (prim/update-state! this update :render-for-size inc))))}
(let [target (.-target-ref this)
popup (.-popup-ref this)
popup-box (if popup (get-abs-position popup) {})
target-box (if target (get-abs-position target) {})
deltaY (case orientation
:bottom (:height target-box)
:left (-> (:height target-box)
(- (:height popup-box))
(/ 2))
:right (-> (:height target-box)
(- (:height popup-box))
(/ 2))
(- (:height popup-box)))
deltaX (case orientation
:left (- (:width popup-box))
:right (:width target-box)
(/ (- (:width target-box) (:width popup-box)) 2))
popupTop (if active (+ (:top target-box) deltaY) -1000)
popupLeft (if active (+ (:left target-box) deltaX) -1000)
children (prim/children this)
content (util/first-node PopOverContent children)
title (util/first-node PopOverTitle children)
target (util/first-node PopOverTarget children)]
(dom/span #js {:style #js {:display "inline-block"} :ref (fn [r] (set! (.-target-ref this) r))}
(ui-render-in-body {}
(dom/div #js {:className (str "popover fade " (name orientation) (when active " in"))
:ref (fn [r] (set! (.-popup-ref this) r))
:style #js {:position "absolute"
:top (str popupTop "px")
:left (str popupLeft "px")
:display "block"}}
(dom/div #js {:className "arrow" :style #js {:left (case orientation
:left "100%"
:right "-11px"
"50%")}})
(when title) title
(when content) content))
target)))
(def ui-popover (prim/factory PopOver))
(defn modal-ident
"Get the ident for a modal with the given props or ID"
[props-or-id]
(if (map? props-or-id)
[:fulcro.ui.boostrap3.modal/by-id (:db/id props-or-id)]
[:fulcro.ui.boostrap3.modal/by-id props-or-id]))
(defn- show-modal* [modal tf]
(assoc modal :modal/visible tf))
(defn- activate-modal* [modal tf]
(assoc modal :modal/active tf))
#?(:cljs
(defmutation show-modal
"Mutation: Show a modal by ID."
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state update-in (modal-ident id) show-modal* true)
(js/setTimeout (fn [] (swap! state update-in (modal-ident id) activate-modal* true)) 10))))
#?(:cljs
(defmutation hide-modal
"mutation: Hide a modal by ID."
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state update-in (modal-ident id) activate-modal* false)
(js/setTimeout (fn [] (swap! state update-in (modal-ident id) show-modal* false)) 300))))
(defui ^:once ModalTitle
Object
(render [this]
(apply dom/div (clj->js (prim/props this)) (prim/children this))))
(def ui-modal-title (prim/factory ModalTitle {:keyfn (fn [props] "modal-title")}))
(defui ^:once ModalBody
Object
(render [this]
(div-with-class "modal-body" (prim/props this) (prim/children this))))
(def ui-modal-body (prim/factory ModalBody {:keyfn (fn [props] "modal-body")}))
(defui ^:once ModalFooter
Object
(render [this]
(div-with-class "modal-footer" (prim/props this) (prim/children this))))
(def ui-modal-footer (prim/factory ModalFooter {:keyfn (fn [props] "modal-footer")}))
(defui ^:once Modal
static prim/InitialAppState
(initial-state [c {:keys [id sz backdrop keyboard] :or {backdrop true keyboard true}}]
{:db/id id :modal/active false :modal/visible false :modal/keyboard keyboard
:modal/size sz :modal/backdrop (boolean backdrop)})
static prim/Ident
(ident [this props] (modal-ident props))
static prim/IQuery
(query [this] [:db/id :modal/active :modal/visible :modal/size :modal/backdrop :modal/keyboard])
Object
(componentDidMount [this] (.focus (.-the-dialog this)))
(componentDidUpdate [this pp _] (when (and (:modal/visible (prim/props this)) (not (:modal/visible pp))) (.focus (.-the-dialog this))))
(render [this]
(let [{:keys [db/id modal/active modal/visible modal/size modal/keyboard modal/backdrop]} (prim/props this)
{:keys [onClose]} (prim/get-computed this)
onClose (fn []
(prim/transact! this `[(hide-modal {:id ~id})])
(when onClose (onClose id)))
children (prim/children this)
label-id (str "modal-label-" id)
title (util/first-node ModalTitle children)
body (util/first-node ModalBody children)
footer (util/first-node ModalFooter children)]
(dom/div #js {:role "dialog" :aria-labelledby label-id
:ref (fn [r] (set! (.-the-dialog this) r))
:onKeyDown (fn [evt] (when (and keyboard (evt/escape-key? evt)) (onClose)))
:style #js {:display (if visible "block" "none")}
:className (str "modal fade" (when active " in")) :tabIndex "-1"}
(dom/div #js {:role "document" :className (str "modal-dialog" (when size (str " modal-" (name size))))}
(dom/div #js {:className "modal-content"}
(dom/div #js {:key "modal-header" :className "modal-header"}
(dom/button #js {:type "button" :onClick onClose :aria-label "Close" :className "close"}
(dom/span #js {:aria-hidden "true"} ent/times))
(when title
(dom/h4 #js {:key label-id :id label-id :className "modal-title"} title)))
(when body body)
(when footer footer)))
(when (and backdrop visible)
(ui-render-in-body {}
(dom/div #js {:key "backdrop" :className (str "modal-backdrop fade" (when active " in"))})))))))
(let [modal-factory (prim/factory Modal {:keyfn (fn [props] (str "modal-" (:db/id props)))})]
(defn ui-modal
"Render a modal.
Modals are stateful. You must compose in initial state and a query. Modals also have IDs.
Modal content should include a ui-modal-title, ui-modal-body, and ui-modal-footer as children. The footer usually contains
one or more buttons.
Use the `prim/get-initial-state` function to pull a valid initial state for this component. The arguments are:
`(prim/get-initial-state Modal {:id ID :sz SZ :backdrop BOOLEAN})`
where the id is required (and must be unique among modals, and `:sz` is optional and must be `:sm` or `:lg`. The
:backdrop option is boolean, and indicates you want a backdrop that blocks the UI. The `:keyboard` option
defaults to true and enables removal of the dialog with `ESC`.
When rendering the modal, it typically looks something like this:
````
(b/ui-modal modal
(b/ui-modal-title nil
(dom/b nil \"WARNING!\"))
(b/ui-modal-body nil
(dom/p #js {:className b/text-danger} \"Stuff went sideways.\"))
(b/ui-modal-footer nil
(b/button {:onClick #(prim/transact! this `[(b/hide-modal {:id :warning-modal})])} \"Bummer!\"))))))
````
NOTE: The grid (`row` and `col`) can be used within the modal body *without* a `container`.
See the developer's guide for an example in the N15-Twitter-Bootstrap-Components section.
Available mudations: `b/show-modal` and `b/hide-modal`."
[props & children]
(apply modal-factory props children)))
(defn collapse-ident [id-or-props]
(if (map? id-or-props)
[:fulcro.ui.bootstrap3.collapse/by-id (:db/id id-or-props)]
[:fulcro.ui.bootstrap3.collapse/by-id id-or-props]))
(defui Collapse
static prim/InitialAppState
(initial-state [c {:keys [id start-open]}] {:db/id id :collapse/phase :closed})
static prim/Ident
(ident [this props] (collapse-ident props))
static prim/IQuery
(query [this] [:db/id :collapse/phase])
Object
(render [this]
(let [{:keys [db/id collapse/phase]} (prim/props this)
dom-ele (.-dom-element this)
box-height (when dom-ele (.-height (.getBoundingClientRect dom-ele)))
height (when dom-ele
(case phase
:opening-no-height nil
:opening (str (.-scrollHeight dom-ele) "px")
:open nil
:closing (str box-height "px")
"0px"))
children (prim/children this)
classes (case phase
:open "collapse in"
:closed "collapse"
"collapsing")]
(apply dom/div #js {:className classes :style #js {:height height} :ref (fn [r] (set! (.-dom-element this) r))} children))))
(def ui-collapse
"Render a collapse component that can height-animate in/out children. The props should be state from the
app database initialized with `get-initial-state` of a Collapse component,
and the children should be the elements you want to show/hide. Each component should have a unique
(application-wide) ID. Use the `toggle-collapse` and `set-collapse` mutations to open/close. "
(prim/factory Collapse {:keyfn :db/id}))
(defn- is-stable?
"Returns true if the given collapse item is not transitioning"
[collapse-item]
(#{:open :closed} (:collapse/phase collapse-item)))
(defn- set-collapse*
"state is a state atom"
[state id open]
; phases [:opening-no-height :opening :open :closing :closed]
(let [cident (collapse-ident id)
item (get-in @state cident)
ppath (conj cident :collapse/phase)]
(when (is-stable? item)
(if open
(do
(swap! state assoc-in ppath :opening-no-height)
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :opening)) 16))
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :open)) 350)))
(do
(swap! state assoc-in ppath :closing)
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :close-height)) 16))
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :closed)) 350)))))))
(defmutation toggle-collapse
"mutation: Toggle a collapse"
[{:keys [id]}]
(action [{:keys [state]}]
(let [cident (collapse-ident id)
ppath (conj cident :collapse/phase)
is-open (= :open (get-in @state ppath))]
(set-collapse* state id (not is-open)))))
(defmutation set-collapse
"mutation: Set the state of a collapse."
[{:keys [id open]}]
(action [{:keys [state]}]
(set-collapse* state id open)))
(defmutation toggle-collapse-group-item
"mutation: Toggle a collapse element as if in a group.
item-id: The specific group to toggle
all-item-ids: A collection of all of the items that are to be considered part of the group. If any items are
in transition, this is a no-op."
[{:keys [item-id all-item-ids]}]
(action [{:keys [state]}]
(let [all-ids (set all-item-ids)
all-items (map #(get-in @state (collapse-ident %)) all-ids)
item-to-toggle (get-in @state (collapse-ident item-id))
closing? (= :open (:collapse/phase item-to-toggle))
stable? (every? is-stable? all-items)]
(when stable?
(if closing?
(set-collapse* state item-id false)
(let [open? (fn [item] (= :open (:collapse/phase item)))
ids-to-close (->> all-items
(filter open?)
(map :db/id))]
(doseq [id ids-to-close]
(set-collapse* state id false))
(set-collapse* state item-id true)))))))
(defn carousel-ident [props-or-id]
(if (map? props-or-id)
[:fulcro.ui.bootstrap3.carousel/by-id (:db/id props-or-id)]
[:fulcro.ui.bootstrap3.carousel/by-id props-or-id]))
(defui CarouselItem
Object
(render [this]
(let [{:keys [src alt] :as props} (prim/props this)
caption (prim/children this)]
(dom/div #js {:key (hash src)}
(dom/img #js {:src src :alt alt})
(when (seq caption)
(dom/div #js {:className "carousel-caption"}
caption))))))
(def ui-carousel-item
"Render a carousel item. Props can include src and alt for the image. If children are supplied, they will be
treated as the caption."
(prim/factory CarouselItem {:keyfn :index}))
(defmutation carousel-slide-to
"mutation: Slides a carousel from the current frame to the indicated frame. The special `frame` value of `:wrap`
can be used to slide from the current frame to the first as if wrapping in a circle."
[{:keys [id frame]}]
(action [{:keys [state]}]
(let [cident (carousel-ident id)
carousel (get-in @state cident)
{:keys [carousel/timer-id carousel/paused carousel/active-index
carousel/slide-to carousel/interval]} carousel
new-timer-id (when (not slide-to)
#?(:cljs (js/setTimeout (fn []
(swap! state update-in (carousel-ident id)
assoc
:carousel/timer-id nil
:carousel/active-index frame
:carousel/slide-to nil)) 600)))]
(when (not slide-to)
#?(:cljs (when timer-id
(js/clearTimeout timer-id)))
(swap! state assoc :carousel/slide-to frame :carousel/timer-id new-timer-id)))))
(defui Carousel
static prim/InitialAppState
(initial-state [c {:keys [id interval wrap keyboard pause-on-hover show-controls]
:or {interval 5000 wrap true keyboard true pause-on-hover true show-controls true}}]
{:db/id id
:carousel/interval interval
:carousel/active-index 0
:carousel/show-controls show-controls
:carousel/wrap wrap
:carousel/keyboard keyboard
:carousel/pause-on-hover pause-on-hover
:carousel/paused false
:carousel/timer-id nil})
static prim/Ident
(ident [this props] (carousel-ident props))
static prim/IQuery
(query [this] [:db/id :carousel/active-index :carousel/slide-to :carousel/show-controls])
Object
(render [this]
(let [items (prim/children this)
slide-count (count items)
{:keys [db/id carousel/active-index carousel/slide-to carousel/show-controls]} (prim/props this)
to (if (= :wrap slide-to) 0 slide-to)
sliding? (and slide-to (not= active-index slide-to))
prior-index (if (zero? active-index) (dec slide-count) (dec active-index))
next-index (if (= (dec slide-count) active-index) 0 (inc active-index))
goto (fn [slide] (prim/transact! this `[(carousel-slide-to {:id ~id :frame ~slide})]))
from-the-left? (or (= :wrap slide-to) (< active-index slide-to))
active-item-class (str "item active "
(when sliding? (if from-the-left? "left" "right")))
slide-to-class (str "item " (when sliding? (if from-the-left? "next left" "next right")))]
(dom/div #js {:className "carousel slide"
:onKeyDown (fn [e]
(.preventDefault e) ; TODO: not getting key evts
(.stopPropagation e)
(cond
(evt/left-arrow? e) (goto prior-index)
(evt/right-arrow? e) (goto next-index))
false)}
(dom/ol #js {:className "carousel-indicators"}
(map #(dom/li #js {:key % :className (str "" (when (= % active-index) "active"))} "") (range slide-count)))
; TODO: extra div needs unwrapped, but is already rendered
(dom/div #js {:className "carousel-inner" :role "listbox"}
(map-indexed (fn [idx i]
(dom/div #js {:className (cond
(= idx to) slide-to-class
(= idx active-index) active-item-class
:else "")} i))
items))
(when show-controls
(dom/a #js {:onClick #(goto prior-index) :className "left carousel-control" :role "button"}
(glyphicon {:aria-hidden true} :chevron-left)
(dom/span #js {:className "sr-only"} "Previous"))
(dom/a #js {:onClick #(goto next-index) :className "right carousel-control" :role "button"}
(glyphicon {:aria-hidden true} :chevron-right)
(dom/span #js {:className "sr-only"} "Next")))))))
; TODO: above is untested...might work ;)
(def ui-carousel (prim/factory Carousel {:keyfn :db/id}))
;; TODO: Carousel (stateful)
;; TODO: Scrollspy (spy-link component that triggers mutation + scrollspy component that gets updated on those mutations)
;; TODO: Affix (similar to scrollspy in terms of interactions)
;; TODO: Media Object
;; TODO: List Group with table etc integrations
|
85469
|
(ns fulcro.ui.bootstrap3
(:require [fulcro.client.dom :as dom]
[fulcro.client.primitives :as prim :refer [defui defsc]]
[fulcro.ui.elements :as ele]
[fulcro.events :as evt]
[fulcro.ui.html-entities :as ent]
[fulcro.i18n :refer [tr tr-unsafe]]
[fulcro.client.mutations :as m :refer [defmutation]]
#?(:clj
[clojure.future :refer :all])
[clojure.string :as str]
[clojure.set :as set]
[fulcro.client :as fc]
[fulcro.logging :as log]
[fulcro.client.util :as util]))
#?(:clj (defn- clj->js [m] m))
;; Bootstrap CSS and Components for Fulcro
(defn- dom-with-class [dom-factory cls attrs children]
(let [attrs (-> attrs
#_(update :key (fnil identity "placeholder-key"))
(update :className #(str cls " " %)))]
(apply dom-factory (clj->js attrs) children)))
(defn- div-with-class [cls attrs children] (dom-with-class dom/div cls attrs children))
(defn- p-with-class [cls attrs children] (dom-with-class dom/p cls attrs children))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; BASE CSS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn container
"Top-level container for bootstrap grid content. This is a responsive fixed-width container. See also container-fluid."
[attrs & children] (div-with-class "container" attrs children))
(defn container-fluid
"Top-level container for bootstrap grid content. This is a responsive full-width container. See also container."
[attrs & children] (div-with-class "container-fluid" attrs children))
(defn row
"Generate a layout row. This is a div container for a row in a 12-wide grid responsive layout.
Rows should contain layout columns generated with the `col` function of this namespace.
The properties are normal DOM attributes as a cljs map and can include standard React DOM properties.
"
[props & children]
(div-with-class "row" props children))
(defn col
"Output a div that represents a column in the 12-column responsive grid.
Any React props are allowed. The following special one pertain to the column:
xs The width of the column on xs screens
sm The width of the column on sm screens
md The width of the column on md screens
lg The width of the column on lg screens
xs-offset The offset of the column on xs screens
sm-offset The offset of the column on sm screens
md-offset The offset of the column on md screens
lg-offset The offset of the column on lg screens
"
[{:keys [className xs sm md lg xs-offset sm-offset md-offset lg-offset] :as props} & children]
(let [classes (cond-> (:className props)
xs (str " col-xs-" xs)
sm (str " col-sm-" sm)
md (str " col-md-" md)
lg (str " col-lg-" lg)
xs-offset (str " col-xs-offset-" xs-offset)
sm-offset (str " col-sm-offset-" sm-offset)
md-offset (str " col-md-offset-" md-offset)
lg-offset (str " col-lg-offset-" lg-offset))
attrs (-> props
(dissoc :xs :sm :md :lg :xs-offset :sm-offset :md-offset :lg-offset)
(assoc :className classes)
clj->js)]
(apply dom/div attrs children)))
(defn lead
"Generates a lead paragraph with an increased font size."
[attrs & children]
(p-with-class "lead" attrs children))
(defn address
"Formats an address"
[name & {:keys [street street2 city-state phone email]}]
(let [brs (repeatedly #(dom/br nil))
children (cond-> (vec (keep identity (list street street2 city-state)))
phone (conj (dom/span nil (dom/abbr #js {:title "Phone"} "P:") phone)))]
(apply dom/address nil
(dom/strong nil name) (dom/br nil)
(vec (interleave children brs)))))
(defn quotation
"Render a block quotation with optional citation and source.
align - :right or :left (default)
credit - The name of the person.
source - The place where it was said/written, you supply the joining preposition.
children - The DOM element(s) (typicaly a p) that represent the body of the quotation
"
[{:keys [align credit source] :as attrs} & children]
(let [attrs (cond-> (dissoc attrs :align :credit :source)
(= :right align) (assoc :className (str "blockquote-reverse " (:className attrs))))
content (concat children [(dom/footer nil credit " " (dom/cite nil source))])]
(apply dom/blockquote (clj->js attrs) content)))
(defn plain-ul
"Render an unstyled unordered list"
[attrs & children]
(let [attrs (update attrs :className #(str " list-unstyled"))]
(apply dom/ul (clj->js attrs) children)))
(defn inline-ul
"Render an inline unordered list"
[attrs & children]
(let [attrs (update attrs :className #(str " list-inline"))]
(apply dom/ul (clj->js attrs) children)))
(def table-styles #{:striped :bordered :condensed :hover})
(defn table
"Renders a table. attrs can contain any normal react attributes, including :className.
Extended attributes that you can include are:
styles - A set of one or more of: #{:striped :bordered :condensed :hover}
"
[{:keys [className styles] :as attrs} & children]
(let [style-classes (str/join " " (map #(str "table-" (name %)) (set/intersection table-styles styles)))
classes (str (when className (str className " ")) "table " style-classes)
attrs (-> attrs
(dissoc :styles)
(assoc :className classes)
clj->js)]
(apply dom/table attrs children)))
(defn form-horizontal
"Set up a container for labeled inputs (which should have :split) to render the labels beside the fields."
[attrs & children]
(div-with-class "form-horizontal" attrs children))
(defn labeled-input
"An input with a label. All of the attrs apply to the input itself. You must supply a type and id for the
field to work correctly. DO NOT USE for checkbox or radio.
The additional attributes are supported:
:split - A number from 1 to 11. The number of `sm` columns to allocate to the field label. If not specified, the
label will be above the input. The parent must use the `.form-horizontal` class.
:help - A string. If supplied, displayed as the help text for the field. NOT shown if warning, error, or success are set.
:input-generator An (optional) function of `props -> input` to be called to generate the DOM input. It will receive a clj map
of properties and should return an input that has those minimum properties. It can, of course, augment those.
You should only ever supply zero or one of the following:
:warning - A boolean or string. If set as a string, that content replaces the help text.
:error - A boolean or string. If set as a string, that content replaces the help text.
:success - A boolean or string. If set as a string, that content replaces the help text.
"
[{:keys [id type className placeholder split help warning error success
input-generator] :as attrs} label]
(let [state-class (cond
error " has-error"
warning " has-warning"
success " has-success"
:else "")
form-group-classes (str "form-group" state-class)
help (first (keep identity [error warning success help]))
split-right (- 12 split)
help-id (str id "-help")
attrs (cond-> (dissoc attrs :split :help :warning :error :success :input-generator)
help (assoc :aria-describedby help-id)
:always (update :className #(str % " form-control")))]
(cond
(int? split) (dom/div #js {:className form-group-classes}
(dom/label #js {:className (str "control-label col-sm-" split) :htmlFor id} label)
(dom/div #js {:className (str "col-sm-" split-right)}
(if input-generator
(input-generator attrs)
(dom/input (clj->js attrs)))
(when help (dom/span #js {:id help-id :className "help-block"} help))))
:else (dom/div #js {:className form-group-classes}
(dom/label #js {:className "control-label" :htmlFor id} label)
(if input-generator
(input-generator attrs)
(dom/input (clj->js attrs)))
(when help (dom/span #js {:id help-id :className "help-block"} help))))))
(defn button
"Render a button with optional styling
kind - Optional. One of :primary, :success, :info, :warning, or :danger. Defaults to none (default).
size - Optional. One of :xs, :sm, or :lg. Defaults to a normal size.
as-block - Optional. Boolean. When true makes the button a block element.
"
[{:keys [kind size as-block] :as attrs} & children]
{:pre [(or (nil? kind) (contains? #{:primary :success :info :warning :danger} kind))
(or (nil? size) (contains? #{:xs :sm :lg} size))]}
(let [incoming-classes (:className attrs)
button-classes (cond-> "btn"
kind (str " btn-" (name kind))
size (str " btn-" (name size))
(not kind) (str " btn-default")
as-block (str " btn-block")
incoming-classes (str " " incoming-classes))
attrs (-> attrs
(dissoc :kind :size :as-block)
(assoc :className button-classes)
clj->js)]
(apply dom/button attrs children)))
(defn close-button [attrs]
(let [addl-classes (:className attrs)
classes (cond-> "close"
addl-classes (str " " addl-classes))
attrs (assoc attrs :type "button" :aria-label "Close" :className classes)]
(dom/button (clj->js attrs)
(dom/span #js {:aria-hidden true} "\u00D7"))))
(defn img
"Render an img tag with bootstrap classes.
is-responsive - Boolean. Marks the image so that it scales to its container.
shape - Optional. One of :rounded, :circle, or :thumbnail
All other normal react attributes (including className) are allowed."
[{:keys [is-responsive shape] :as attrs}]
{:pre [(or (nil? shape) (contains? #{:rounded :circle :thumbnail} shape))]}
(let [incoming-classes (:className attrs)
button-classes (cond-> ""
shape (str " " "img-" (name shape))
is-responsive (str " img-responsive")
incoming-classes (str " " incoming-classes))
attrs (-> attrs
(dissoc :is-responsive :shape)
(assoc :className button-classes)
clj->js)]
(dom/img attrs)))
;; raw classes (for docstrings and autocomplete
(def text-left "A CSS class for Left aligned text." "text-left")
(def text-center "A CSS class for Center aligned text." "text-center")
(def text-right "A CSS class for Right aligned text." "text-right")
(def text-justify "A CSS class for Justified text." "text-justify")
(def text-nowrap "A CSS class for No wrap text." "text-nowrap")
(def text-lowercase "A css transform that will change encosed text to lowercased text." "text-lowercase")
(def text-uppercase "A css transform that will change encosed text to uppercased text." "text-uppercase")
(def text-capitalize "A css transform that will change encosed text to capitalized text." "text-capitalize")
(def text-muted "CSS class for a muted text color" "text-muted")
(def text-primary "A CSS classname for a primary text color" "text-primary")
(def text-success "A CSS classname for a success text color" "text-success")
(def text-info "A CSS classname for a info text color" "text-info")
(def text-warning "A CSS classname for a warning text color" "text-warning")
(def text-danger "A CSS classname for a danger text color" "text-danger")
(def bg-primary "A CSS classname for a contextual primary background color" "bg-primary")
(def bg-success "A CSS classname for a contextual success background color" "bg-success")
(def bg-info "A CSS classname for a contextual info background color" "bg-info")
(def bg-warning "A CSS classname for a contextual warning background color" "bg-warning")
(def bg-danger "A CSS classname for a contextual danger background color" "bg-danger")
(def pull-left "A CSS class for forcing a float" "pull-left")
(def pull-right "A CSS class for forcing a float" "pull-right")
(def center-block "A CSS class for centering a block element" "center-block")
(def clearfix "A CSS class used on the PARENT to clear floats within that parent." "clearfix")
(def show "A CSS class for BLOCK-level elements. Element affects flow and is visible." "show")
(def hidden "A CSS class for BLOCK-level elements. Element is not in flow." "hidden")
(def invisible "A CSS class for BLOCK-level elements. Element still affects flow." "invisible")
(def visible-xs-block "A responsive CSS class to show element according to screen size" "visible-xs-block")
(def visible-xs-inline "A responsive CSS class to show element according to screen size" "visible-xs-inline")
(def visible-xs-inline-block "A responsive CSS class to show element according to screen size" "visible-xs-inline-block")
(def visible-sm-block "A responsive CSS class to show element according to screen size" "visible-sm-block")
(def visible-sm-inline "A responsive CSS class to show element according to screen size" "visible-sm-inline")
(def visible-sm-inline-block "A responsive CSS class to show element according to screen size" "visible-sm-inline-block")
(def visible-md-block "A responsive CSS class to show element according to screen size" "visible-md-block")
(def visible-md-inline "A responsive CSS class to show element according to screen size" "visible-md-inline")
(def visible-md-inline-block "A responsive CSS class to show element according to screen size" "visible-md-inline-block")
(def visible-lg-block "A responsive CSS class to show element according to screen size" "visible-lg-block")
(def visible-lg-inline "A responsive CSS class to show element according to screen size" "visible-lg-inline")
(def visible-lg-inline-block "A responsive CSS class to show element according to screen size" "visible-lg-inline-block")
(def hidden-xs "A CSS class to hide the element according to screen size" "hidden-xs")
(def hidden-sm "A CSS class to hide the element according to screen size" "hidden-sm")
(def hidden-md "A CSS class to hide the element according to screen size" "hidden-md")
(def hidden-lg "A CSS class to hide the element according to screen size" "hidden-lg")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Bootstrap Components
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def glyph-icons #{:asterisk :plus :euro :eur :minus :cloud :envelope :pencil :glass :music :search :heart
:star :star-empty :user :film :th-large :th :th-list :ok :remove :zoom-in :zoom-out :off :signal
:cog :trash :home :file :time :road :download-alt :download :upload :inbox :play-circle
:repeat :refresh :list-alt :lock :flag :headphones :volume-off :volume-down :volume-up :qrcode
:barcode :tag :tags :book :bookmark :print :camera :font :bold :italic :text-height
:text-width :align-left :align-center :align-right :align-justify :list :indent-left :indent-right
:facetime-video :picture :map-marker :adjust :tint :edit :share :check :move :step-backward
:fast-backward :backward :play :pause :stop :forward :fast-forward :step-forward :eject
:chevron-left :chevron-right :plus-sign :minus-sign :remove-sign :ok-sign :question-sign
:info-sign :screenshot :remove-circle :ok-circle :ban-circle :arrow-left :arrow-right :arrow-up
:arrow-down :share-alt :resize-full :resize-small :exclamation-sign :gift :leaf :fire :eye-open
:eye-close :warning-sign :plane :calendar :random :comment :magnet :chevron-up :chevron-down
:retweet :shopping-cart :folder-close :folder-open :resize-vertical :resize-horizontal :hdd :bullhorn :bell
:certificate :thumbs-up :thumbs-down :hand-right :hand-left :hand-up :hand-down :circle-arrow-right :circle-arrow-left
:circle-arrow-up :circle-arrow-down :globe :wrench :tasks :filter :briefcase :fullscreen :dashboard
:paperclip :heart-empty :link :phone :pushpin :usd :gbp :sort :sort-by-alphabet
:sort-by-alphabet-alt :sort-by-order :sort-by-order-alt :sort-by-attributes :sort-by-attributes-alt :unchecked
:expand :collapse-down :collapse-up :log-in :flash :log-out :new-window :record :save :open :saved :import
:export :send :floppy-disk :floppy-saved :floppy-remove :floppy-save :floppy-open :credit-card :transfer
:cutlery :header :compressed :earphone :phone-alt :tower :stats :sd-video :hd-video
:subtitles :sound-stereo :sound-dolby :sound-5-1 :sound-6-1 :sound-7-1 :copyright-mark :registration-mark :cloud-download
:cloud-upload :tree-conifer :tree-deciduous :cd :save-file :open-file :level-up :copy :paste
:alert :equalizer :king :queen :pawn :bishop :knight :baby-formula :tent
:blackboard :bed :apple :erase :hourglass :lamp :duplicate :piggy-bank :scissors
:bitcoin :btc :xbt :yen :jpy :ruble :rub :scale :ice-lolly
:ice-lolly-tasted :education :option-horizontal :option-vertical :menu-hamburger :modal-window :oil :grain :sunglasses
:text-size :text-color :text-background :object-align-top :object-align-bottom :object-align-horizontal :object-align-left
:object-align-vertical :object-align-right :triangle-right :triangle-left :triangle-bottom :triangle-top
:console :superscript :subscript :menu-left :menu-right :menu-down :menu-up})
(defn glyphicon
"Render a glyphicon in a span. Legal icon names are in b/glyph-icons.
attrs will be added to the span's attributes.
size - The size of the icon font. Defaults to 10pt.
"
[{:keys [size] :or {size "10pt"} :as attrs} icon]
{:pre [(contains? glyph-icons icon)]}
(let [attrs (-> attrs
(dissoc :size)
(assoc :aria-hidden true)
(assoc :style #js {:fontSize size})
(update :className #(str % " glyphicon glyphicon-" (name icon)))
clj->js)]
(dom/span attrs "")))
(defn button-group
"Groups nested buttons together in a horizontal row.
`size` - (optional) can be :xs, :sm, or :lg.
`kind` - (optional) can be :vertical or :justified"
[{:keys [size kind] :as attrs} & children]
(let [justified? (= kind :justified)
vertical? (= kind :vertical)
cls (cond-> "btn-group"
justified? (str " btn-group-justified")
vertical? (str "-vertical")
size (str " btn-group-" (name size)))
wrap-button (fn [ele] (if (ele/react-instance? "button" ele) (button-group {} ele) ele))
attrs (-> attrs (dissoc :size :kind) (assoc :role "group"))
children (if justified? (map #(wrap-button %) children) children)]
(div-with-class cls attrs children)))
(defn button-toolbar
"Groups button groups together as a toolbar, and a bit of space between each group"
[attrs & children]
(div-with-class "btn-toolbar" (assoc attrs :role "toolbar") children))
(defn breadcrumb-item
"Define a breadcrumb.
label - The label to show. You should internationalize this yourself.
onClick - A function. What to do when the item is clicked. Not needed for the last item."
([label] {:label label :onClick identity})
([label onClick] {:label label :onClick onClick}))
(defn breadcrumbs
"props - Properties to place on the top-level `ol`.
items - a list of breadcrumb-item"
[props & items]
(let [attrs (update props :className #(str " breadcrumb"))]
(dom/ol (clj->js attrs)
(conj
(mapv (fn [item] (dom/li #js {:key (:label item)} (dom/a #js {:onClick (:onClick item)} (:label item)))) (butlast items))
(dom/li #js {:key (:label (last items)) :className "active"} (:label (last items)))))))
(defn pagination
"Render a pagination control.
props - A map of properties.
size - One of :sm or :lg
pagination-entries - One or more `pagination-entry`"
[{:keys [size] :as props} & pagination-entries]
(let [classes (cond-> (get props :className "")
:always (str "pagination")
size (str " pagination-" (name size)))
attrs (assoc props :className classes)]
(dom/nav #js {:aria-label "Page Navigation"}
(apply dom/ul (clj->js attrs) pagination-entries))))
(defn pagination-entry
"Create an entry in a pagination control. Forward and back buttons can be rendered at either end with any label, but
the fulcro.ui.html-entities/raqao and laqao defs give a nicely sized font-based arrow."
[{:keys [label disabled active onClick] :as props}]
(let [onClick (if (and onClick (not disabled)) onClick identity)
classes (cond-> (:className props)
disabled (str " disabled")
active (str " active"))
attrs (-> props
(assoc :className classes)
(dissoc :active :label :disabled :onClick))]
(dom/li (clj->js attrs)
(if (or (= label ent/raqao) (= label ent/laqao))
(dom/a #js {:onClick onClick :aria-label (if (= ent/raqao label) "Next" "Previous")}
(dom/span #js {:aria-hidden "true"} label))
(dom/a #js {:onClick onClick}
label (when active (dom/span #js {:className "sr-only"} " (current)")))))))
(defn pager
"A light next/previous pair of controls. Use `pager-next` and `pager-previous` as the children of this."
[props & children]
(let [attrs (-> props
(update :className #(str " pager"))
clj->js)]
(dom/nav #js {:aria-label "Page Navigation"}
(apply dom/ul attrs children))))
(defn pager-next
"Render a next button in a pager"
[{:keys [onClick disabled]} & label-children]
(dom/li #js {:key "next" :className (str "next" (when disabled " disabled"))} (apply dom/a #js {:onClick (or onClick identity)} label-children)))
(defn pager-previous
"Render a previous button in a pager"
[{:keys [onClick disabled]} & label-children]
(dom/li #js {:key "prior" :className (str "previous" (when disabled " disabled"))} (apply dom/a #js {:onClick (or onClick identity)} label-children)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dropdowns
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def dropdown-table :bootstrap.dropdown/by-id)
(def dropdown-item-table :bootstrap.dropdown-item/by-id)
(defn dropdown-item
"Define the state for an item of a dropdown."
[id label] {::id id ::label label})
(defn dropdown-divider
"Creates a divider between items. Must have a unique ID"
[id] {::id id ::label ::divider})
(defn dropdown
"Creates a dropdown's state. Create items with dropdown-item or dropdown-divider."
[id label items] {::id id ::active-item nil ::label label ::items items ::open? false :type dropdown-table})
(defn dropdown-ident [id-or-props]
(if (map? id-or-props)
[(:type id-or-props) (::id id-or-props)]
[dropdown-table id-or-props]))
(defn dropdown-item-ident [id-or-props]
(if (map? id-or-props)
(dropdown-item-ident (::id id-or-props))
[dropdown-item-table id-or-props]))
(m/defmutation set-dropdown-open
"Mutation. Set the open flag to true/false to open/close the dropdown."
[{:keys [id open?]}]
(action [{:keys [state]}]
(let [kpath (conj (dropdown-ident id) ::open?)]
(swap! state assoc-in kpath open?))))
(defn set-dropdown-item-active* [state-map dropdown-id item-id]
(assoc-in state-map (conj (dropdown-ident dropdown-id) ::active-item) item-id))
(m/defmutation set-dropdown-item-active
"Mutation. Set one of the items in a dropdown to active.
id - the ID of the dropdown
item-id - the ID of the dropdown item
"
[{:keys [id item-id]}]
(action [{:keys [state]}]
(swap! state set-dropdown-item-active* id item-id)))
(defn- close-all-dropdowns-impl [dropdown-map]
(reduce (fn [m id] (assoc-in m [id ::open?] false)) dropdown-map (keys dropdown-map)))
(m/defmutation close-all-dropdowns
"Mutations: Close all dropdowns (globally)"
[ignored]
(action [{:keys [state]}]
(swap! state update dropdown-table close-all-dropdowns-impl)))
(defui ^:once DropdownItem
static prim/IQuery
(query [this] [::id ::label ::active? ::disabled? :type])
static prim/Ident
(ident [this props] (dropdown-item-ident props))
Object
(render [this]
(let [{:keys [::label ::id ::disabled?]} (prim/props this)
active? (prim/get-computed this :active?)
onSelect (or (prim/get-computed this :onSelect) identity)]
(if (= ::divider label)
(dom/li #js {:key id :role "separator" :className "divider"})
(dom/li #js {:key id :className (cond-> ""
disabled? (str " disabled")
active? (str " active"))}
(dom/a #js {:onClick (fn [evt]
(.stopPropagation evt)
(onSelect id)
false)} (tr-unsafe label)))))))
(let [ui-dropdown-item-factory (prim/factory DropdownItem {:keyfn ::id})]
(defn ui-dropdown-item
"Render a dropdown item. The props are the state props of the dropdown item. The additional by-name
arguments:
onSelect - The function to call when a menu item is selected
active? - render this item as active
"
[props & {:keys [onSelect active?]}]
(ui-dropdown-item-factory (prim/computed props {:onSelect onSelect :active? active?}))))
(defui ^:once Dropdown
static prim/IQuery
(query [this] [::id ::active-item ::label ::open? {::items (prim/get-query DropdownItem)} :type])
static prim/Ident
(ident [this props] (dropdown-ident props))
Object
(render [this]
(let [{:keys [::id ::label ::active-item ::items ::open?]} (prim/props this)
{:keys [onSelect kind stateful? value]} (prim/get-computed this)
active-item-label (->> items
(some #(and (= active-item (::id %)) %))
::label)
value-label (->> items
(some #(and (= value (::id %)) %))
::label)
label (cond
(and value value-label) value-label
(and active-item-label stateful?) active-item-label
:otherwise label)
onSelect (fn [item-id]
(prim/transact! this `[(close-all-dropdowns {}) (set-dropdown-item-active ~{:id id :item-id item-id})])
(when onSelect (onSelect item-id)))
open-menu (fn [evt]
(.stopPropagation evt)
(prim/transact! this `[(close-all-dropdowns {}) (set-dropdown-open ~{:id id :open? (not open?)})])
false)]
(button-group {:className (if open? "open" "")}
(button {:className (cond-> "dropdown-toggle"
kind (str " btn-" (name kind))) :aria-haspopup true :aria-expanded open? :onClick open-menu}
(tr-unsafe label) " " (dom/span #js {:className "caret"}))
(dom/ul #js {:className "dropdown-menu"}
(map #(ui-dropdown-item % :onSelect onSelect :active? (cond
stateful? (= (::id %) active-item)
value (= value (::id %)))) items))))))
(let [ui-dropdown-factory (prim/factory Dropdown {:keyfn ::id})]
(defn ui-dropdown
"Render a dropdown. The props are the state props of the dropdown. The additional by-name
arguments:
onSelect - The function to call when a menu item is selected
stateful? - If set to true, the dropdown will remember the selection and show it.
kind - The kind of dropdown. See `button`."
[props & {:keys [onSelect kind value stateful?] :as attrs}]
(ui-dropdown-factory (prim/computed props attrs))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NAV (tabs/pills)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def nav-table :bootstrap.nav/by-id)
(def nav-link-table :bootstrap.navitem/by-id)
(defn nav-link
"Creates a navigation link. ID must be globally unique. The label will be run through `tr-unsafe`, so it can be
internationalized. "
[id label disabled?]
{::id id ::label label ::disbled? disabled? :type nav-link-table})
(defn nav-link-ident [id-or-props]
(if (map? id-or-props)
[(:type id-or-props) (::id id-or-props)]
[nav-link-table id-or-props]))
(defn nav-ident [id-or-props]
(if (map? id-or-props)
[nav-table (::id id-or-props)]
[nav-table id-or-props]))
(defn nav
"Creates a navigation control.
- kind - One of :tabs or :pills
- layout - One of :normal, :stacked or :justified
- active-link-id - Which of the nested links is the active one
- links - A vector of `nav-link` or `dropdown` instances."
[id kind layout active-link-id links]
{::id id ::kind kind ::layout layout ::active-link-id active-link-id ::links links})
(defui ^:once NavLink
static prim/IQuery
(query [this] [::id ::label ::disabled? :type])
static prim/Ident
(ident [this props] (nav-link-ident props))
Object
(render [this]
(let [{:keys [::id ::label ::disabled?]} (prim/props this)
{:keys [onSelect active?]} (prim/get-computed this)]
(dom/li #js {:role "presentation" :className (cond-> ""
active? (str " active")
disabled? (str " disabled"))}
(dom/a #js {:onClick #(when onSelect (onSelect id))} (tr-unsafe label))))))
(def ui-nav-link (prim/factory NavLink {:keyfn ::id}))
(defui ^:once NavItemUnion
static prim/Ident
(ident [this {:keys [::id type]}] [type id])
static prim/IQuery
(query [this] {dropdown-table (prim/get-query Dropdown) nav-link-table (prim/get-query NavLink)})
Object
(render [this]
(let [{:keys [type ::items] :as child} (prim/props this)
{:keys [onSelect active-id active?] :as computed} (prim/get-computed this)
stateful? (some #(= active-id (::id %)) items)]
(case type
:bootstrap.navitem/by-id (ui-nav-link (prim/computed child computed))
:bootstrap.dropdown/by-id (ui-dropdown child :onSelect onSelect :stateful? stateful?)
(dom/p nil "Unknown link type!")))))
(def ui-nav-item (prim/factory NavItemUnion {:keyfn ::id}))
(defn set-active-nav-link*
[state-map nav-id link-id]
(update-in state-map (nav-ident nav-id) assoc ::active-link-id link-id))
(m/defmutation set-active-nav-link
"Mutation: Set the active navigation link"
[{:keys [id target]}]
(action [{:keys [state]}]
(swap! state set-active-nav-link* id target)))
(defui ^:once Nav
static prim/Ident
(ident [this props] (nav-ident props))
static prim/IQuery
(query [this] [::id ::kind ::layout ::active-link-id {::links (prim/get-query NavItemUnion)}])
Object
(render [this]
(let [{:keys [::id ::kind ::layout ::active-link-id ::links]} (prim/props this)
{:keys [onSelect]} (prim/get-computed this)
onSelect (fn [nav-id] (when onSelect (onSelect nav-id))
(prim/transact! this `[(set-active-nav-link ~{:id id :target nav-id})]))]
(dom/ul #js {:className (str "nav nav-" (name kind) (case layout :justified " nav-justified" :stacked " nav-stacked" ""))}
(map #(ui-nav-item (prim/computed % {:onSelect onSelect :active-id active-link-id :active? (= (::id %) active-link-id)})) links)))))
(let [nav-factory (prim/factory Nav {:keyfn ::id})]
(defn ui-nav
"Render a nav, which should have state declared with `nav`.
props - a cljs map of the data props
onSelect - an optional named parameter to supply a function that is called when navigation is done.
"
[props & {:keys [onSelect]}]
(nav-factory (prim/computed props {:onSelect onSelect}))))
(defn label
"Wraps children in an (inline) bootstrap label.
props are standard DOM props, with support for the additional:
kind - One of :primary, :success, :warning, :info, :danger. Defaults to :default."
[{:keys [kind] :as props :or {kind :default}} & children]
(let [classes (str "label label-" (name kind) " " (get props :className ""))
attrs (-> (dissoc props :kind)
(assoc :className classes))]
(apply dom/span (clj->js attrs) children)))
(defn badge
"Wraps children in an (inline) bootstrap badge.
props are standard DOM props."
[props & children]
(let [classes (str "badge " (get props :className ""))
attrs (assoc props :className classes)]
(apply dom/span (clj->js attrs) children)))
(defn jumbotron
"Wraps children in a jumbotron"
[props & children]
(div-with-class "jumbotron" props children))
(defn alert
"Renders an alert.
Props can contain normal DOM props, and additionally:
kind - The kind of alert: :info, :success, :warning, or :danger. Defaults to `:danger`.
onClose - What to do when the close button is pressed. If nil, close will not be rendered."
[{:keys [kind onClose] :as props} & children]
(let [classes (str (:className props) " alert alert-dismissable alert-" (if kind (name kind) "danger"))
attrs (-> props
(dissoc :kind :onClose)
(assoc :role "alert" :className classes)
clj->js)]
(apply dom/div attrs (if onClose
(close-button {:onClick onClose})
"") children)))
(defn caption
"Renders content that has padding and a lightened color for the font."
[props & children]
(div-with-class "caption" props children))
(defn thumbnail
"Renders a box around content. Typically used to double-box and image or generate Pinterest-style blocks."
[props & children]
(div-with-class "thumbnail" props children))
(defn progress-bar
"Render's a progress bar from an input of the current progress (a number from 0 to 100).
:current - The current value of progress (0 to 100)
:animated? - Should the bar have a striped animation?
:kind - One of :success, :warning, :danger, or :info
Any classname or other properties included will be placed on the top-level div of the progress bar.
"
[{:keys [current kind animated?] :or {kind :info} :as props}]
(let [attrs (dissoc props :current :kind :animated?)]
(div-with-class "progress" attrs
[(dom/div #js {:className (str "progress-bar progress-bar-" (name kind)
(when animated? " progress-bar-striped active")) :role "progressbar" :aria-valuenow current
:aria-valuemin 0 :aria-valuemax 100 :style #js {:width (str current "%")}})])))
(defn panel
"Render a panel. Use `panel-heading`, `panel-title`, `panel-body`, and `panel-footer` for elements of the panel.
:kind is one of :primary, :success, :info, :warning, or :danger"
[{:keys [kind] :or {kind :default} :as props} & children]
(div-with-class (str "panel panel-" (name kind)) props children))
(defn panel-group
"A wrapper for panels that visually groups them together."
[props & children]
(div-with-class "panel-group" props children))
(defn panel-heading
"Render a heading area in a panel. Must be first. Optional."
[props & children]
(div-with-class "panel-heading" props children))
(defn panel-title
"Render a title in a panel. Must be in a `panel-heading`."
[props & children]
(div-with-class "panel-title" props children))
(defn panel-body
"Render children in the body of a panel. Not needed for tables or list groups. Should come after (optional) panel-heading."
[props & children]
(div-with-class "panel-body" props children))
(defn panel-footer
"Render children in a footer of a panel."
[props & children]
(div-with-class "panel-footer" props children))
(defn well
"Inset content.
size - Optional to increase or decrease size. Can be :sm or :lg"
[{:keys [size] :as props} & children]
(div-with-class (str "well " (when size (str "well-" (name size)))) (dissoc props :size) children))
(defn get-abs-position
"Get a map (with the keys :left and :top) that has the absolute position of the given DOM element."
[ele]
#?(:clj {}
:cljs (let [doc (.-ownerDocument ele)
win (or (.-defaultView doc) js/window)
box (.getBoundingClientRect ele)]
{:width (.-width box)
:height (.-height box)
:left (+ (.-left box) (.-scrollX win))
:top (+ (.-top box) (.-scrollY win))})))
; we're using owner document to make sure this works in iframes, where js/document would be wrong
(defui RenderInBody
Object
(renderLayer [this]
#?(:cljs (let [child (first (prim/children this))
popup (.-popup this)]
(.render js/ReactDOM child popup))))
(componentDidMount [this]
#?(:cljs (let [doc (some-> (.-doc-element this) .-ownerDocument)
popup (when doc (.createElement doc "div"))]
(set! (.-popup this) popup)
(when doc (.appendChild (.-body doc) popup))
(.renderLayer this))))
(componentDidUpdate [this np ns] (.renderLayer this))
(shouldComponentUpdate [this np ns] true)
(componentWillUnmount [this]
#?(:cljs (let [doc (some-> (.-doc-element this) .-ownerDocument)
popup (.-popup this)]
(.unmountComponentAtNode js/ReactDOM (.-popup this))
(when doc
(.removeChild (.-body doc) (.-popup this))))))
(render [this] (dom/div #js {:key "<KEY>" :ref (fn [r] (set! (.-doc-element this) r))})))
(def ui-render-in-body (prim/factory RenderInBody {:keyfn :key}))
(defsc PopOverContent [this props] (dom-with-class dom/div "popover-content" props (prim/children this)))
(def ui-popover-content (prim/factory PopOverContent))
(defsc PopOverTitle [this props] (dom-with-class dom/h3 "popover-title" props (prim/children this)))
(def ui-popover-title (prim/factory PopOverTitle))
(defsc PopOverTarget [this props] (dom-with-class dom/span "" props (prim/children this)))
(def ui-popover-target (prim/factory PopOverTarget))
(defsc PopOver [this {:keys [active orientation] :or {orientation :top}}]
{:componentWillUpdate (fn [new-props new-state]
(let [old-props (prim/props this)
becoming-active? (and (:active new-props) (not (:active old-props)))]
(when becoming-active? (prim/update-state! this update :render-for-size inc))))}
(let [target (.-target-ref this)
popup (.-popup-ref this)
popup-box (if popup (get-abs-position popup) {})
target-box (if target (get-abs-position target) {})
deltaY (case orientation
:bottom (:height target-box)
:left (-> (:height target-box)
(- (:height popup-box))
(/ 2))
:right (-> (:height target-box)
(- (:height popup-box))
(/ 2))
(- (:height popup-box)))
deltaX (case orientation
:left (- (:width popup-box))
:right (:width target-box)
(/ (- (:width target-box) (:width popup-box)) 2))
popupTop (if active (+ (:top target-box) deltaY) -1000)
popupLeft (if active (+ (:left target-box) deltaX) -1000)
children (prim/children this)
content (util/first-node PopOverContent children)
title (util/first-node PopOverTitle children)
target (util/first-node PopOverTarget children)]
(dom/span #js {:style #js {:display "inline-block"} :ref (fn [r] (set! (.-target-ref this) r))}
(ui-render-in-body {}
(dom/div #js {:className (str "popover fade " (name orientation) (when active " in"))
:ref (fn [r] (set! (.-popup-ref this) r))
:style #js {:position "absolute"
:top (str popupTop "px")
:left (str popupLeft "px")
:display "block"}}
(dom/div #js {:className "arrow" :style #js {:left (case orientation
:left "100%"
:right "-11px"
"50%")}})
(when title) title
(when content) content))
target)))
(def ui-popover (prim/factory PopOver))
(defn modal-ident
"Get the ident for a modal with the given props or ID"
[props-or-id]
(if (map? props-or-id)
[:fulcro.ui.boostrap3.modal/by-id (:db/id props-or-id)]
[:fulcro.ui.boostrap3.modal/by-id props-or-id]))
(defn- show-modal* [modal tf]
(assoc modal :modal/visible tf))
(defn- activate-modal* [modal tf]
(assoc modal :modal/active tf))
#?(:cljs
(defmutation show-modal
"Mutation: Show a modal by ID."
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state update-in (modal-ident id) show-modal* true)
(js/setTimeout (fn [] (swap! state update-in (modal-ident id) activate-modal* true)) 10))))
#?(:cljs
(defmutation hide-modal
"mutation: Hide a modal by ID."
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state update-in (modal-ident id) activate-modal* false)
(js/setTimeout (fn [] (swap! state update-in (modal-ident id) show-modal* false)) 300))))
(defui ^:once ModalTitle
Object
(render [this]
(apply dom/div (clj->js (prim/props this)) (prim/children this))))
(def ui-modal-title (prim/factory ModalTitle {:keyfn (fn [props] "modal-title")}))
(defui ^:once ModalBody
Object
(render [this]
(div-with-class "modal-body" (prim/props this) (prim/children this))))
(def ui-modal-body (prim/factory ModalBody {:keyfn (fn [props] "modal-body")}))
(defui ^:once ModalFooter
Object
(render [this]
(div-with-class "modal-footer" (prim/props this) (prim/children this))))
(def ui-modal-footer (prim/factory ModalFooter {:keyfn (fn [props] "modal-footer")}))
(defui ^:once Modal
static prim/InitialAppState
(initial-state [c {:keys [id sz backdrop keyboard] :or {backdrop true keyboard true}}]
{:db/id id :modal/active false :modal/visible false :modal/keyboard keyboard
:modal/size sz :modal/backdrop (boolean backdrop)})
static prim/Ident
(ident [this props] (modal-ident props))
static prim/IQuery
(query [this] [:db/id :modal/active :modal/visible :modal/size :modal/backdrop :modal/keyboard])
Object
(componentDidMount [this] (.focus (.-the-dialog this)))
(componentDidUpdate [this pp _] (when (and (:modal/visible (prim/props this)) (not (:modal/visible pp))) (.focus (.-the-dialog this))))
(render [this]
(let [{:keys [db/id modal/active modal/visible modal/size modal/keyboard modal/backdrop]} (prim/props this)
{:keys [onClose]} (prim/get-computed this)
onClose (fn []
(prim/transact! this `[(hide-modal {:id ~id})])
(when onClose (onClose id)))
children (prim/children this)
label-id (str "modal-label-" id)
title (util/first-node ModalTitle children)
body (util/first-node ModalBody children)
footer (util/first-node ModalFooter children)]
(dom/div #js {:role "dialog" :aria-labelledby label-id
:ref (fn [r] (set! (.-the-dialog this) r))
:onKeyDown (fn [evt] (when (and keyboard (evt/escape-key? evt)) (onClose)))
:style #js {:display (if visible "block" "none")}
:className (str "modal fade" (when active " in")) :tabIndex "-1"}
(dom/div #js {:role "document" :className (str "modal-dialog" (when size (str " modal-" (name size))))}
(dom/div #js {:className "modal-content"}
(dom/div #js {:key "modal-header" :className "modal-header"}
(dom/button #js {:type "button" :onClick onClose :aria-label "Close" :className "close"}
(dom/span #js {:aria-hidden "true"} ent/times))
(when title
(dom/h4 #js {:key label-id :id label-id :className "modal-title"} title)))
(when body body)
(when footer footer)))
(when (and backdrop visible)
(ui-render-in-body {}
(dom/div #js {:key "backdrop" :className (str "modal-backdrop fade" (when active " in"))})))))))
(let [modal-factory (prim/factory Modal {:keyfn (fn [props] (str "modal-" (:db/id props)))})]
(defn ui-modal
"Render a modal.
Modals are stateful. You must compose in initial state and a query. Modals also have IDs.
Modal content should include a ui-modal-title, ui-modal-body, and ui-modal-footer as children. The footer usually contains
one or more buttons.
Use the `prim/get-initial-state` function to pull a valid initial state for this component. The arguments are:
`(prim/get-initial-state Modal {:id ID :sz SZ :backdrop BOOLEAN})`
where the id is required (and must be unique among modals, and `:sz` is optional and must be `:sm` or `:lg`. The
:backdrop option is boolean, and indicates you want a backdrop that blocks the UI. The `:keyboard` option
defaults to true and enables removal of the dialog with `ESC`.
When rendering the modal, it typically looks something like this:
````
(b/ui-modal modal
(b/ui-modal-title nil
(dom/b nil \"WARNING!\"))
(b/ui-modal-body nil
(dom/p #js {:className b/text-danger} \"Stuff went sideways.\"))
(b/ui-modal-footer nil
(b/button {:onClick #(prim/transact! this `[(b/hide-modal {:id :warning-modal})])} \"Bummer!\"))))))
````
NOTE: The grid (`row` and `col`) can be used within the modal body *without* a `container`.
See the developer's guide for an example in the N15-Twitter-Bootstrap-Components section.
Available mudations: `b/show-modal` and `b/hide-modal`."
[props & children]
(apply modal-factory props children)))
(defn collapse-ident [id-or-props]
(if (map? id-or-props)
[:fulcro.ui.bootstrap3.collapse/by-id (:db/id id-or-props)]
[:fulcro.ui.bootstrap3.collapse/by-id id-or-props]))
(defui Collapse
static prim/InitialAppState
(initial-state [c {:keys [id start-open]}] {:db/id id :collapse/phase :closed})
static prim/Ident
(ident [this props] (collapse-ident props))
static prim/IQuery
(query [this] [:db/id :collapse/phase])
Object
(render [this]
(let [{:keys [db/id collapse/phase]} (prim/props this)
dom-ele (.-dom-element this)
box-height (when dom-ele (.-height (.getBoundingClientRect dom-ele)))
height (when dom-ele
(case phase
:opening-no-height nil
:opening (str (.-scrollHeight dom-ele) "px")
:open nil
:closing (str box-height "px")
"0px"))
children (prim/children this)
classes (case phase
:open "collapse in"
:closed "collapse"
"collapsing")]
(apply dom/div #js {:className classes :style #js {:height height} :ref (fn [r] (set! (.-dom-element this) r))} children))))
(def ui-collapse
"Render a collapse component that can height-animate in/out children. The props should be state from the
app database initialized with `get-initial-state` of a Collapse component,
and the children should be the elements you want to show/hide. Each component should have a unique
(application-wide) ID. Use the `toggle-collapse` and `set-collapse` mutations to open/close. "
(prim/factory Collapse {:keyfn :db/id}))
(defn- is-stable?
"Returns true if the given collapse item is not transitioning"
[collapse-item]
(#{:open :closed} (:collapse/phase collapse-item)))
(defn- set-collapse*
"state is a state atom"
[state id open]
; phases [:opening-no-height :opening :open :closing :closed]
(let [cident (collapse-ident id)
item (get-in @state cident)
ppath (conj cident :collapse/phase)]
(when (is-stable? item)
(if open
(do
(swap! state assoc-in ppath :opening-no-height)
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :opening)) 16))
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :open)) 350)))
(do
(swap! state assoc-in ppath :closing)
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :close-height)) 16))
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :closed)) 350)))))))
(defmutation toggle-collapse
"mutation: Toggle a collapse"
[{:keys [id]}]
(action [{:keys [state]}]
(let [cident (collapse-ident id)
ppath (conj cident :collapse/phase)
is-open (= :open (get-in @state ppath))]
(set-collapse* state id (not is-open)))))
(defmutation set-collapse
"mutation: Set the state of a collapse."
[{:keys [id open]}]
(action [{:keys [state]}]
(set-collapse* state id open)))
(defmutation toggle-collapse-group-item
"mutation: Toggle a collapse element as if in a group.
item-id: The specific group to toggle
all-item-ids: A collection of all of the items that are to be considered part of the group. If any items are
in transition, this is a no-op."
[{:keys [item-id all-item-ids]}]
(action [{:keys [state]}]
(let [all-ids (set all-item-ids)
all-items (map #(get-in @state (collapse-ident %)) all-ids)
item-to-toggle (get-in @state (collapse-ident item-id))
closing? (= :open (:collapse/phase item-to-toggle))
stable? (every? is-stable? all-items)]
(when stable?
(if closing?
(set-collapse* state item-id false)
(let [open? (fn [item] (= :open (:collapse/phase item)))
ids-to-close (->> all-items
(filter open?)
(map :db/id))]
(doseq [id ids-to-close]
(set-collapse* state id false))
(set-collapse* state item-id true)))))))
(defn carousel-ident [props-or-id]
(if (map? props-or-id)
[:fulcro.ui.bootstrap3.carousel/by-id (:db/id props-or-id)]
[:fulcro.ui.bootstrap3.carousel/by-id props-or-id]))
(defui CarouselItem
Object
(render [this]
(let [{:keys [src alt] :as props} (prim/props this)
caption (prim/children this)]
(dom/div #js {:key (hash src)}
(dom/img #js {:src src :alt alt})
(when (seq caption)
(dom/div #js {:className "carousel-caption"}
caption))))))
(def ui-carousel-item
"Render a carousel item. Props can include src and alt for the image. If children are supplied, they will be
treated as the caption."
(prim/factory CarouselItem {:keyfn :index}))
(defmutation carousel-slide-to
"mutation: Slides a carousel from the current frame to the indicated frame. The special `frame` value of `:wrap`
can be used to slide from the current frame to the first as if wrapping in a circle."
[{:keys [id frame]}]
(action [{:keys [state]}]
(let [cident (carousel-ident id)
carousel (get-in @state cident)
{:keys [carousel/timer-id carousel/paused carousel/active-index
carousel/slide-to carousel/interval]} carousel
new-timer-id (when (not slide-to)
#?(:cljs (js/setTimeout (fn []
(swap! state update-in (carousel-ident id)
assoc
:carousel/timer-id nil
:carousel/active-index frame
:carousel/slide-to nil)) 600)))]
(when (not slide-to)
#?(:cljs (when timer-id
(js/clearTimeout timer-id)))
(swap! state assoc :carousel/slide-to frame :carousel/timer-id new-timer-id)))))
(defui Carousel
static prim/InitialAppState
(initial-state [c {:keys [id interval wrap keyboard pause-on-hover show-controls]
:or {interval 5000 wrap true keyboard true pause-on-hover true show-controls true}}]
{:db/id id
:carousel/interval interval
:carousel/active-index 0
:carousel/show-controls show-controls
:carousel/wrap wrap
:carousel/keyboard keyboard
:carousel/pause-on-hover pause-on-hover
:carousel/paused false
:carousel/timer-id nil})
static prim/Ident
(ident [this props] (carousel-ident props))
static prim/IQuery
(query [this] [:db/id :carousel/active-index :carousel/slide-to :carousel/show-controls])
Object
(render [this]
(let [items (prim/children this)
slide-count (count items)
{:keys [db/id carousel/active-index carousel/slide-to carousel/show-controls]} (prim/props this)
to (if (= :wrap slide-to) 0 slide-to)
sliding? (and slide-to (not= active-index slide-to))
prior-index (if (zero? active-index) (dec slide-count) (dec active-index))
next-index (if (= (dec slide-count) active-index) 0 (inc active-index))
goto (fn [slide] (prim/transact! this `[(carousel-slide-to {:id ~id :frame ~slide})]))
from-the-left? (or (= :wrap slide-to) (< active-index slide-to))
active-item-class (str "item active "
(when sliding? (if from-the-left? "left" "right")))
slide-to-class (str "item " (when sliding? (if from-the-left? "next left" "next right")))]
(dom/div #js {:className "carousel slide"
:onKeyDown (fn [e]
(.preventDefault e) ; TODO: not getting key evts
(.stopPropagation e)
(cond
(evt/left-arrow? e) (goto prior-index)
(evt/right-arrow? e) (goto next-index))
false)}
(dom/ol #js {:className "carousel-indicators"}
(map #(dom/li #js {:key % :className (str "" (when (= % active-index) "active"))} "") (range slide-count)))
; TODO: extra div needs unwrapped, but is already rendered
(dom/div #js {:className "carousel-inner" :role "listbox"}
(map-indexed (fn [idx i]
(dom/div #js {:className (cond
(= idx to) slide-to-class
(= idx active-index) active-item-class
:else "")} i))
items))
(when show-controls
(dom/a #js {:onClick #(goto prior-index) :className "left carousel-control" :role "button"}
(glyphicon {:aria-hidden true} :chevron-left)
(dom/span #js {:className "sr-only"} "Previous"))
(dom/a #js {:onClick #(goto next-index) :className "right carousel-control" :role "button"}
(glyphicon {:aria-hidden true} :chevron-right)
(dom/span #js {:className "sr-only"} "Next")))))))
; TODO: above is untested...might work ;)
(def ui-carousel (prim/factory Carousel {:keyfn :db/id}))
;; TODO: Carousel (stateful)
;; TODO: Scrollspy (spy-link component that triggers mutation + scrollspy component that gets updated on those mutations)
;; TODO: Affix (similar to scrollspy in terms of interactions)
;; TODO: Media Object
;; TODO: List Group with table etc integrations
| true |
(ns fulcro.ui.bootstrap3
(:require [fulcro.client.dom :as dom]
[fulcro.client.primitives :as prim :refer [defui defsc]]
[fulcro.ui.elements :as ele]
[fulcro.events :as evt]
[fulcro.ui.html-entities :as ent]
[fulcro.i18n :refer [tr tr-unsafe]]
[fulcro.client.mutations :as m :refer [defmutation]]
#?(:clj
[clojure.future :refer :all])
[clojure.string :as str]
[clojure.set :as set]
[fulcro.client :as fc]
[fulcro.logging :as log]
[fulcro.client.util :as util]))
#?(:clj (defn- clj->js [m] m))
;; Bootstrap CSS and Components for Fulcro
(defn- dom-with-class [dom-factory cls attrs children]
(let [attrs (-> attrs
#_(update :key (fnil identity "placeholder-key"))
(update :className #(str cls " " %)))]
(apply dom-factory (clj->js attrs) children)))
(defn- div-with-class [cls attrs children] (dom-with-class dom/div cls attrs children))
(defn- p-with-class [cls attrs children] (dom-with-class dom/p cls attrs children))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; BASE CSS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn container
"Top-level container for bootstrap grid content. This is a responsive fixed-width container. See also container-fluid."
[attrs & children] (div-with-class "container" attrs children))
(defn container-fluid
"Top-level container for bootstrap grid content. This is a responsive full-width container. See also container."
[attrs & children] (div-with-class "container-fluid" attrs children))
(defn row
"Generate a layout row. This is a div container for a row in a 12-wide grid responsive layout.
Rows should contain layout columns generated with the `col` function of this namespace.
The properties are normal DOM attributes as a cljs map and can include standard React DOM properties.
"
[props & children]
(div-with-class "row" props children))
(defn col
"Output a div that represents a column in the 12-column responsive grid.
Any React props are allowed. The following special one pertain to the column:
xs The width of the column on xs screens
sm The width of the column on sm screens
md The width of the column on md screens
lg The width of the column on lg screens
xs-offset The offset of the column on xs screens
sm-offset The offset of the column on sm screens
md-offset The offset of the column on md screens
lg-offset The offset of the column on lg screens
"
[{:keys [className xs sm md lg xs-offset sm-offset md-offset lg-offset] :as props} & children]
(let [classes (cond-> (:className props)
xs (str " col-xs-" xs)
sm (str " col-sm-" sm)
md (str " col-md-" md)
lg (str " col-lg-" lg)
xs-offset (str " col-xs-offset-" xs-offset)
sm-offset (str " col-sm-offset-" sm-offset)
md-offset (str " col-md-offset-" md-offset)
lg-offset (str " col-lg-offset-" lg-offset))
attrs (-> props
(dissoc :xs :sm :md :lg :xs-offset :sm-offset :md-offset :lg-offset)
(assoc :className classes)
clj->js)]
(apply dom/div attrs children)))
(defn lead
"Generates a lead paragraph with an increased font size."
[attrs & children]
(p-with-class "lead" attrs children))
(defn address
"Formats an address"
[name & {:keys [street street2 city-state phone email]}]
(let [brs (repeatedly #(dom/br nil))
children (cond-> (vec (keep identity (list street street2 city-state)))
phone (conj (dom/span nil (dom/abbr #js {:title "Phone"} "P:") phone)))]
(apply dom/address nil
(dom/strong nil name) (dom/br nil)
(vec (interleave children brs)))))
(defn quotation
"Render a block quotation with optional citation and source.
align - :right or :left (default)
credit - The name of the person.
source - The place where it was said/written, you supply the joining preposition.
children - The DOM element(s) (typicaly a p) that represent the body of the quotation
"
[{:keys [align credit source] :as attrs} & children]
(let [attrs (cond-> (dissoc attrs :align :credit :source)
(= :right align) (assoc :className (str "blockquote-reverse " (:className attrs))))
content (concat children [(dom/footer nil credit " " (dom/cite nil source))])]
(apply dom/blockquote (clj->js attrs) content)))
(defn plain-ul
"Render an unstyled unordered list"
[attrs & children]
(let [attrs (update attrs :className #(str " list-unstyled"))]
(apply dom/ul (clj->js attrs) children)))
(defn inline-ul
"Render an inline unordered list"
[attrs & children]
(let [attrs (update attrs :className #(str " list-inline"))]
(apply dom/ul (clj->js attrs) children)))
(def table-styles #{:striped :bordered :condensed :hover})
(defn table
"Renders a table. attrs can contain any normal react attributes, including :className.
Extended attributes that you can include are:
styles - A set of one or more of: #{:striped :bordered :condensed :hover}
"
[{:keys [className styles] :as attrs} & children]
(let [style-classes (str/join " " (map #(str "table-" (name %)) (set/intersection table-styles styles)))
classes (str (when className (str className " ")) "table " style-classes)
attrs (-> attrs
(dissoc :styles)
(assoc :className classes)
clj->js)]
(apply dom/table attrs children)))
(defn form-horizontal
"Set up a container for labeled inputs (which should have :split) to render the labels beside the fields."
[attrs & children]
(div-with-class "form-horizontal" attrs children))
(defn labeled-input
"An input with a label. All of the attrs apply to the input itself. You must supply a type and id for the
field to work correctly. DO NOT USE for checkbox or radio.
The additional attributes are supported:
:split - A number from 1 to 11. The number of `sm` columns to allocate to the field label. If not specified, the
label will be above the input. The parent must use the `.form-horizontal` class.
:help - A string. If supplied, displayed as the help text for the field. NOT shown if warning, error, or success are set.
:input-generator An (optional) function of `props -> input` to be called to generate the DOM input. It will receive a clj map
of properties and should return an input that has those minimum properties. It can, of course, augment those.
You should only ever supply zero or one of the following:
:warning - A boolean or string. If set as a string, that content replaces the help text.
:error - A boolean or string. If set as a string, that content replaces the help text.
:success - A boolean or string. If set as a string, that content replaces the help text.
"
[{:keys [id type className placeholder split help warning error success
input-generator] :as attrs} label]
(let [state-class (cond
error " has-error"
warning " has-warning"
success " has-success"
:else "")
form-group-classes (str "form-group" state-class)
help (first (keep identity [error warning success help]))
split-right (- 12 split)
help-id (str id "-help")
attrs (cond-> (dissoc attrs :split :help :warning :error :success :input-generator)
help (assoc :aria-describedby help-id)
:always (update :className #(str % " form-control")))]
(cond
(int? split) (dom/div #js {:className form-group-classes}
(dom/label #js {:className (str "control-label col-sm-" split) :htmlFor id} label)
(dom/div #js {:className (str "col-sm-" split-right)}
(if input-generator
(input-generator attrs)
(dom/input (clj->js attrs)))
(when help (dom/span #js {:id help-id :className "help-block"} help))))
:else (dom/div #js {:className form-group-classes}
(dom/label #js {:className "control-label" :htmlFor id} label)
(if input-generator
(input-generator attrs)
(dom/input (clj->js attrs)))
(when help (dom/span #js {:id help-id :className "help-block"} help))))))
(defn button
"Render a button with optional styling
kind - Optional. One of :primary, :success, :info, :warning, or :danger. Defaults to none (default).
size - Optional. One of :xs, :sm, or :lg. Defaults to a normal size.
as-block - Optional. Boolean. When true makes the button a block element.
"
[{:keys [kind size as-block] :as attrs} & children]
{:pre [(or (nil? kind) (contains? #{:primary :success :info :warning :danger} kind))
(or (nil? size) (contains? #{:xs :sm :lg} size))]}
(let [incoming-classes (:className attrs)
button-classes (cond-> "btn"
kind (str " btn-" (name kind))
size (str " btn-" (name size))
(not kind) (str " btn-default")
as-block (str " btn-block")
incoming-classes (str " " incoming-classes))
attrs (-> attrs
(dissoc :kind :size :as-block)
(assoc :className button-classes)
clj->js)]
(apply dom/button attrs children)))
(defn close-button [attrs]
(let [addl-classes (:className attrs)
classes (cond-> "close"
addl-classes (str " " addl-classes))
attrs (assoc attrs :type "button" :aria-label "Close" :className classes)]
(dom/button (clj->js attrs)
(dom/span #js {:aria-hidden true} "\u00D7"))))
(defn img
"Render an img tag with bootstrap classes.
is-responsive - Boolean. Marks the image so that it scales to its container.
shape - Optional. One of :rounded, :circle, or :thumbnail
All other normal react attributes (including className) are allowed."
[{:keys [is-responsive shape] :as attrs}]
{:pre [(or (nil? shape) (contains? #{:rounded :circle :thumbnail} shape))]}
(let [incoming-classes (:className attrs)
button-classes (cond-> ""
shape (str " " "img-" (name shape))
is-responsive (str " img-responsive")
incoming-classes (str " " incoming-classes))
attrs (-> attrs
(dissoc :is-responsive :shape)
(assoc :className button-classes)
clj->js)]
(dom/img attrs)))
;; raw classes (for docstrings and autocomplete
(def text-left "A CSS class for Left aligned text." "text-left")
(def text-center "A CSS class for Center aligned text." "text-center")
(def text-right "A CSS class for Right aligned text." "text-right")
(def text-justify "A CSS class for Justified text." "text-justify")
(def text-nowrap "A CSS class for No wrap text." "text-nowrap")
(def text-lowercase "A css transform that will change encosed text to lowercased text." "text-lowercase")
(def text-uppercase "A css transform that will change encosed text to uppercased text." "text-uppercase")
(def text-capitalize "A css transform that will change encosed text to capitalized text." "text-capitalize")
(def text-muted "CSS class for a muted text color" "text-muted")
(def text-primary "A CSS classname for a primary text color" "text-primary")
(def text-success "A CSS classname for a success text color" "text-success")
(def text-info "A CSS classname for a info text color" "text-info")
(def text-warning "A CSS classname for a warning text color" "text-warning")
(def text-danger "A CSS classname for a danger text color" "text-danger")
(def bg-primary "A CSS classname for a contextual primary background color" "bg-primary")
(def bg-success "A CSS classname for a contextual success background color" "bg-success")
(def bg-info "A CSS classname for a contextual info background color" "bg-info")
(def bg-warning "A CSS classname for a contextual warning background color" "bg-warning")
(def bg-danger "A CSS classname for a contextual danger background color" "bg-danger")
(def pull-left "A CSS class for forcing a float" "pull-left")
(def pull-right "A CSS class for forcing a float" "pull-right")
(def center-block "A CSS class for centering a block element" "center-block")
(def clearfix "A CSS class used on the PARENT to clear floats within that parent." "clearfix")
(def show "A CSS class for BLOCK-level elements. Element affects flow and is visible." "show")
(def hidden "A CSS class for BLOCK-level elements. Element is not in flow." "hidden")
(def invisible "A CSS class for BLOCK-level elements. Element still affects flow." "invisible")
(def visible-xs-block "A responsive CSS class to show element according to screen size" "visible-xs-block")
(def visible-xs-inline "A responsive CSS class to show element according to screen size" "visible-xs-inline")
(def visible-xs-inline-block "A responsive CSS class to show element according to screen size" "visible-xs-inline-block")
(def visible-sm-block "A responsive CSS class to show element according to screen size" "visible-sm-block")
(def visible-sm-inline "A responsive CSS class to show element according to screen size" "visible-sm-inline")
(def visible-sm-inline-block "A responsive CSS class to show element according to screen size" "visible-sm-inline-block")
(def visible-md-block "A responsive CSS class to show element according to screen size" "visible-md-block")
(def visible-md-inline "A responsive CSS class to show element according to screen size" "visible-md-inline")
(def visible-md-inline-block "A responsive CSS class to show element according to screen size" "visible-md-inline-block")
(def visible-lg-block "A responsive CSS class to show element according to screen size" "visible-lg-block")
(def visible-lg-inline "A responsive CSS class to show element according to screen size" "visible-lg-inline")
(def visible-lg-inline-block "A responsive CSS class to show element according to screen size" "visible-lg-inline-block")
(def hidden-xs "A CSS class to hide the element according to screen size" "hidden-xs")
(def hidden-sm "A CSS class to hide the element according to screen size" "hidden-sm")
(def hidden-md "A CSS class to hide the element according to screen size" "hidden-md")
(def hidden-lg "A CSS class to hide the element according to screen size" "hidden-lg")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Bootstrap Components
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def glyph-icons #{:asterisk :plus :euro :eur :minus :cloud :envelope :pencil :glass :music :search :heart
:star :star-empty :user :film :th-large :th :th-list :ok :remove :zoom-in :zoom-out :off :signal
:cog :trash :home :file :time :road :download-alt :download :upload :inbox :play-circle
:repeat :refresh :list-alt :lock :flag :headphones :volume-off :volume-down :volume-up :qrcode
:barcode :tag :tags :book :bookmark :print :camera :font :bold :italic :text-height
:text-width :align-left :align-center :align-right :align-justify :list :indent-left :indent-right
:facetime-video :picture :map-marker :adjust :tint :edit :share :check :move :step-backward
:fast-backward :backward :play :pause :stop :forward :fast-forward :step-forward :eject
:chevron-left :chevron-right :plus-sign :minus-sign :remove-sign :ok-sign :question-sign
:info-sign :screenshot :remove-circle :ok-circle :ban-circle :arrow-left :arrow-right :arrow-up
:arrow-down :share-alt :resize-full :resize-small :exclamation-sign :gift :leaf :fire :eye-open
:eye-close :warning-sign :plane :calendar :random :comment :magnet :chevron-up :chevron-down
:retweet :shopping-cart :folder-close :folder-open :resize-vertical :resize-horizontal :hdd :bullhorn :bell
:certificate :thumbs-up :thumbs-down :hand-right :hand-left :hand-up :hand-down :circle-arrow-right :circle-arrow-left
:circle-arrow-up :circle-arrow-down :globe :wrench :tasks :filter :briefcase :fullscreen :dashboard
:paperclip :heart-empty :link :phone :pushpin :usd :gbp :sort :sort-by-alphabet
:sort-by-alphabet-alt :sort-by-order :sort-by-order-alt :sort-by-attributes :sort-by-attributes-alt :unchecked
:expand :collapse-down :collapse-up :log-in :flash :log-out :new-window :record :save :open :saved :import
:export :send :floppy-disk :floppy-saved :floppy-remove :floppy-save :floppy-open :credit-card :transfer
:cutlery :header :compressed :earphone :phone-alt :tower :stats :sd-video :hd-video
:subtitles :sound-stereo :sound-dolby :sound-5-1 :sound-6-1 :sound-7-1 :copyright-mark :registration-mark :cloud-download
:cloud-upload :tree-conifer :tree-deciduous :cd :save-file :open-file :level-up :copy :paste
:alert :equalizer :king :queen :pawn :bishop :knight :baby-formula :tent
:blackboard :bed :apple :erase :hourglass :lamp :duplicate :piggy-bank :scissors
:bitcoin :btc :xbt :yen :jpy :ruble :rub :scale :ice-lolly
:ice-lolly-tasted :education :option-horizontal :option-vertical :menu-hamburger :modal-window :oil :grain :sunglasses
:text-size :text-color :text-background :object-align-top :object-align-bottom :object-align-horizontal :object-align-left
:object-align-vertical :object-align-right :triangle-right :triangle-left :triangle-bottom :triangle-top
:console :superscript :subscript :menu-left :menu-right :menu-down :menu-up})
(defn glyphicon
"Render a glyphicon in a span. Legal icon names are in b/glyph-icons.
attrs will be added to the span's attributes.
size - The size of the icon font. Defaults to 10pt.
"
[{:keys [size] :or {size "10pt"} :as attrs} icon]
{:pre [(contains? glyph-icons icon)]}
(let [attrs (-> attrs
(dissoc :size)
(assoc :aria-hidden true)
(assoc :style #js {:fontSize size})
(update :className #(str % " glyphicon glyphicon-" (name icon)))
clj->js)]
(dom/span attrs "")))
(defn button-group
"Groups nested buttons together in a horizontal row.
`size` - (optional) can be :xs, :sm, or :lg.
`kind` - (optional) can be :vertical or :justified"
[{:keys [size kind] :as attrs} & children]
(let [justified? (= kind :justified)
vertical? (= kind :vertical)
cls (cond-> "btn-group"
justified? (str " btn-group-justified")
vertical? (str "-vertical")
size (str " btn-group-" (name size)))
wrap-button (fn [ele] (if (ele/react-instance? "button" ele) (button-group {} ele) ele))
attrs (-> attrs (dissoc :size :kind) (assoc :role "group"))
children (if justified? (map #(wrap-button %) children) children)]
(div-with-class cls attrs children)))
(defn button-toolbar
"Groups button groups together as a toolbar, and a bit of space between each group"
[attrs & children]
(div-with-class "btn-toolbar" (assoc attrs :role "toolbar") children))
(defn breadcrumb-item
"Define a breadcrumb.
label - The label to show. You should internationalize this yourself.
onClick - A function. What to do when the item is clicked. Not needed for the last item."
([label] {:label label :onClick identity})
([label onClick] {:label label :onClick onClick}))
(defn breadcrumbs
"props - Properties to place on the top-level `ol`.
items - a list of breadcrumb-item"
[props & items]
(let [attrs (update props :className #(str " breadcrumb"))]
(dom/ol (clj->js attrs)
(conj
(mapv (fn [item] (dom/li #js {:key (:label item)} (dom/a #js {:onClick (:onClick item)} (:label item)))) (butlast items))
(dom/li #js {:key (:label (last items)) :className "active"} (:label (last items)))))))
(defn pagination
"Render a pagination control.
props - A map of properties.
size - One of :sm or :lg
pagination-entries - One or more `pagination-entry`"
[{:keys [size] :as props} & pagination-entries]
(let [classes (cond-> (get props :className "")
:always (str "pagination")
size (str " pagination-" (name size)))
attrs (assoc props :className classes)]
(dom/nav #js {:aria-label "Page Navigation"}
(apply dom/ul (clj->js attrs) pagination-entries))))
(defn pagination-entry
"Create an entry in a pagination control. Forward and back buttons can be rendered at either end with any label, but
the fulcro.ui.html-entities/raqao and laqao defs give a nicely sized font-based arrow."
[{:keys [label disabled active onClick] :as props}]
(let [onClick (if (and onClick (not disabled)) onClick identity)
classes (cond-> (:className props)
disabled (str " disabled")
active (str " active"))
attrs (-> props
(assoc :className classes)
(dissoc :active :label :disabled :onClick))]
(dom/li (clj->js attrs)
(if (or (= label ent/raqao) (= label ent/laqao))
(dom/a #js {:onClick onClick :aria-label (if (= ent/raqao label) "Next" "Previous")}
(dom/span #js {:aria-hidden "true"} label))
(dom/a #js {:onClick onClick}
label (when active (dom/span #js {:className "sr-only"} " (current)")))))))
(defn pager
"A light next/previous pair of controls. Use `pager-next` and `pager-previous` as the children of this."
[props & children]
(let [attrs (-> props
(update :className #(str " pager"))
clj->js)]
(dom/nav #js {:aria-label "Page Navigation"}
(apply dom/ul attrs children))))
(defn pager-next
"Render a next button in a pager"
[{:keys [onClick disabled]} & label-children]
(dom/li #js {:key "next" :className (str "next" (when disabled " disabled"))} (apply dom/a #js {:onClick (or onClick identity)} label-children)))
(defn pager-previous
"Render a previous button in a pager"
[{:keys [onClick disabled]} & label-children]
(dom/li #js {:key "prior" :className (str "previous" (when disabled " disabled"))} (apply dom/a #js {:onClick (or onClick identity)} label-children)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dropdowns
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def dropdown-table :bootstrap.dropdown/by-id)
(def dropdown-item-table :bootstrap.dropdown-item/by-id)
(defn dropdown-item
"Define the state for an item of a dropdown."
[id label] {::id id ::label label})
(defn dropdown-divider
"Creates a divider between items. Must have a unique ID"
[id] {::id id ::label ::divider})
(defn dropdown
"Creates a dropdown's state. Create items with dropdown-item or dropdown-divider."
[id label items] {::id id ::active-item nil ::label label ::items items ::open? false :type dropdown-table})
(defn dropdown-ident [id-or-props]
(if (map? id-or-props)
[(:type id-or-props) (::id id-or-props)]
[dropdown-table id-or-props]))
(defn dropdown-item-ident [id-or-props]
(if (map? id-or-props)
(dropdown-item-ident (::id id-or-props))
[dropdown-item-table id-or-props]))
(m/defmutation set-dropdown-open
"Mutation. Set the open flag to true/false to open/close the dropdown."
[{:keys [id open?]}]
(action [{:keys [state]}]
(let [kpath (conj (dropdown-ident id) ::open?)]
(swap! state assoc-in kpath open?))))
(defn set-dropdown-item-active* [state-map dropdown-id item-id]
(assoc-in state-map (conj (dropdown-ident dropdown-id) ::active-item) item-id))
(m/defmutation set-dropdown-item-active
"Mutation. Set one of the items in a dropdown to active.
id - the ID of the dropdown
item-id - the ID of the dropdown item
"
[{:keys [id item-id]}]
(action [{:keys [state]}]
(swap! state set-dropdown-item-active* id item-id)))
(defn- close-all-dropdowns-impl [dropdown-map]
(reduce (fn [m id] (assoc-in m [id ::open?] false)) dropdown-map (keys dropdown-map)))
(m/defmutation close-all-dropdowns
"Mutations: Close all dropdowns (globally)"
[ignored]
(action [{:keys [state]}]
(swap! state update dropdown-table close-all-dropdowns-impl)))
(defui ^:once DropdownItem
static prim/IQuery
(query [this] [::id ::label ::active? ::disabled? :type])
static prim/Ident
(ident [this props] (dropdown-item-ident props))
Object
(render [this]
(let [{:keys [::label ::id ::disabled?]} (prim/props this)
active? (prim/get-computed this :active?)
onSelect (or (prim/get-computed this :onSelect) identity)]
(if (= ::divider label)
(dom/li #js {:key id :role "separator" :className "divider"})
(dom/li #js {:key id :className (cond-> ""
disabled? (str " disabled")
active? (str " active"))}
(dom/a #js {:onClick (fn [evt]
(.stopPropagation evt)
(onSelect id)
false)} (tr-unsafe label)))))))
(let [ui-dropdown-item-factory (prim/factory DropdownItem {:keyfn ::id})]
(defn ui-dropdown-item
"Render a dropdown item. The props are the state props of the dropdown item. The additional by-name
arguments:
onSelect - The function to call when a menu item is selected
active? - render this item as active
"
[props & {:keys [onSelect active?]}]
(ui-dropdown-item-factory (prim/computed props {:onSelect onSelect :active? active?}))))
(defui ^:once Dropdown
static prim/IQuery
(query [this] [::id ::active-item ::label ::open? {::items (prim/get-query DropdownItem)} :type])
static prim/Ident
(ident [this props] (dropdown-ident props))
Object
(render [this]
(let [{:keys [::id ::label ::active-item ::items ::open?]} (prim/props this)
{:keys [onSelect kind stateful? value]} (prim/get-computed this)
active-item-label (->> items
(some #(and (= active-item (::id %)) %))
::label)
value-label (->> items
(some #(and (= value (::id %)) %))
::label)
label (cond
(and value value-label) value-label
(and active-item-label stateful?) active-item-label
:otherwise label)
onSelect (fn [item-id]
(prim/transact! this `[(close-all-dropdowns {}) (set-dropdown-item-active ~{:id id :item-id item-id})])
(when onSelect (onSelect item-id)))
open-menu (fn [evt]
(.stopPropagation evt)
(prim/transact! this `[(close-all-dropdowns {}) (set-dropdown-open ~{:id id :open? (not open?)})])
false)]
(button-group {:className (if open? "open" "")}
(button {:className (cond-> "dropdown-toggle"
kind (str " btn-" (name kind))) :aria-haspopup true :aria-expanded open? :onClick open-menu}
(tr-unsafe label) " " (dom/span #js {:className "caret"}))
(dom/ul #js {:className "dropdown-menu"}
(map #(ui-dropdown-item % :onSelect onSelect :active? (cond
stateful? (= (::id %) active-item)
value (= value (::id %)))) items))))))
(let [ui-dropdown-factory (prim/factory Dropdown {:keyfn ::id})]
(defn ui-dropdown
"Render a dropdown. The props are the state props of the dropdown. The additional by-name
arguments:
onSelect - The function to call when a menu item is selected
stateful? - If set to true, the dropdown will remember the selection and show it.
kind - The kind of dropdown. See `button`."
[props & {:keys [onSelect kind value stateful?] :as attrs}]
(ui-dropdown-factory (prim/computed props attrs))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; NAV (tabs/pills)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def nav-table :bootstrap.nav/by-id)
(def nav-link-table :bootstrap.navitem/by-id)
(defn nav-link
"Creates a navigation link. ID must be globally unique. The label will be run through `tr-unsafe`, so it can be
internationalized. "
[id label disabled?]
{::id id ::label label ::disbled? disabled? :type nav-link-table})
(defn nav-link-ident [id-or-props]
(if (map? id-or-props)
[(:type id-or-props) (::id id-or-props)]
[nav-link-table id-or-props]))
(defn nav-ident [id-or-props]
(if (map? id-or-props)
[nav-table (::id id-or-props)]
[nav-table id-or-props]))
(defn nav
"Creates a navigation control.
- kind - One of :tabs or :pills
- layout - One of :normal, :stacked or :justified
- active-link-id - Which of the nested links is the active one
- links - A vector of `nav-link` or `dropdown` instances."
[id kind layout active-link-id links]
{::id id ::kind kind ::layout layout ::active-link-id active-link-id ::links links})
(defui ^:once NavLink
static prim/IQuery
(query [this] [::id ::label ::disabled? :type])
static prim/Ident
(ident [this props] (nav-link-ident props))
Object
(render [this]
(let [{:keys [::id ::label ::disabled?]} (prim/props this)
{:keys [onSelect active?]} (prim/get-computed this)]
(dom/li #js {:role "presentation" :className (cond-> ""
active? (str " active")
disabled? (str " disabled"))}
(dom/a #js {:onClick #(when onSelect (onSelect id))} (tr-unsafe label))))))
(def ui-nav-link (prim/factory NavLink {:keyfn ::id}))
(defui ^:once NavItemUnion
static prim/Ident
(ident [this {:keys [::id type]}] [type id])
static prim/IQuery
(query [this] {dropdown-table (prim/get-query Dropdown) nav-link-table (prim/get-query NavLink)})
Object
(render [this]
(let [{:keys [type ::items] :as child} (prim/props this)
{:keys [onSelect active-id active?] :as computed} (prim/get-computed this)
stateful? (some #(= active-id (::id %)) items)]
(case type
:bootstrap.navitem/by-id (ui-nav-link (prim/computed child computed))
:bootstrap.dropdown/by-id (ui-dropdown child :onSelect onSelect :stateful? stateful?)
(dom/p nil "Unknown link type!")))))
(def ui-nav-item (prim/factory NavItemUnion {:keyfn ::id}))
(defn set-active-nav-link*
[state-map nav-id link-id]
(update-in state-map (nav-ident nav-id) assoc ::active-link-id link-id))
(m/defmutation set-active-nav-link
"Mutation: Set the active navigation link"
[{:keys [id target]}]
(action [{:keys [state]}]
(swap! state set-active-nav-link* id target)))
(defui ^:once Nav
static prim/Ident
(ident [this props] (nav-ident props))
static prim/IQuery
(query [this] [::id ::kind ::layout ::active-link-id {::links (prim/get-query NavItemUnion)}])
Object
(render [this]
(let [{:keys [::id ::kind ::layout ::active-link-id ::links]} (prim/props this)
{:keys [onSelect]} (prim/get-computed this)
onSelect (fn [nav-id] (when onSelect (onSelect nav-id))
(prim/transact! this `[(set-active-nav-link ~{:id id :target nav-id})]))]
(dom/ul #js {:className (str "nav nav-" (name kind) (case layout :justified " nav-justified" :stacked " nav-stacked" ""))}
(map #(ui-nav-item (prim/computed % {:onSelect onSelect :active-id active-link-id :active? (= (::id %) active-link-id)})) links)))))
(let [nav-factory (prim/factory Nav {:keyfn ::id})]
(defn ui-nav
"Render a nav, which should have state declared with `nav`.
props - a cljs map of the data props
onSelect - an optional named parameter to supply a function that is called when navigation is done.
"
[props & {:keys [onSelect]}]
(nav-factory (prim/computed props {:onSelect onSelect}))))
(defn label
"Wraps children in an (inline) bootstrap label.
props are standard DOM props, with support for the additional:
kind - One of :primary, :success, :warning, :info, :danger. Defaults to :default."
[{:keys [kind] :as props :or {kind :default}} & children]
(let [classes (str "label label-" (name kind) " " (get props :className ""))
attrs (-> (dissoc props :kind)
(assoc :className classes))]
(apply dom/span (clj->js attrs) children)))
(defn badge
"Wraps children in an (inline) bootstrap badge.
props are standard DOM props."
[props & children]
(let [classes (str "badge " (get props :className ""))
attrs (assoc props :className classes)]
(apply dom/span (clj->js attrs) children)))
(defn jumbotron
"Wraps children in a jumbotron"
[props & children]
(div-with-class "jumbotron" props children))
(defn alert
"Renders an alert.
Props can contain normal DOM props, and additionally:
kind - The kind of alert: :info, :success, :warning, or :danger. Defaults to `:danger`.
onClose - What to do when the close button is pressed. If nil, close will not be rendered."
[{:keys [kind onClose] :as props} & children]
(let [classes (str (:className props) " alert alert-dismissable alert-" (if kind (name kind) "danger"))
attrs (-> props
(dissoc :kind :onClose)
(assoc :role "alert" :className classes)
clj->js)]
(apply dom/div attrs (if onClose
(close-button {:onClick onClose})
"") children)))
(defn caption
"Renders content that has padding and a lightened color for the font."
[props & children]
(div-with-class "caption" props children))
(defn thumbnail
"Renders a box around content. Typically used to double-box and image or generate Pinterest-style blocks."
[props & children]
(div-with-class "thumbnail" props children))
(defn progress-bar
"Render's a progress bar from an input of the current progress (a number from 0 to 100).
:current - The current value of progress (0 to 100)
:animated? - Should the bar have a striped animation?
:kind - One of :success, :warning, :danger, or :info
Any classname or other properties included will be placed on the top-level div of the progress bar.
"
[{:keys [current kind animated?] :or {kind :info} :as props}]
(let [attrs (dissoc props :current :kind :animated?)]
(div-with-class "progress" attrs
[(dom/div #js {:className (str "progress-bar progress-bar-" (name kind)
(when animated? " progress-bar-striped active")) :role "progressbar" :aria-valuenow current
:aria-valuemin 0 :aria-valuemax 100 :style #js {:width (str current "%")}})])))
(defn panel
"Render a panel. Use `panel-heading`, `panel-title`, `panel-body`, and `panel-footer` for elements of the panel.
:kind is one of :primary, :success, :info, :warning, or :danger"
[{:keys [kind] :or {kind :default} :as props} & children]
(div-with-class (str "panel panel-" (name kind)) props children))
(defn panel-group
"A wrapper for panels that visually groups them together."
[props & children]
(div-with-class "panel-group" props children))
(defn panel-heading
"Render a heading area in a panel. Must be first. Optional."
[props & children]
(div-with-class "panel-heading" props children))
(defn panel-title
"Render a title in a panel. Must be in a `panel-heading`."
[props & children]
(div-with-class "panel-title" props children))
(defn panel-body
"Render children in the body of a panel. Not needed for tables or list groups. Should come after (optional) panel-heading."
[props & children]
(div-with-class "panel-body" props children))
(defn panel-footer
"Render children in a footer of a panel."
[props & children]
(div-with-class "panel-footer" props children))
(defn well
"Inset content.
size - Optional to increase or decrease size. Can be :sm or :lg"
[{:keys [size] :as props} & children]
(div-with-class (str "well " (when size (str "well-" (name size)))) (dissoc props :size) children))
(defn get-abs-position
"Get a map (with the keys :left and :top) that has the absolute position of the given DOM element."
[ele]
#?(:clj {}
:cljs (let [doc (.-ownerDocument ele)
win (or (.-defaultView doc) js/window)
box (.getBoundingClientRect ele)]
{:width (.-width box)
:height (.-height box)
:left (+ (.-left box) (.-scrollX win))
:top (+ (.-top box) (.-scrollY win))})))
; we're using owner document to make sure this works in iframes, where js/document would be wrong
(defui RenderInBody
Object
(renderLayer [this]
#?(:cljs (let [child (first (prim/children this))
popup (.-popup this)]
(.render js/ReactDOM child popup))))
(componentDidMount [this]
#?(:cljs (let [doc (some-> (.-doc-element this) .-ownerDocument)
popup (when doc (.createElement doc "div"))]
(set! (.-popup this) popup)
(when doc (.appendChild (.-body doc) popup))
(.renderLayer this))))
(componentDidUpdate [this np ns] (.renderLayer this))
(shouldComponentUpdate [this np ns] true)
(componentWillUnmount [this]
#?(:cljs (let [doc (some-> (.-doc-element this) .-ownerDocument)
popup (.-popup this)]
(.unmountComponentAtNode js/ReactDOM (.-popup this))
(when doc
(.removeChild (.-body doc) (.-popup this))))))
(render [this] (dom/div #js {:key "PI:KEY:<KEY>END_PI" :ref (fn [r] (set! (.-doc-element this) r))})))
(def ui-render-in-body (prim/factory RenderInBody {:keyfn :key}))
(defsc PopOverContent [this props] (dom-with-class dom/div "popover-content" props (prim/children this)))
(def ui-popover-content (prim/factory PopOverContent))
(defsc PopOverTitle [this props] (dom-with-class dom/h3 "popover-title" props (prim/children this)))
(def ui-popover-title (prim/factory PopOverTitle))
(defsc PopOverTarget [this props] (dom-with-class dom/span "" props (prim/children this)))
(def ui-popover-target (prim/factory PopOverTarget))
(defsc PopOver [this {:keys [active orientation] :or {orientation :top}}]
{:componentWillUpdate (fn [new-props new-state]
(let [old-props (prim/props this)
becoming-active? (and (:active new-props) (not (:active old-props)))]
(when becoming-active? (prim/update-state! this update :render-for-size inc))))}
(let [target (.-target-ref this)
popup (.-popup-ref this)
popup-box (if popup (get-abs-position popup) {})
target-box (if target (get-abs-position target) {})
deltaY (case orientation
:bottom (:height target-box)
:left (-> (:height target-box)
(- (:height popup-box))
(/ 2))
:right (-> (:height target-box)
(- (:height popup-box))
(/ 2))
(- (:height popup-box)))
deltaX (case orientation
:left (- (:width popup-box))
:right (:width target-box)
(/ (- (:width target-box) (:width popup-box)) 2))
popupTop (if active (+ (:top target-box) deltaY) -1000)
popupLeft (if active (+ (:left target-box) deltaX) -1000)
children (prim/children this)
content (util/first-node PopOverContent children)
title (util/first-node PopOverTitle children)
target (util/first-node PopOverTarget children)]
(dom/span #js {:style #js {:display "inline-block"} :ref (fn [r] (set! (.-target-ref this) r))}
(ui-render-in-body {}
(dom/div #js {:className (str "popover fade " (name orientation) (when active " in"))
:ref (fn [r] (set! (.-popup-ref this) r))
:style #js {:position "absolute"
:top (str popupTop "px")
:left (str popupLeft "px")
:display "block"}}
(dom/div #js {:className "arrow" :style #js {:left (case orientation
:left "100%"
:right "-11px"
"50%")}})
(when title) title
(when content) content))
target)))
(def ui-popover (prim/factory PopOver))
(defn modal-ident
"Get the ident for a modal with the given props or ID"
[props-or-id]
(if (map? props-or-id)
[:fulcro.ui.boostrap3.modal/by-id (:db/id props-or-id)]
[:fulcro.ui.boostrap3.modal/by-id props-or-id]))
(defn- show-modal* [modal tf]
(assoc modal :modal/visible tf))
(defn- activate-modal* [modal tf]
(assoc modal :modal/active tf))
#?(:cljs
(defmutation show-modal
"Mutation: Show a modal by ID."
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state update-in (modal-ident id) show-modal* true)
(js/setTimeout (fn [] (swap! state update-in (modal-ident id) activate-modal* true)) 10))))
#?(:cljs
(defmutation hide-modal
"mutation: Hide a modal by ID."
[{:keys [id]}]
(action [{:keys [state]}]
(swap! state update-in (modal-ident id) activate-modal* false)
(js/setTimeout (fn [] (swap! state update-in (modal-ident id) show-modal* false)) 300))))
(defui ^:once ModalTitle
Object
(render [this]
(apply dom/div (clj->js (prim/props this)) (prim/children this))))
(def ui-modal-title (prim/factory ModalTitle {:keyfn (fn [props] "modal-title")}))
(defui ^:once ModalBody
Object
(render [this]
(div-with-class "modal-body" (prim/props this) (prim/children this))))
(def ui-modal-body (prim/factory ModalBody {:keyfn (fn [props] "modal-body")}))
(defui ^:once ModalFooter
Object
(render [this]
(div-with-class "modal-footer" (prim/props this) (prim/children this))))
(def ui-modal-footer (prim/factory ModalFooter {:keyfn (fn [props] "modal-footer")}))
(defui ^:once Modal
static prim/InitialAppState
(initial-state [c {:keys [id sz backdrop keyboard] :or {backdrop true keyboard true}}]
{:db/id id :modal/active false :modal/visible false :modal/keyboard keyboard
:modal/size sz :modal/backdrop (boolean backdrop)})
static prim/Ident
(ident [this props] (modal-ident props))
static prim/IQuery
(query [this] [:db/id :modal/active :modal/visible :modal/size :modal/backdrop :modal/keyboard])
Object
(componentDidMount [this] (.focus (.-the-dialog this)))
(componentDidUpdate [this pp _] (when (and (:modal/visible (prim/props this)) (not (:modal/visible pp))) (.focus (.-the-dialog this))))
(render [this]
(let [{:keys [db/id modal/active modal/visible modal/size modal/keyboard modal/backdrop]} (prim/props this)
{:keys [onClose]} (prim/get-computed this)
onClose (fn []
(prim/transact! this `[(hide-modal {:id ~id})])
(when onClose (onClose id)))
children (prim/children this)
label-id (str "modal-label-" id)
title (util/first-node ModalTitle children)
body (util/first-node ModalBody children)
footer (util/first-node ModalFooter children)]
(dom/div #js {:role "dialog" :aria-labelledby label-id
:ref (fn [r] (set! (.-the-dialog this) r))
:onKeyDown (fn [evt] (when (and keyboard (evt/escape-key? evt)) (onClose)))
:style #js {:display (if visible "block" "none")}
:className (str "modal fade" (when active " in")) :tabIndex "-1"}
(dom/div #js {:role "document" :className (str "modal-dialog" (when size (str " modal-" (name size))))}
(dom/div #js {:className "modal-content"}
(dom/div #js {:key "modal-header" :className "modal-header"}
(dom/button #js {:type "button" :onClick onClose :aria-label "Close" :className "close"}
(dom/span #js {:aria-hidden "true"} ent/times))
(when title
(dom/h4 #js {:key label-id :id label-id :className "modal-title"} title)))
(when body body)
(when footer footer)))
(when (and backdrop visible)
(ui-render-in-body {}
(dom/div #js {:key "backdrop" :className (str "modal-backdrop fade" (when active " in"))})))))))
(let [modal-factory (prim/factory Modal {:keyfn (fn [props] (str "modal-" (:db/id props)))})]
(defn ui-modal
"Render a modal.
Modals are stateful. You must compose in initial state and a query. Modals also have IDs.
Modal content should include a ui-modal-title, ui-modal-body, and ui-modal-footer as children. The footer usually contains
one or more buttons.
Use the `prim/get-initial-state` function to pull a valid initial state for this component. The arguments are:
`(prim/get-initial-state Modal {:id ID :sz SZ :backdrop BOOLEAN})`
where the id is required (and must be unique among modals, and `:sz` is optional and must be `:sm` or `:lg`. The
:backdrop option is boolean, and indicates you want a backdrop that blocks the UI. The `:keyboard` option
defaults to true and enables removal of the dialog with `ESC`.
When rendering the modal, it typically looks something like this:
````
(b/ui-modal modal
(b/ui-modal-title nil
(dom/b nil \"WARNING!\"))
(b/ui-modal-body nil
(dom/p #js {:className b/text-danger} \"Stuff went sideways.\"))
(b/ui-modal-footer nil
(b/button {:onClick #(prim/transact! this `[(b/hide-modal {:id :warning-modal})])} \"Bummer!\"))))))
````
NOTE: The grid (`row` and `col`) can be used within the modal body *without* a `container`.
See the developer's guide for an example in the N15-Twitter-Bootstrap-Components section.
Available mudations: `b/show-modal` and `b/hide-modal`."
[props & children]
(apply modal-factory props children)))
(defn collapse-ident [id-or-props]
(if (map? id-or-props)
[:fulcro.ui.bootstrap3.collapse/by-id (:db/id id-or-props)]
[:fulcro.ui.bootstrap3.collapse/by-id id-or-props]))
(defui Collapse
static prim/InitialAppState
(initial-state [c {:keys [id start-open]}] {:db/id id :collapse/phase :closed})
static prim/Ident
(ident [this props] (collapse-ident props))
static prim/IQuery
(query [this] [:db/id :collapse/phase])
Object
(render [this]
(let [{:keys [db/id collapse/phase]} (prim/props this)
dom-ele (.-dom-element this)
box-height (when dom-ele (.-height (.getBoundingClientRect dom-ele)))
height (when dom-ele
(case phase
:opening-no-height nil
:opening (str (.-scrollHeight dom-ele) "px")
:open nil
:closing (str box-height "px")
"0px"))
children (prim/children this)
classes (case phase
:open "collapse in"
:closed "collapse"
"collapsing")]
(apply dom/div #js {:className classes :style #js {:height height} :ref (fn [r] (set! (.-dom-element this) r))} children))))
(def ui-collapse
"Render a collapse component that can height-animate in/out children. The props should be state from the
app database initialized with `get-initial-state` of a Collapse component,
and the children should be the elements you want to show/hide. Each component should have a unique
(application-wide) ID. Use the `toggle-collapse` and `set-collapse` mutations to open/close. "
(prim/factory Collapse {:keyfn :db/id}))
(defn- is-stable?
"Returns true if the given collapse item is not transitioning"
[collapse-item]
(#{:open :closed} (:collapse/phase collapse-item)))
(defn- set-collapse*
"state is a state atom"
[state id open]
; phases [:opening-no-height :opening :open :closing :closed]
(let [cident (collapse-ident id)
item (get-in @state cident)
ppath (conj cident :collapse/phase)]
(when (is-stable? item)
(if open
(do
(swap! state assoc-in ppath :opening-no-height)
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :opening)) 16))
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :open)) 350)))
(do
(swap! state assoc-in ppath :closing)
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :close-height)) 16))
#?(:cljs (js/setTimeout (fn [] (swap! state assoc-in ppath :closed)) 350)))))))
(defmutation toggle-collapse
"mutation: Toggle a collapse"
[{:keys [id]}]
(action [{:keys [state]}]
(let [cident (collapse-ident id)
ppath (conj cident :collapse/phase)
is-open (= :open (get-in @state ppath))]
(set-collapse* state id (not is-open)))))
(defmutation set-collapse
"mutation: Set the state of a collapse."
[{:keys [id open]}]
(action [{:keys [state]}]
(set-collapse* state id open)))
(defmutation toggle-collapse-group-item
"mutation: Toggle a collapse element as if in a group.
item-id: The specific group to toggle
all-item-ids: A collection of all of the items that are to be considered part of the group. If any items are
in transition, this is a no-op."
[{:keys [item-id all-item-ids]}]
(action [{:keys [state]}]
(let [all-ids (set all-item-ids)
all-items (map #(get-in @state (collapse-ident %)) all-ids)
item-to-toggle (get-in @state (collapse-ident item-id))
closing? (= :open (:collapse/phase item-to-toggle))
stable? (every? is-stable? all-items)]
(when stable?
(if closing?
(set-collapse* state item-id false)
(let [open? (fn [item] (= :open (:collapse/phase item)))
ids-to-close (->> all-items
(filter open?)
(map :db/id))]
(doseq [id ids-to-close]
(set-collapse* state id false))
(set-collapse* state item-id true)))))))
(defn carousel-ident [props-or-id]
(if (map? props-or-id)
[:fulcro.ui.bootstrap3.carousel/by-id (:db/id props-or-id)]
[:fulcro.ui.bootstrap3.carousel/by-id props-or-id]))
(defui CarouselItem
Object
(render [this]
(let [{:keys [src alt] :as props} (prim/props this)
caption (prim/children this)]
(dom/div #js {:key (hash src)}
(dom/img #js {:src src :alt alt})
(when (seq caption)
(dom/div #js {:className "carousel-caption"}
caption))))))
(def ui-carousel-item
"Render a carousel item. Props can include src and alt for the image. If children are supplied, they will be
treated as the caption."
(prim/factory CarouselItem {:keyfn :index}))
(defmutation carousel-slide-to
"mutation: Slides a carousel from the current frame to the indicated frame. The special `frame` value of `:wrap`
can be used to slide from the current frame to the first as if wrapping in a circle."
[{:keys [id frame]}]
(action [{:keys [state]}]
(let [cident (carousel-ident id)
carousel (get-in @state cident)
{:keys [carousel/timer-id carousel/paused carousel/active-index
carousel/slide-to carousel/interval]} carousel
new-timer-id (when (not slide-to)
#?(:cljs (js/setTimeout (fn []
(swap! state update-in (carousel-ident id)
assoc
:carousel/timer-id nil
:carousel/active-index frame
:carousel/slide-to nil)) 600)))]
(when (not slide-to)
#?(:cljs (when timer-id
(js/clearTimeout timer-id)))
(swap! state assoc :carousel/slide-to frame :carousel/timer-id new-timer-id)))))
(defui Carousel
static prim/InitialAppState
(initial-state [c {:keys [id interval wrap keyboard pause-on-hover show-controls]
:or {interval 5000 wrap true keyboard true pause-on-hover true show-controls true}}]
{:db/id id
:carousel/interval interval
:carousel/active-index 0
:carousel/show-controls show-controls
:carousel/wrap wrap
:carousel/keyboard keyboard
:carousel/pause-on-hover pause-on-hover
:carousel/paused false
:carousel/timer-id nil})
static prim/Ident
(ident [this props] (carousel-ident props))
static prim/IQuery
(query [this] [:db/id :carousel/active-index :carousel/slide-to :carousel/show-controls])
Object
(render [this]
(let [items (prim/children this)
slide-count (count items)
{:keys [db/id carousel/active-index carousel/slide-to carousel/show-controls]} (prim/props this)
to (if (= :wrap slide-to) 0 slide-to)
sliding? (and slide-to (not= active-index slide-to))
prior-index (if (zero? active-index) (dec slide-count) (dec active-index))
next-index (if (= (dec slide-count) active-index) 0 (inc active-index))
goto (fn [slide] (prim/transact! this `[(carousel-slide-to {:id ~id :frame ~slide})]))
from-the-left? (or (= :wrap slide-to) (< active-index slide-to))
active-item-class (str "item active "
(when sliding? (if from-the-left? "left" "right")))
slide-to-class (str "item " (when sliding? (if from-the-left? "next left" "next right")))]
(dom/div #js {:className "carousel slide"
:onKeyDown (fn [e]
(.preventDefault e) ; TODO: not getting key evts
(.stopPropagation e)
(cond
(evt/left-arrow? e) (goto prior-index)
(evt/right-arrow? e) (goto next-index))
false)}
(dom/ol #js {:className "carousel-indicators"}
(map #(dom/li #js {:key % :className (str "" (when (= % active-index) "active"))} "") (range slide-count)))
; TODO: extra div needs unwrapped, but is already rendered
(dom/div #js {:className "carousel-inner" :role "listbox"}
(map-indexed (fn [idx i]
(dom/div #js {:className (cond
(= idx to) slide-to-class
(= idx active-index) active-item-class
:else "")} i))
items))
(when show-controls
(dom/a #js {:onClick #(goto prior-index) :className "left carousel-control" :role "button"}
(glyphicon {:aria-hidden true} :chevron-left)
(dom/span #js {:className "sr-only"} "Previous"))
(dom/a #js {:onClick #(goto next-index) :className "right carousel-control" :role "button"}
(glyphicon {:aria-hidden true} :chevron-right)
(dom/span #js {:className "sr-only"} "Next")))))))
; TODO: above is untested...might work ;)
(def ui-carousel (prim/factory Carousel {:keyfn :db/id}))
;; TODO: Carousel (stateful)
;; TODO: Scrollspy (spy-link component that triggers mutation + scrollspy component that gets updated on those mutations)
;; TODO: Affix (similar to scrollspy in terms of interactions)
;; TODO: Media Object
;; TODO: List Group with table etc integrations
|
[
{
"context": "ith-temp* [Pulse [{pulse-id :id} {:name \"Lodi Dodi\" :creator_id (mt/user->id :crowberto)}]\n ",
"end": 59464,
"score": 0.999411940574646,
"start": 59455,
"tag": "NAME",
"value": "Lodi Dodi"
},
{
"context": " :emails [\"[email protected]\"]}}]]\n (testing \"Should be able to delete yo",
"end": 59904,
"score": 0.9997021555900574,
"start": 59893,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
c#-metabase/test/metabase/api/pulse_test.clj
|
hanakhry/Crime_Admin
| 0 |
(ns metabase.api.pulse-test
"Tests for /api/pulse endpoints."
(:require [clojure.test :refer :all]
[metabase.api.card-test :as card-api-test]
[metabase.api.pulse :as pulse-api]
[metabase.http-client :as http]
[metabase.integrations.slack :as slack]
[metabase.models :refer [Card Collection Dashboard Pulse PulseCard PulseChannel PulseChannelRecipient]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as perms-group]
[metabase.models.pulse :as pulse]
[metabase.models.pulse-test :as pulse-test]
[metabase.pulse.render.png :as png]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.mock.util :refer [pulse-channel-defaults]]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Helper Fns & Macros |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- user-details [user]
(select-keys
user
[:email :first_name :last_login :is_qbnewb :is_superuser :id :last_name :date_joined :common_name :locale]))
(defn- pulse-card-details [card]
(-> (select-keys card [:id :collection_id :name :description :display])
(update :display name)
(update :collection_id boolean)
;; why? these fields in this last assoc are from the PulseCard model and this function takes the Card model
;; because PulseCard is somewhat hidden behind the scenes
(assoc :include_csv false, :include_xls false, :dashboard_card_id nil, :dashboard_id nil,
:parameter_mappings nil)))
(defn- pulse-channel-details [channel]
(select-keys channel [:schedule_type :schedule_details :channel_type :updated_at :details :pulse_id :id :enabled
:created_at]))
(defn- pulse-details [pulse]
(merge
(select-keys
pulse
[:id :name :created_at :updated_at :creator_id :collection_id :collection_position :archived :skip_if_empty :dashboard_id :parameters])
{:creator (user-details (db/select-one 'User :id (:creator_id pulse)))
:cards (map pulse-card-details (:cards pulse))
:channels (map pulse-channel-details (:channels pulse))}))
(defn- pulse-response [{:keys [created_at updated_at], :as pulse}]
(-> pulse
(dissoc :id)
(assoc :created_at (some? created_at)
:updated_at (some? updated_at))
(update :collection_id boolean)
(update :cards #(for [card %]
(update card :collection_id boolean)))))
(defn- do-with-pulses-in-a-collection [grant-collection-perms-fn! pulses-or-ids f]
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp Collection [collection]
(grant-collection-perms-fn! (perms-group/all-users) collection)
;; use db/execute! instead of db/update! so the updated_at field doesn't get automatically updated!
(when (seq pulses-or-ids)
(db/execute! {:update Pulse
:set [[:collection_id (u/the-id collection)]]
:where [:in :id (set (map u/the-id pulses-or-ids))]}))
(f))))
(defmacro ^:private with-pulses-in-readable-collection [pulses-or-ids & body]
`(do-with-pulses-in-a-collection perms/grant-collection-read-permissions! ~pulses-or-ids (fn [] ~@body)))
(defmacro ^:private with-pulses-in-writeable-collection [pulses-or-ids & body]
`(do-with-pulses-in-a-collection perms/grant-collection-readwrite-permissions! ~pulses-or-ids (fn [] ~@body)))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | /api/pulse/* AUTHENTICATION Tests |
;;; +----------------------------------------------------------------------------------------------------------------+
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(deftest authentication-test
(is (= (:body middleware.u/response-unauthentic) (http/client :get 401 "pulse")))
(is (= (:body middleware.u/response-unauthentic) (http/client :put 401 "pulse/13"))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/pulse |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^:private default-post-card-ref-validation-error
{:errors
{:cards (str "value must be an array. Each value must satisfy one of the following requirements: "
"1) value must be a map with the following keys "
"`(collection_id, description, display, id, include_csv, include_xls, name, dashboard_id, parameter_mappings)` "
"2) value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`. The array cannot be empty.")}})
(deftest create-pulse-validation-test
(doseq [[input expected-error]
{{}
{:errors {:name "value must be a non-blank string."}}
{:name "abc"}
default-post-card-ref-validation-error
{:name "abc"
:cards "foobar"}
default-post-card-ref-validation-error
{:name "abc"
:cards ["abc"]}
default-post-card-ref-validation-error
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]
:channels "foobar"}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]
:channels ["abc"]}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}}]
(testing (pr-str input)
(is (= expected-error
(mt/user-http-request :rasta :post 400 "pulse" input))))))
(defn- remove-extra-channels-fields [channels]
(for [channel channels]
(dissoc channel :id :pulse_id :created_at :updated_at)))
(def ^:private pulse-defaults
{:collection_id nil
:collection_position nil
:created_at true
:skip_if_empty false
:updated_at true
:archived false
:dashboard_id nil
:parameters []})
(def ^:private daily-email-channel
{:enabled true
:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:schedule_day nil
:recipients []})
(deftest create-test
(testing "POST /api/pulse"
(testing "legacy pulse"
(mt/with-temp* [Card [card-1]
Card [card-2]
Dashboard [{dashboard-id :id} {:name "Birdcage KPIs"}]
Collection [collection]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-model-cleanup [Pulse]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields))))))))
(testing "dashboard subscriptions"
(mt/with-temp* [Collection [collection]
Card [card-1]
Card [card-2]
Dashboard [{permitted-dashboard-id :id} {:name "Birdcage KPIs" :collection_id (u/the-id collection)}]
Dashboard [{blocked-dashboard-id :id} {:name "[redacted]"}]]
(let [filter-params [{:id "abc123", :name "test", :type "date"}]
payload {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:dashboard_id permitted-dashboard-id
:skip_if_empty false
:parameters filter-params}]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-model-cleanup [Pulse]
(testing "successful creation"
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true
:dashboard_id permitted-dashboard-id
:parameters filter-params})
(-> (mt/user-http-request :rasta :post 200 "pulse" payload)
pulse-response
(update :channels remove-extra-channels-fields)))))
(testing "authorization"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 "pulse" (assoc payload :dashboard_id blocked-dashboard-id))))))))))))
(deftest create-with-hybrid-pulse-card-test
(testing "POST /api/pulse"
(testing "Create a pulse with a HybridPulseCard and a CardRef, PUT accepts this format, we should make sure POST does as well"
(mt/with-temp* [Card [card-1]
Card [card-2 {:name "The card"
:description "Info"
:display :table}]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/with-model-cleanup [Pulse]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
(-> card-2
(select-keys [:id :name :description :display :collection_id])
(assoc :include_csv false, :include_xls false, :dashboard_id nil,
:dashboard_card_id nil, :parameter_mappings nil))]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields)))))))))))
(deftest create-csv-xls-test
(testing "POST /api/pulse"
(testing "Create a pulse with a csv and xls"
(mt/with-temp* [Card [card-1]
Card [card-2]]
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/with-model-cleanup [Pulse]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards [(assoc (pulse-card-details card-1) :include_csv true, :include_xls true, :collection_id true, :dashboard_card_id nil)
(assoc (pulse-card-details card-2) :collection_id true)]
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv true
:include_xls true
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields))))))))))))
(deftest create-with-collection-position-test
(testing "POST /api/pulse"
(testing "Make sure we can create a Pulse with a Collection position"
(mt/with-model-cleanup [Pulse]
(letfn [(create-pulse! [expected-status-code pulse-name card collection]
(let [response (mt/user-http-request :rasta :post expected-status-code "pulse"
{:name pulse-name
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false
:collection_id (u/the-id collection)
:collection_position 1})]
(testing "response"
(is (= nil
(:errors response))))))]
(let [pulse-name (mt/random-name)]
(mt/with-temp* [Card [card]
Collection [collection]]
(card-api-test/with-cards-in-readable-collection [card]
(create-pulse! 200 pulse-name card collection)
(is (= {:collection_id (u/the-id collection), :collection_position 1}
(mt/derecordize (db/select-one [Pulse :collection_id :collection_position] :name pulse-name)))))))
(testing "...but not if we don't have permissions for the Collection"
(mt/with-non-admin-groups-no-root-collection-perms
(let [pulse-name (mt/random-name)]
(mt/with-temp* [Card [card]
Collection [collection]]
(create-pulse! 403 pulse-name card collection)
(is (= nil
(db/select-one [Pulse :collection_id :collection_position] :name pulse-name))))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PUT /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^:private default-put-card-ref-validation-error
{:errors
{:cards (str "value may be nil, or if non-nil, value must be an array. "
"Each value must satisfy one of the following requirements: "
"1) value must be a map with the following keys "
"`(collection_id, description, display, id, include_csv, include_xls, name, dashboard_id, parameter_mappings)` "
"2) value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`. The array cannot be empty.")}})
(deftest update-pulse-validation-test
(testing "PUT /api/pulse/:id"
(doseq [[input expected-error]
{{:name 123}
{:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}}
{:cards 123}
default-put-card-ref-validation-error
{:cards "foobar"}
default-put-card-ref-validation-error
{:cards ["abc"]}
default-put-card-ref-validation-error
{:channels 123}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}
{:channels "foobar"}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}
{:channels ["abc"]}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}}]
(testing (pr-str input)
(is (= expected-error
(mt/user-http-request :rasta :put 400 "pulse/1" input)))))))
(deftest update-test
(testing "PUT /api/pulse/:id"
(mt/with-temp* [Pulse [pulse]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]
Card [card]]
(let [filter-params [{:id "123abc", :name "species", :type "string"}]]
(with-pulses-in-writeable-collection [pulse]
(card-api-test/with-cards-in-readable-collection [card]
(is (= (merge
pulse-defaults
{:name "Updated Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards [(assoc (pulse-card-details card)
:collection_id true)]
:channels [(merge pulse-channel-defaults
{:channel_type "slack"
:schedule_type "hourly"
:details {:channels "#general"}
:recipients []})]
:collection_id true
:parameters filter-params})
(-> (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
{:name "Updated Pulse"
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [{:enabled true
:channel_type "slack"
:schedule_type "hourly"
:schedule_hour 12
:schedule_day "mon"
:recipients []
:details {:channels "#general"}}]
:skip_if_empty false
:parameters filter-params})
pulse-response
(update :channels remove-extra-channels-fields))))))))))
(deftest add-card-to-existing-test
(testing "PUT /api/pulse/:id"
(testing "Can we add a card to an existing pulse that has a card?"
;; Specifically this will include a HybridPulseCard (the original card associated with the pulse) and a CardRef
;; (the new card)
(mt/with-temp* [Pulse [pulse {:name "Original Pulse Name"}]
Card [card-1 {:name "Test"
:description "Just Testing"}]
PulseCard [_ {:card_id (u/the-id card-1)
:pulse_id (u/the-id pulse)}]
Card [card-2 {:name "Test2"
:description "Just Testing2"}]]
(with-pulses-in-writeable-collection [pulse]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
;; The FE will include the original HybridPulseCard, similar to how the API returns the card via GET
(let [pulse-cards (:cards (mt/user-http-request :rasta :get 200 (format "pulse/%d" (u/the-id pulse))))]
(is (= (merge
pulse-defaults
{:name "Original Pulse Name"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (mapv (comp #(assoc % :collection_id true) pulse-card-details) [card-1 card-2])
:channels []
:collection_id true})
(-> (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
{:cards (concat pulse-cards
[{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}])})
pulse-response
(update :channels remove-extra-channels-fields)))))))))))
(deftest update-collection-id-test
(testing "Can we update *just* the Collection ID of a Pulse?"
(mt/with-temp* [Pulse [pulse]
Collection [collection]]
(mt/user-http-request :crowberto :put 200 (str "pulse/" (u/the-id pulse))
{:collection_id (u/the-id collection)})
(is (= (db/select-one-field :collection_id Pulse :id (u/the-id pulse))
(u/the-id collection))))))
(deftest change-collection-test
(testing "Can we change the Collection a Pulse is in (assuming we have the permissions to do so)?"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for both new and old collections
(doseq [coll [collection new-collection]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll))
;; now make an API call to move collections
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)})
;; Check to make sure the ID has changed in the DB
(is (= (db/select-one-field :collection_id Pulse :id (u/the-id pulse))
(u/the-id new-collection)))))
(testing "...but if we don't have the Permissions for the old collection, we should get an Exception"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for only the *new* collection
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) new-collection)
;; now make an API call to move collections. Should fail
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)}))))))
(testing "...and if we don't have the Permissions for the new collection, we should get an Exception"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for only the *old* collection
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
;; now make an API call to move collections. Should fail
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)}))))))))
(deftest update-collection-position-test
(testing "Can we change the Collection position of a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:collection_position 1})
(is (= 1
(db/select-one-field :collection_position Pulse :id (u/the-id pulse)))))
(testing "...and unset (unpin) it as well?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(db/update! Pulse (u/the-id pulse) :collection_position 1)
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:collection_position nil})
(is (= nil
(db/select-one-field :collection_position Pulse :id (u/the-id pulse))))))
(testing "...we shouldn't be able to if we don't have permissions for the Collection"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse))
{:collection_position 1})
(is (= nil
(db/select-one-field :collection_position Pulse :id (u/the-id pulse))))
(testing "shouldn't be able to unset (unpin) a Pulse"
(db/update! Pulse (u/the-id pulse) :collection_position 1)
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse))
{:collection_position nil})
(is (= 1
(db/select-one-field :collection_position Pulse :id (u/the-id pulse)))))))))
(deftest archive-test
(testing "Can we archive a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived true})
(is (= true
(db/select-one-field :archived Pulse :id (u/the-id pulse)))))))
(deftest unarchive-test
(testing "Can we unarchive a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(db/update! Pulse (u/the-id pulse) :archived true)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived false})
(is (= false
(db/select-one-field :archived Pulse :id (u/the-id pulse))))))
(testing "Does unarchiving a Pulse affect its Cards & Recipients? It shouldn't. This should behave as a PATCH-style endpoint!"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp* [Collection [collection]
Pulse [pulse {:collection_id (u/the-id collection)}]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [pcr {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]
Card [card]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived true})
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived false})
(is (db/exists? PulseChannel :id (u/the-id pc)))
(is (db/exists? PulseChannelRecipient :id (u/the-id pcr)))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | UPDATING PULSE COLLECTION POSITIONS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defmulti ^:private move-pulse-test-action
{:arglists '([action context & args])}
(fn [action & _]
action))
(defmethod move-pulse-test-action :move
[_ context pulse & {:keys [collection position]}]
(let [pulse (get-in context [:pulse pulse])
response (mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
(merge
(when collection
{:collection_id (u/the-id (get-in context [:collection collection]))})
(when position
{:collection_position position})))]
(is (= nil
(:errors response)))))
(defmethod move-pulse-test-action :insert-pulse
[_ context collection & {:keys [position]}]
(let [collection (get-in context [:collection collection])
response (mt/user-http-request :rasta :post 200 "pulse"
(merge
{:name "x"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id (get-in context [:card 1]))
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false}
(when position
{:collection_position position})))]
(is (= nil
(:errors response)))))
(def ^:private move-test-definitions
[{:message "Check that we can update a Pulse's position in a Collection"
:action [:move :d :position 1]
:expected {"d" 1
"a" 2
"b" 3
"c" 4}}
{:message "Change the position of b to 4, will dec c and d"
:action [:move :b :position 4]
:expected {"a" 1
"c" 2
"d" 3
"b" 4}}
{:message "Change the position of d to 2, should inc b and c"
:action [:move :d :position 2]
:expected {"a" 1
"d" 2
"b" 3
"c" 4}}
{:message "Change the position of a to 4th, will decrement all existing items"
:action [:move :a :position 4]
:expected {"b" 1
"c" 2
"d" 3
"a" 4}}
{:message "Change the position of the d to the 1st, will increment all existing items"
:action [:move :d :position 1]
:expected {"d" 1
"a" 2
"b" 3
"c" 4}}
{:message (str "Check that no position change, but changing collections still triggers a fixup of both "
"collections Moving `c` from collection-1 to collection-2, `c` is now at position 3 in "
"collection 2")
:action [:move :c :collection 2]
:expected [{"a" 1
"b" 2
"d" 3}
{"e" 1
"f" 2
"c" 3
"g" 4
"h" 5}]}
{:message (str "Check that moving a pulse to another collection, with a changed position will fixup "
"both collections Moving `b` to collection 2, giving it a position of 1")
:action [:move :b :collection 2, :position 1]
:expected [{"a" 1
"c" 2
"d" 3}
{"b" 1
"e" 2
"f" 3
"g" 4
"h" 5}]}
{:message "Add a new pulse at position 2, causing existing pulses to be incremented"
:action [:insert-pulse 1 :position 2]
:expected {"a" 1
"x" 2
"b" 3
"c" 4
"d" 5}}
{:message "Add a new pulse without a position, should leave existing positions unchanged"
:action [:insert-pulse 1]
:expected {"x" nil
"a" 1
"b" 2
"c" 3
"d" 4}}])
(deftest move-pulse-test
(testing "PUT /api/pulse/:id"
(doseq [{:keys [message action expected]} move-test-definitions
:let [expected (if (map? expected) [expected] expected)]]
(testing (str "\n" message)
(mt/with-temp* [Collection [collection-1]
Collection [collection-2]
Card [card-1]]
(card-api-test/with-ordered-items collection-1 [Pulse a
Pulse b
Pulse c
Pulse d]
(card-api-test/with-ordered-items collection-2 [Card e
Card f
Dashboard g
Dashboard h]
(let [[action & args] action
context {:pulse {:a a, :b b, :c c, :d d, :e e, :f f, :g g, :h h}
:collection {1 collection-1, 2 collection-2}
:card {1 card-1}}]
(testing (str "\n" (pr-str (cons action args)))
(apply move-pulse-test-action action context args)))
(testing "\nPositions after actions for"
(testing "Collection 1"
(is (= (first expected)
(card-api-test/get-name->collection-position :rasta (u/the-id collection-1)))))
(when (second expected)
(testing "Collection 2"
(is (= (second expected)
(card-api-test/get-name->collection-position :rasta (u/the-id collection-2))))))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DELETE /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest delete-test
(testing "DELETE /api/pulse/:id"
(testing "check that a regular user can delete a Pulse if they have write permissions for its collection (!)"
(mt/with-temp* [Pulse [pulse]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]]
(with-pulses-in-writeable-collection [pulse]
(mt/user-http-request :rasta :delete 204 (format "pulse/%d" (u/the-id pulse)))
(is (= nil
(pulse/retrieve-pulse (u/the-id pulse)))))))
(testing "check that a rando (e.g. someone without collection write access) isn't allowed to delete a pulse"
(mt/with-temp-copy-of-db
(mt/with-temp* [Card [card {:dataset_query {:database (mt/id)
:type "query"
:query {:source-table (mt/id :venues)
:aggregation [[:count]]}}}]
Pulse [pulse {:name "Daily Sad Toucans"}]
PulseCard [_ {:pulse_id (u/the-id pulse), :card_id (u/the-id card)}]]
(with-pulses-in-readable-collection [pulse]
;; revoke permissions for default group to this database
(perms/revoke-permissions! (perms-group/all-users) (mt/id))
;; now a user without permissions to the Card in question should *not* be allowed to delete the pulse
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :delete 403 (format "pulse/%d" (u/the-id pulse)))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest list-test
(testing "GET /api/pulse"
(mt/with-temp* [Pulse [pulse-1 {:name "ABCDEF"}]
Pulse [pulse-2 {:name "GHIJKL"}]]
(testing "should come back in alphabetical order"
(with-pulses-in-readable-collection [pulse-1 pulse-2]
;; delete anything else in DB just to be sure; this step may not be necessary any more
(db/delete! Pulse :id [:not-in #{(u/the-id pulse-1)
(u/the-id pulse-2)}])
(is (= [(assoc (pulse-details pulse-1) :can_write false, :collection_id true)
(assoc (pulse-details pulse-2) :can_write false, :collection_id true)]
(for [pulse (mt/user-http-request :rasta :get 200 "pulse")]
(-> pulse
(update :collection_id boolean)))))))
(testing "`can_write` property should get updated correctly based on whether current user can write"
;; delete anything else in DB just to be sure; this step may not be necessary any more
(db/delete! Pulse :id [:not-in #{(u/the-id pulse-1)
(u/the-id pulse-2)}])
(is (= [(assoc (pulse-details pulse-1) :can_write true)
(assoc (pulse-details pulse-2) :can_write true)]
(mt/user-http-request :crowberto :get 200 "pulse")))))
(testing "should not return alerts"
(mt/with-temp* [Pulse [pulse-1 {:name "ABCDEF"}]
Pulse [pulse-2 {:name "GHIJKL"}]
Pulse [pulse-3 {:name "AAAAAA"
:alert_condition "rows"}]]
(with-pulses-in-readable-collection [pulse-1 pulse-2 pulse-3]
(is (= [(assoc (pulse-details pulse-1) :can_write false, :collection_id true)
(assoc (pulse-details pulse-2) :can_write false, :collection_id true)]
(for [pulse (mt/user-http-request :rasta :get 200 "pulse")]
(-> pulse
(update :collection_id boolean))))))))
(testing "by default, archived Pulses should be excluded"
(mt/with-temp* [Pulse [not-archived-pulse {:name "Not Archived"}]
Pulse [archived-pulse {:name "Archived", :archived true}]]
(with-pulses-in-readable-collection [not-archived-pulse archived-pulse]
(is (= #{"Not Archived"}
(set (map :name (mt/user-http-request :rasta :get 200 "pulse"))))))))
(testing "can we fetch archived Pulses?"
(mt/with-temp* [Pulse [not-archived-pulse {:name "Not Archived"}]
Pulse [archived-pulse {:name "Archived", :archived true}]]
(with-pulses-in-readable-collection [not-archived-pulse archived-pulse]
(is (= #{"Archived"}
(set (map :name (mt/user-http-request :rasta :get 200 "pulse?archived=true"))))))))
(testing "can fetch pulses by user ID -- should return pulses created by the user,
or pulses for which the user is a known recipient"
(mt/with-temp* [Pulse [creator-pulse {:name "LuckyCreator" :creator_id (mt/user->id :lucky)}]
Pulse [recipient-pulse {:name "LuckyRecipient"}]
Pulse [other-pulse {:name "Other"}]
PulseChannel [pulse-channel {:pulse_id (u/the-id recipient-pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pulse-channel),
:user_id (mt/user->id :lucky)}]]
(is (= #{"LuckyCreator" "LuckyRecipient"}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :lucky)))))))
(is (= #{"LuckyRecipient" "Other"}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :rasta)))))))
(is (= #{}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :trashbird)))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest get-pulse-test
(testing "GET /api/pulse/:id"
(mt/with-temp Pulse [pulse]
(with-pulses-in-readable-collection [pulse]
(is (= (assoc (pulse-details pulse)
:can_write false
:collection_id true)
(-> (mt/user-http-request :rasta :get 200 (str "pulse/" (u/the-id pulse)))
(update :collection_id boolean))))))
(testing "should 404 for an Alert"
(mt/with-temp Pulse [{pulse-id :id} {:alert_condition "rows"}]
(is (= "Not found."
(with-pulses-in-readable-collection [pulse-id]
(mt/user-http-request :rasta :get 404 (str "pulse/" pulse-id)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/pulse/test |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest send-test-pulse-test
(testing "POST /api/pulse/test"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-fake-inbox
(mt/dataset sad-toucan-incidents
(mt/with-temp* [Collection [collection]
Card [card {:dataset_query (mt/mbql-query incidents {:aggregation [[:count]]})}]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(card-api-test/with-cards-in-readable-collection [card]
(is (= {:ok true}
(mt/user-http-request :rasta :post 200 "pulse/test" {:name "Daily Sad Toucans"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [{:enabled true
:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:schedule_day nil
:recipients [(mt/fetch-user :rasta)]}]
:skip_if_empty false})))
(is (= (mt/email-to :rasta {:subject "Pulse: Daily Sad Toucans"
:body {"Daily Sad Toucans" true}})
(mt/regex-email-bodies #"Daily Sad Toucans"))))))))))
;; This test follows a flow that the user/UI would follow by first creating a pulse, then making a small change to
;; that pulse and testing it. The primary purpose of this test is to ensure tha the pulse/test endpoint accepts data
;; of the same format that the pulse GET returns
(deftest update-flow-test
(mt/with-temp* [Card [card-1 {:dataset_query
{:database (mt/id), :type :query, :query {:source-table (mt/id :venues)}}}]
Card [card-2 {:dataset_query
{:database (mt/id), :type :query, :query {:source-table (mt/id :venues)}}}]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-fake-inbox
(mt/with-model-cleanup [Pulse]
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
;; First create the pulse
(let [{pulse-id :id} (mt/user-http-request :rasta :post 200 "pulse"
{:name "A Pulse"
:collection_id (u/the-id collection)
:skip_if_empty false
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [(assoc daily-email-channel :recipients [(mt/fetch-user :rasta)
(mt/fetch-user :crowberto)])]})
;; Retrieve the pulse via GET
result (mt/user-http-request :rasta :get 200 (str "pulse/" pulse-id))
;; Change our fetched copy of the pulse to only have Rasta for the recipients
email-channel (assoc (-> result :channels first) :recipients [(mt/fetch-user :rasta)])]
;; Don't update the pulse, but test the pulse with the updated recipients
(is (= {:ok true}
(mt/user-http-request :rasta :post 200 "pulse/test" (assoc result :channels [email-channel]))))
(is (= (mt/email-to :rasta {:subject "Pulse: A Pulse"
:body {"A Pulse" true}})
(mt/regex-email-bodies #"A Pulse"))))))))))
(deftest dont-run-cards-async-test
(testing "A Card saved with `:async?` true should not be ran async for a Pulse"
(is (map? (#'pulse-api/pulse-card-query-results
{:id 1
:dataset_query {:database (mt/id)
:type :query
:query {:source-table (mt/id :venues)
:limit 1}
:async? true}})))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/form_input |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest form-input-test
(testing "GET /api/pulse/form_input"
(testing "Check that Slack channels come back when configured"
(mt/with-temporary-setting-values [slack-token "something"]
(with-redefs [slack/conversations-list (constantly [{:name "foo"}])
slack/users-list (constantly [{:name "bar"}])]
(is (= [{:name "channel", :type "select", :displayName "Post to", :options ["#foo" "@bar"], :required true}]
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])))))))
(testing "When slack is not configured, `form_input` returns no channels"
(mt/with-temporary-setting-values [slack-token nil]
(is (empty?
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])
(first)
(:options))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/preview_card/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest preview-pulse-test
(testing "GET /api/pulse/preview_card/:id"
(mt/with-temp* [Collection [collection]
Card [card {:dataset_query (mt/mbql-query checkins {:limit 5})}]]
(letfn [(preview [expected-status-code]
(http/client-full-response (mt/user->credentials :rasta)
:get expected-status-code (format "pulse/preview_card_png/%d" (u/the-id card))))]
(testing "Should be able to preview a Pulse"
(let [{{:strs [Content-Type]} :headers, :keys [body]} (preview 200)]
(is (= "image/png"
Content-Type))
(is (some? body))))
(testing "If rendering a Pulse fails (e.g. because font registration failed) the endpoint should return the error message"
(with-redefs [png/register-fonts-if-needed! (fn []
(throw (ex-info "Can't register fonts!"
{}
(NullPointerException.))))]
(let [{{:strs [Content-Type]} :headers, :keys [body]} (mt/suppress-output (preview 500))]
(is (= "application/json;charset=utf-8"
Content-Type))
(is (schema= {:message (s/eq "Can't register fonts!")
:trace s/Any
:via s/Any
s/Keyword s/Any}
body)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DELETE /api/pulse/:pulse-id/subscription |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest delete-subscription-test
(testing "DELETE /api/pulse/:pulse-id/subscription"
(mt/with-temp* [Pulse [{pulse-id :id} {:name "Lodi Dodi" :creator_id (mt/user->id :crowberto)}]
PulseChannel [{channel-id :id} {:pulse_id pulse-id
:channel_type "email"
:schedule_type "daily"
:details {:other "stuff"
:emails ["[email protected]"]}}]]
(testing "Should be able to delete your own subscription"
(mt/with-temp PulseChannelRecipient [pcr {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= nil
(mt/user-http-request :rasta :delete 204 (str "pulse/" pulse-id "/subscription/email"))))))
(testing "Users can't delete someone else's pulse subscription"
(mt/with-temp PulseChannelRecipient [pcr {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= "Not found."
(mt/user-http-request :lucky :delete 404 (str "pulse/" pulse-id "/subscription/email")))))))))
|
23517
|
(ns metabase.api.pulse-test
"Tests for /api/pulse endpoints."
(:require [clojure.test :refer :all]
[metabase.api.card-test :as card-api-test]
[metabase.api.pulse :as pulse-api]
[metabase.http-client :as http]
[metabase.integrations.slack :as slack]
[metabase.models :refer [Card Collection Dashboard Pulse PulseCard PulseChannel PulseChannelRecipient]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as perms-group]
[metabase.models.pulse :as pulse]
[metabase.models.pulse-test :as pulse-test]
[metabase.pulse.render.png :as png]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.mock.util :refer [pulse-channel-defaults]]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Helper Fns & Macros |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- user-details [user]
(select-keys
user
[:email :first_name :last_login :is_qbnewb :is_superuser :id :last_name :date_joined :common_name :locale]))
(defn- pulse-card-details [card]
(-> (select-keys card [:id :collection_id :name :description :display])
(update :display name)
(update :collection_id boolean)
;; why? these fields in this last assoc are from the PulseCard model and this function takes the Card model
;; because PulseCard is somewhat hidden behind the scenes
(assoc :include_csv false, :include_xls false, :dashboard_card_id nil, :dashboard_id nil,
:parameter_mappings nil)))
(defn- pulse-channel-details [channel]
(select-keys channel [:schedule_type :schedule_details :channel_type :updated_at :details :pulse_id :id :enabled
:created_at]))
(defn- pulse-details [pulse]
(merge
(select-keys
pulse
[:id :name :created_at :updated_at :creator_id :collection_id :collection_position :archived :skip_if_empty :dashboard_id :parameters])
{:creator (user-details (db/select-one 'User :id (:creator_id pulse)))
:cards (map pulse-card-details (:cards pulse))
:channels (map pulse-channel-details (:channels pulse))}))
(defn- pulse-response [{:keys [created_at updated_at], :as pulse}]
(-> pulse
(dissoc :id)
(assoc :created_at (some? created_at)
:updated_at (some? updated_at))
(update :collection_id boolean)
(update :cards #(for [card %]
(update card :collection_id boolean)))))
(defn- do-with-pulses-in-a-collection [grant-collection-perms-fn! pulses-or-ids f]
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp Collection [collection]
(grant-collection-perms-fn! (perms-group/all-users) collection)
;; use db/execute! instead of db/update! so the updated_at field doesn't get automatically updated!
(when (seq pulses-or-ids)
(db/execute! {:update Pulse
:set [[:collection_id (u/the-id collection)]]
:where [:in :id (set (map u/the-id pulses-or-ids))]}))
(f))))
(defmacro ^:private with-pulses-in-readable-collection [pulses-or-ids & body]
`(do-with-pulses-in-a-collection perms/grant-collection-read-permissions! ~pulses-or-ids (fn [] ~@body)))
(defmacro ^:private with-pulses-in-writeable-collection [pulses-or-ids & body]
`(do-with-pulses-in-a-collection perms/grant-collection-readwrite-permissions! ~pulses-or-ids (fn [] ~@body)))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | /api/pulse/* AUTHENTICATION Tests |
;;; +----------------------------------------------------------------------------------------------------------------+
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(deftest authentication-test
(is (= (:body middleware.u/response-unauthentic) (http/client :get 401 "pulse")))
(is (= (:body middleware.u/response-unauthentic) (http/client :put 401 "pulse/13"))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/pulse |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^:private default-post-card-ref-validation-error
{:errors
{:cards (str "value must be an array. Each value must satisfy one of the following requirements: "
"1) value must be a map with the following keys "
"`(collection_id, description, display, id, include_csv, include_xls, name, dashboard_id, parameter_mappings)` "
"2) value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`. The array cannot be empty.")}})
(deftest create-pulse-validation-test
(doseq [[input expected-error]
{{}
{:errors {:name "value must be a non-blank string."}}
{:name "abc"}
default-post-card-ref-validation-error
{:name "abc"
:cards "foobar"}
default-post-card-ref-validation-error
{:name "abc"
:cards ["abc"]}
default-post-card-ref-validation-error
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]
:channels "foobar"}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]
:channels ["abc"]}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}}]
(testing (pr-str input)
(is (= expected-error
(mt/user-http-request :rasta :post 400 "pulse" input))))))
(defn- remove-extra-channels-fields [channels]
(for [channel channels]
(dissoc channel :id :pulse_id :created_at :updated_at)))
(def ^:private pulse-defaults
{:collection_id nil
:collection_position nil
:created_at true
:skip_if_empty false
:updated_at true
:archived false
:dashboard_id nil
:parameters []})
(def ^:private daily-email-channel
{:enabled true
:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:schedule_day nil
:recipients []})
(deftest create-test
(testing "POST /api/pulse"
(testing "legacy pulse"
(mt/with-temp* [Card [card-1]
Card [card-2]
Dashboard [{dashboard-id :id} {:name "Birdcage KPIs"}]
Collection [collection]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-model-cleanup [Pulse]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields))))))))
(testing "dashboard subscriptions"
(mt/with-temp* [Collection [collection]
Card [card-1]
Card [card-2]
Dashboard [{permitted-dashboard-id :id} {:name "Birdcage KPIs" :collection_id (u/the-id collection)}]
Dashboard [{blocked-dashboard-id :id} {:name "[redacted]"}]]
(let [filter-params [{:id "abc123", :name "test", :type "date"}]
payload {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:dashboard_id permitted-dashboard-id
:skip_if_empty false
:parameters filter-params}]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-model-cleanup [Pulse]
(testing "successful creation"
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true
:dashboard_id permitted-dashboard-id
:parameters filter-params})
(-> (mt/user-http-request :rasta :post 200 "pulse" payload)
pulse-response
(update :channels remove-extra-channels-fields)))))
(testing "authorization"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 "pulse" (assoc payload :dashboard_id blocked-dashboard-id))))))))))))
(deftest create-with-hybrid-pulse-card-test
(testing "POST /api/pulse"
(testing "Create a pulse with a HybridPulseCard and a CardRef, PUT accepts this format, we should make sure POST does as well"
(mt/with-temp* [Card [card-1]
Card [card-2 {:name "The card"
:description "Info"
:display :table}]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/with-model-cleanup [Pulse]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
(-> card-2
(select-keys [:id :name :description :display :collection_id])
(assoc :include_csv false, :include_xls false, :dashboard_id nil,
:dashboard_card_id nil, :parameter_mappings nil))]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields)))))))))))
(deftest create-csv-xls-test
(testing "POST /api/pulse"
(testing "Create a pulse with a csv and xls"
(mt/with-temp* [Card [card-1]
Card [card-2]]
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/with-model-cleanup [Pulse]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards [(assoc (pulse-card-details card-1) :include_csv true, :include_xls true, :collection_id true, :dashboard_card_id nil)
(assoc (pulse-card-details card-2) :collection_id true)]
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv true
:include_xls true
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields))))))))))))
(deftest create-with-collection-position-test
(testing "POST /api/pulse"
(testing "Make sure we can create a Pulse with a Collection position"
(mt/with-model-cleanup [Pulse]
(letfn [(create-pulse! [expected-status-code pulse-name card collection]
(let [response (mt/user-http-request :rasta :post expected-status-code "pulse"
{:name pulse-name
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false
:collection_id (u/the-id collection)
:collection_position 1})]
(testing "response"
(is (= nil
(:errors response))))))]
(let [pulse-name (mt/random-name)]
(mt/with-temp* [Card [card]
Collection [collection]]
(card-api-test/with-cards-in-readable-collection [card]
(create-pulse! 200 pulse-name card collection)
(is (= {:collection_id (u/the-id collection), :collection_position 1}
(mt/derecordize (db/select-one [Pulse :collection_id :collection_position] :name pulse-name)))))))
(testing "...but not if we don't have permissions for the Collection"
(mt/with-non-admin-groups-no-root-collection-perms
(let [pulse-name (mt/random-name)]
(mt/with-temp* [Card [card]
Collection [collection]]
(create-pulse! 403 pulse-name card collection)
(is (= nil
(db/select-one [Pulse :collection_id :collection_position] :name pulse-name))))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PUT /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^:private default-put-card-ref-validation-error
{:errors
{:cards (str "value may be nil, or if non-nil, value must be an array. "
"Each value must satisfy one of the following requirements: "
"1) value must be a map with the following keys "
"`(collection_id, description, display, id, include_csv, include_xls, name, dashboard_id, parameter_mappings)` "
"2) value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`. The array cannot be empty.")}})
(deftest update-pulse-validation-test
(testing "PUT /api/pulse/:id"
(doseq [[input expected-error]
{{:name 123}
{:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}}
{:cards 123}
default-put-card-ref-validation-error
{:cards "foobar"}
default-put-card-ref-validation-error
{:cards ["abc"]}
default-put-card-ref-validation-error
{:channels 123}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}
{:channels "foobar"}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}
{:channels ["abc"]}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}}]
(testing (pr-str input)
(is (= expected-error
(mt/user-http-request :rasta :put 400 "pulse/1" input)))))))
(deftest update-test
(testing "PUT /api/pulse/:id"
(mt/with-temp* [Pulse [pulse]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]
Card [card]]
(let [filter-params [{:id "123abc", :name "species", :type "string"}]]
(with-pulses-in-writeable-collection [pulse]
(card-api-test/with-cards-in-readable-collection [card]
(is (= (merge
pulse-defaults
{:name "Updated Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards [(assoc (pulse-card-details card)
:collection_id true)]
:channels [(merge pulse-channel-defaults
{:channel_type "slack"
:schedule_type "hourly"
:details {:channels "#general"}
:recipients []})]
:collection_id true
:parameters filter-params})
(-> (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
{:name "Updated Pulse"
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [{:enabled true
:channel_type "slack"
:schedule_type "hourly"
:schedule_hour 12
:schedule_day "mon"
:recipients []
:details {:channels "#general"}}]
:skip_if_empty false
:parameters filter-params})
pulse-response
(update :channels remove-extra-channels-fields))))))))))
(deftest add-card-to-existing-test
(testing "PUT /api/pulse/:id"
(testing "Can we add a card to an existing pulse that has a card?"
;; Specifically this will include a HybridPulseCard (the original card associated with the pulse) and a CardRef
;; (the new card)
(mt/with-temp* [Pulse [pulse {:name "Original Pulse Name"}]
Card [card-1 {:name "Test"
:description "Just Testing"}]
PulseCard [_ {:card_id (u/the-id card-1)
:pulse_id (u/the-id pulse)}]
Card [card-2 {:name "Test2"
:description "Just Testing2"}]]
(with-pulses-in-writeable-collection [pulse]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
;; The FE will include the original HybridPulseCard, similar to how the API returns the card via GET
(let [pulse-cards (:cards (mt/user-http-request :rasta :get 200 (format "pulse/%d" (u/the-id pulse))))]
(is (= (merge
pulse-defaults
{:name "Original Pulse Name"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (mapv (comp #(assoc % :collection_id true) pulse-card-details) [card-1 card-2])
:channels []
:collection_id true})
(-> (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
{:cards (concat pulse-cards
[{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}])})
pulse-response
(update :channels remove-extra-channels-fields)))))))))))
(deftest update-collection-id-test
(testing "Can we update *just* the Collection ID of a Pulse?"
(mt/with-temp* [Pulse [pulse]
Collection [collection]]
(mt/user-http-request :crowberto :put 200 (str "pulse/" (u/the-id pulse))
{:collection_id (u/the-id collection)})
(is (= (db/select-one-field :collection_id Pulse :id (u/the-id pulse))
(u/the-id collection))))))
(deftest change-collection-test
(testing "Can we change the Collection a Pulse is in (assuming we have the permissions to do so)?"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for both new and old collections
(doseq [coll [collection new-collection]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll))
;; now make an API call to move collections
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)})
;; Check to make sure the ID has changed in the DB
(is (= (db/select-one-field :collection_id Pulse :id (u/the-id pulse))
(u/the-id new-collection)))))
(testing "...but if we don't have the Permissions for the old collection, we should get an Exception"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for only the *new* collection
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) new-collection)
;; now make an API call to move collections. Should fail
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)}))))))
(testing "...and if we don't have the Permissions for the new collection, we should get an Exception"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for only the *old* collection
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
;; now make an API call to move collections. Should fail
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)}))))))))
(deftest update-collection-position-test
(testing "Can we change the Collection position of a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:collection_position 1})
(is (= 1
(db/select-one-field :collection_position Pulse :id (u/the-id pulse)))))
(testing "...and unset (unpin) it as well?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(db/update! Pulse (u/the-id pulse) :collection_position 1)
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:collection_position nil})
(is (= nil
(db/select-one-field :collection_position Pulse :id (u/the-id pulse))))))
(testing "...we shouldn't be able to if we don't have permissions for the Collection"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse))
{:collection_position 1})
(is (= nil
(db/select-one-field :collection_position Pulse :id (u/the-id pulse))))
(testing "shouldn't be able to unset (unpin) a Pulse"
(db/update! Pulse (u/the-id pulse) :collection_position 1)
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse))
{:collection_position nil})
(is (= 1
(db/select-one-field :collection_position Pulse :id (u/the-id pulse)))))))))
(deftest archive-test
(testing "Can we archive a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived true})
(is (= true
(db/select-one-field :archived Pulse :id (u/the-id pulse)))))))
(deftest unarchive-test
(testing "Can we unarchive a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(db/update! Pulse (u/the-id pulse) :archived true)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived false})
(is (= false
(db/select-one-field :archived Pulse :id (u/the-id pulse))))))
(testing "Does unarchiving a Pulse affect its Cards & Recipients? It shouldn't. This should behave as a PATCH-style endpoint!"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp* [Collection [collection]
Pulse [pulse {:collection_id (u/the-id collection)}]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [pcr {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]
Card [card]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived true})
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived false})
(is (db/exists? PulseChannel :id (u/the-id pc)))
(is (db/exists? PulseChannelRecipient :id (u/the-id pcr)))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | UPDATING PULSE COLLECTION POSITIONS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defmulti ^:private move-pulse-test-action
{:arglists '([action context & args])}
(fn [action & _]
action))
(defmethod move-pulse-test-action :move
[_ context pulse & {:keys [collection position]}]
(let [pulse (get-in context [:pulse pulse])
response (mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
(merge
(when collection
{:collection_id (u/the-id (get-in context [:collection collection]))})
(when position
{:collection_position position})))]
(is (= nil
(:errors response)))))
(defmethod move-pulse-test-action :insert-pulse
[_ context collection & {:keys [position]}]
(let [collection (get-in context [:collection collection])
response (mt/user-http-request :rasta :post 200 "pulse"
(merge
{:name "x"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id (get-in context [:card 1]))
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false}
(when position
{:collection_position position})))]
(is (= nil
(:errors response)))))
(def ^:private move-test-definitions
[{:message "Check that we can update a Pulse's position in a Collection"
:action [:move :d :position 1]
:expected {"d" 1
"a" 2
"b" 3
"c" 4}}
{:message "Change the position of b to 4, will dec c and d"
:action [:move :b :position 4]
:expected {"a" 1
"c" 2
"d" 3
"b" 4}}
{:message "Change the position of d to 2, should inc b and c"
:action [:move :d :position 2]
:expected {"a" 1
"d" 2
"b" 3
"c" 4}}
{:message "Change the position of a to 4th, will decrement all existing items"
:action [:move :a :position 4]
:expected {"b" 1
"c" 2
"d" 3
"a" 4}}
{:message "Change the position of the d to the 1st, will increment all existing items"
:action [:move :d :position 1]
:expected {"d" 1
"a" 2
"b" 3
"c" 4}}
{:message (str "Check that no position change, but changing collections still triggers a fixup of both "
"collections Moving `c` from collection-1 to collection-2, `c` is now at position 3 in "
"collection 2")
:action [:move :c :collection 2]
:expected [{"a" 1
"b" 2
"d" 3}
{"e" 1
"f" 2
"c" 3
"g" 4
"h" 5}]}
{:message (str "Check that moving a pulse to another collection, with a changed position will fixup "
"both collections Moving `b` to collection 2, giving it a position of 1")
:action [:move :b :collection 2, :position 1]
:expected [{"a" 1
"c" 2
"d" 3}
{"b" 1
"e" 2
"f" 3
"g" 4
"h" 5}]}
{:message "Add a new pulse at position 2, causing existing pulses to be incremented"
:action [:insert-pulse 1 :position 2]
:expected {"a" 1
"x" 2
"b" 3
"c" 4
"d" 5}}
{:message "Add a new pulse without a position, should leave existing positions unchanged"
:action [:insert-pulse 1]
:expected {"x" nil
"a" 1
"b" 2
"c" 3
"d" 4}}])
(deftest move-pulse-test
(testing "PUT /api/pulse/:id"
(doseq [{:keys [message action expected]} move-test-definitions
:let [expected (if (map? expected) [expected] expected)]]
(testing (str "\n" message)
(mt/with-temp* [Collection [collection-1]
Collection [collection-2]
Card [card-1]]
(card-api-test/with-ordered-items collection-1 [Pulse a
Pulse b
Pulse c
Pulse d]
(card-api-test/with-ordered-items collection-2 [Card e
Card f
Dashboard g
Dashboard h]
(let [[action & args] action
context {:pulse {:a a, :b b, :c c, :d d, :e e, :f f, :g g, :h h}
:collection {1 collection-1, 2 collection-2}
:card {1 card-1}}]
(testing (str "\n" (pr-str (cons action args)))
(apply move-pulse-test-action action context args)))
(testing "\nPositions after actions for"
(testing "Collection 1"
(is (= (first expected)
(card-api-test/get-name->collection-position :rasta (u/the-id collection-1)))))
(when (second expected)
(testing "Collection 2"
(is (= (second expected)
(card-api-test/get-name->collection-position :rasta (u/the-id collection-2))))))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DELETE /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest delete-test
(testing "DELETE /api/pulse/:id"
(testing "check that a regular user can delete a Pulse if they have write permissions for its collection (!)"
(mt/with-temp* [Pulse [pulse]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]]
(with-pulses-in-writeable-collection [pulse]
(mt/user-http-request :rasta :delete 204 (format "pulse/%d" (u/the-id pulse)))
(is (= nil
(pulse/retrieve-pulse (u/the-id pulse)))))))
(testing "check that a rando (e.g. someone without collection write access) isn't allowed to delete a pulse"
(mt/with-temp-copy-of-db
(mt/with-temp* [Card [card {:dataset_query {:database (mt/id)
:type "query"
:query {:source-table (mt/id :venues)
:aggregation [[:count]]}}}]
Pulse [pulse {:name "Daily Sad Toucans"}]
PulseCard [_ {:pulse_id (u/the-id pulse), :card_id (u/the-id card)}]]
(with-pulses-in-readable-collection [pulse]
;; revoke permissions for default group to this database
(perms/revoke-permissions! (perms-group/all-users) (mt/id))
;; now a user without permissions to the Card in question should *not* be allowed to delete the pulse
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :delete 403 (format "pulse/%d" (u/the-id pulse)))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest list-test
(testing "GET /api/pulse"
(mt/with-temp* [Pulse [pulse-1 {:name "ABCDEF"}]
Pulse [pulse-2 {:name "GHIJKL"}]]
(testing "should come back in alphabetical order"
(with-pulses-in-readable-collection [pulse-1 pulse-2]
;; delete anything else in DB just to be sure; this step may not be necessary any more
(db/delete! Pulse :id [:not-in #{(u/the-id pulse-1)
(u/the-id pulse-2)}])
(is (= [(assoc (pulse-details pulse-1) :can_write false, :collection_id true)
(assoc (pulse-details pulse-2) :can_write false, :collection_id true)]
(for [pulse (mt/user-http-request :rasta :get 200 "pulse")]
(-> pulse
(update :collection_id boolean)))))))
(testing "`can_write` property should get updated correctly based on whether current user can write"
;; delete anything else in DB just to be sure; this step may not be necessary any more
(db/delete! Pulse :id [:not-in #{(u/the-id pulse-1)
(u/the-id pulse-2)}])
(is (= [(assoc (pulse-details pulse-1) :can_write true)
(assoc (pulse-details pulse-2) :can_write true)]
(mt/user-http-request :crowberto :get 200 "pulse")))))
(testing "should not return alerts"
(mt/with-temp* [Pulse [pulse-1 {:name "ABCDEF"}]
Pulse [pulse-2 {:name "GHIJKL"}]
Pulse [pulse-3 {:name "AAAAAA"
:alert_condition "rows"}]]
(with-pulses-in-readable-collection [pulse-1 pulse-2 pulse-3]
(is (= [(assoc (pulse-details pulse-1) :can_write false, :collection_id true)
(assoc (pulse-details pulse-2) :can_write false, :collection_id true)]
(for [pulse (mt/user-http-request :rasta :get 200 "pulse")]
(-> pulse
(update :collection_id boolean))))))))
(testing "by default, archived Pulses should be excluded"
(mt/with-temp* [Pulse [not-archived-pulse {:name "Not Archived"}]
Pulse [archived-pulse {:name "Archived", :archived true}]]
(with-pulses-in-readable-collection [not-archived-pulse archived-pulse]
(is (= #{"Not Archived"}
(set (map :name (mt/user-http-request :rasta :get 200 "pulse"))))))))
(testing "can we fetch archived Pulses?"
(mt/with-temp* [Pulse [not-archived-pulse {:name "Not Archived"}]
Pulse [archived-pulse {:name "Archived", :archived true}]]
(with-pulses-in-readable-collection [not-archived-pulse archived-pulse]
(is (= #{"Archived"}
(set (map :name (mt/user-http-request :rasta :get 200 "pulse?archived=true"))))))))
(testing "can fetch pulses by user ID -- should return pulses created by the user,
or pulses for which the user is a known recipient"
(mt/with-temp* [Pulse [creator-pulse {:name "LuckyCreator" :creator_id (mt/user->id :lucky)}]
Pulse [recipient-pulse {:name "LuckyRecipient"}]
Pulse [other-pulse {:name "Other"}]
PulseChannel [pulse-channel {:pulse_id (u/the-id recipient-pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pulse-channel),
:user_id (mt/user->id :lucky)}]]
(is (= #{"LuckyCreator" "LuckyRecipient"}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :lucky)))))))
(is (= #{"LuckyRecipient" "Other"}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :rasta)))))))
(is (= #{}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :trashbird)))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest get-pulse-test
(testing "GET /api/pulse/:id"
(mt/with-temp Pulse [pulse]
(with-pulses-in-readable-collection [pulse]
(is (= (assoc (pulse-details pulse)
:can_write false
:collection_id true)
(-> (mt/user-http-request :rasta :get 200 (str "pulse/" (u/the-id pulse)))
(update :collection_id boolean))))))
(testing "should 404 for an Alert"
(mt/with-temp Pulse [{pulse-id :id} {:alert_condition "rows"}]
(is (= "Not found."
(with-pulses-in-readable-collection [pulse-id]
(mt/user-http-request :rasta :get 404 (str "pulse/" pulse-id)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/pulse/test |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest send-test-pulse-test
(testing "POST /api/pulse/test"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-fake-inbox
(mt/dataset sad-toucan-incidents
(mt/with-temp* [Collection [collection]
Card [card {:dataset_query (mt/mbql-query incidents {:aggregation [[:count]]})}]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(card-api-test/with-cards-in-readable-collection [card]
(is (= {:ok true}
(mt/user-http-request :rasta :post 200 "pulse/test" {:name "Daily Sad Toucans"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [{:enabled true
:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:schedule_day nil
:recipients [(mt/fetch-user :rasta)]}]
:skip_if_empty false})))
(is (= (mt/email-to :rasta {:subject "Pulse: Daily Sad Toucans"
:body {"Daily Sad Toucans" true}})
(mt/regex-email-bodies #"Daily Sad Toucans"))))))))))
;; This test follows a flow that the user/UI would follow by first creating a pulse, then making a small change to
;; that pulse and testing it. The primary purpose of this test is to ensure tha the pulse/test endpoint accepts data
;; of the same format that the pulse GET returns
(deftest update-flow-test
(mt/with-temp* [Card [card-1 {:dataset_query
{:database (mt/id), :type :query, :query {:source-table (mt/id :venues)}}}]
Card [card-2 {:dataset_query
{:database (mt/id), :type :query, :query {:source-table (mt/id :venues)}}}]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-fake-inbox
(mt/with-model-cleanup [Pulse]
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
;; First create the pulse
(let [{pulse-id :id} (mt/user-http-request :rasta :post 200 "pulse"
{:name "A Pulse"
:collection_id (u/the-id collection)
:skip_if_empty false
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [(assoc daily-email-channel :recipients [(mt/fetch-user :rasta)
(mt/fetch-user :crowberto)])]})
;; Retrieve the pulse via GET
result (mt/user-http-request :rasta :get 200 (str "pulse/" pulse-id))
;; Change our fetched copy of the pulse to only have Rasta for the recipients
email-channel (assoc (-> result :channels first) :recipients [(mt/fetch-user :rasta)])]
;; Don't update the pulse, but test the pulse with the updated recipients
(is (= {:ok true}
(mt/user-http-request :rasta :post 200 "pulse/test" (assoc result :channels [email-channel]))))
(is (= (mt/email-to :rasta {:subject "Pulse: A Pulse"
:body {"A Pulse" true}})
(mt/regex-email-bodies #"A Pulse"))))))))))
(deftest dont-run-cards-async-test
(testing "A Card saved with `:async?` true should not be ran async for a Pulse"
(is (map? (#'pulse-api/pulse-card-query-results
{:id 1
:dataset_query {:database (mt/id)
:type :query
:query {:source-table (mt/id :venues)
:limit 1}
:async? true}})))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/form_input |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest form-input-test
(testing "GET /api/pulse/form_input"
(testing "Check that Slack channels come back when configured"
(mt/with-temporary-setting-values [slack-token "something"]
(with-redefs [slack/conversations-list (constantly [{:name "foo"}])
slack/users-list (constantly [{:name "bar"}])]
(is (= [{:name "channel", :type "select", :displayName "Post to", :options ["#foo" "@bar"], :required true}]
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])))))))
(testing "When slack is not configured, `form_input` returns no channels"
(mt/with-temporary-setting-values [slack-token nil]
(is (empty?
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])
(first)
(:options))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/preview_card/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest preview-pulse-test
(testing "GET /api/pulse/preview_card/:id"
(mt/with-temp* [Collection [collection]
Card [card {:dataset_query (mt/mbql-query checkins {:limit 5})}]]
(letfn [(preview [expected-status-code]
(http/client-full-response (mt/user->credentials :rasta)
:get expected-status-code (format "pulse/preview_card_png/%d" (u/the-id card))))]
(testing "Should be able to preview a Pulse"
(let [{{:strs [Content-Type]} :headers, :keys [body]} (preview 200)]
(is (= "image/png"
Content-Type))
(is (some? body))))
(testing "If rendering a Pulse fails (e.g. because font registration failed) the endpoint should return the error message"
(with-redefs [png/register-fonts-if-needed! (fn []
(throw (ex-info "Can't register fonts!"
{}
(NullPointerException.))))]
(let [{{:strs [Content-Type]} :headers, :keys [body]} (mt/suppress-output (preview 500))]
(is (= "application/json;charset=utf-8"
Content-Type))
(is (schema= {:message (s/eq "Can't register fonts!")
:trace s/Any
:via s/Any
s/Keyword s/Any}
body)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DELETE /api/pulse/:pulse-id/subscription |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest delete-subscription-test
(testing "DELETE /api/pulse/:pulse-id/subscription"
(mt/with-temp* [Pulse [{pulse-id :id} {:name "<NAME>" :creator_id (mt/user->id :crowberto)}]
PulseChannel [{channel-id :id} {:pulse_id pulse-id
:channel_type "email"
:schedule_type "daily"
:details {:other "stuff"
:emails ["<EMAIL>"]}}]]
(testing "Should be able to delete your own subscription"
(mt/with-temp PulseChannelRecipient [pcr {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= nil
(mt/user-http-request :rasta :delete 204 (str "pulse/" pulse-id "/subscription/email"))))))
(testing "Users can't delete someone else's pulse subscription"
(mt/with-temp PulseChannelRecipient [pcr {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= "Not found."
(mt/user-http-request :lucky :delete 404 (str "pulse/" pulse-id "/subscription/email")))))))))
| true |
(ns metabase.api.pulse-test
"Tests for /api/pulse endpoints."
(:require [clojure.test :refer :all]
[metabase.api.card-test :as card-api-test]
[metabase.api.pulse :as pulse-api]
[metabase.http-client :as http]
[metabase.integrations.slack :as slack]
[metabase.models :refer [Card Collection Dashboard Pulse PulseCard PulseChannel PulseChannelRecipient]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as perms-group]
[metabase.models.pulse :as pulse]
[metabase.models.pulse-test :as pulse-test]
[metabase.pulse.render.png :as png]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.mock.util :refer [pulse-channel-defaults]]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Helper Fns & Macros |
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- user-details [user]
(select-keys
user
[:email :first_name :last_login :is_qbnewb :is_superuser :id :last_name :date_joined :common_name :locale]))
(defn- pulse-card-details [card]
(-> (select-keys card [:id :collection_id :name :description :display])
(update :display name)
(update :collection_id boolean)
;; why? these fields in this last assoc are from the PulseCard model and this function takes the Card model
;; because PulseCard is somewhat hidden behind the scenes
(assoc :include_csv false, :include_xls false, :dashboard_card_id nil, :dashboard_id nil,
:parameter_mappings nil)))
(defn- pulse-channel-details [channel]
(select-keys channel [:schedule_type :schedule_details :channel_type :updated_at :details :pulse_id :id :enabled
:created_at]))
(defn- pulse-details [pulse]
(merge
(select-keys
pulse
[:id :name :created_at :updated_at :creator_id :collection_id :collection_position :archived :skip_if_empty :dashboard_id :parameters])
{:creator (user-details (db/select-one 'User :id (:creator_id pulse)))
:cards (map pulse-card-details (:cards pulse))
:channels (map pulse-channel-details (:channels pulse))}))
(defn- pulse-response [{:keys [created_at updated_at], :as pulse}]
(-> pulse
(dissoc :id)
(assoc :created_at (some? created_at)
:updated_at (some? updated_at))
(update :collection_id boolean)
(update :cards #(for [card %]
(update card :collection_id boolean)))))
(defn- do-with-pulses-in-a-collection [grant-collection-perms-fn! pulses-or-ids f]
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp Collection [collection]
(grant-collection-perms-fn! (perms-group/all-users) collection)
;; use db/execute! instead of db/update! so the updated_at field doesn't get automatically updated!
(when (seq pulses-or-ids)
(db/execute! {:update Pulse
:set [[:collection_id (u/the-id collection)]]
:where [:in :id (set (map u/the-id pulses-or-ids))]}))
(f))))
(defmacro ^:private with-pulses-in-readable-collection [pulses-or-ids & body]
`(do-with-pulses-in-a-collection perms/grant-collection-read-permissions! ~pulses-or-ids (fn [] ~@body)))
(defmacro ^:private with-pulses-in-writeable-collection [pulses-or-ids & body]
`(do-with-pulses-in-a-collection perms/grant-collection-readwrite-permissions! ~pulses-or-ids (fn [] ~@body)))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | /api/pulse/* AUTHENTICATION Tests |
;;; +----------------------------------------------------------------------------------------------------------------+
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(deftest authentication-test
(is (= (:body middleware.u/response-unauthentic) (http/client :get 401 "pulse")))
(is (= (:body middleware.u/response-unauthentic) (http/client :put 401 "pulse/13"))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/pulse |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^:private default-post-card-ref-validation-error
{:errors
{:cards (str "value must be an array. Each value must satisfy one of the following requirements: "
"1) value must be a map with the following keys "
"`(collection_id, description, display, id, include_csv, include_xls, name, dashboard_id, parameter_mappings)` "
"2) value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`. The array cannot be empty.")}})
(deftest create-pulse-validation-test
(doseq [[input expected-error]
{{}
{:errors {:name "value must be a non-blank string."}}
{:name "abc"}
default-post-card-ref-validation-error
{:name "abc"
:cards "foobar"}
default-post-card-ref-validation-error
{:name "abc"
:cards ["abc"]}
default-post-card-ref-validation-error
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]
:channels "foobar"}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}
{:name "abc"
:cards [{:id 100, :include_csv false, :include_xls false, :dashboard_card_id nil}
{:id 200, :include_csv false, :include_xls false, :dashboard_card_id nil}]
:channels ["abc"]}
{:errors {:channels "value must be an array. Each value must be a map. The array cannot be empty."}}}]
(testing (pr-str input)
(is (= expected-error
(mt/user-http-request :rasta :post 400 "pulse" input))))))
(defn- remove-extra-channels-fields [channels]
(for [channel channels]
(dissoc channel :id :pulse_id :created_at :updated_at)))
(def ^:private pulse-defaults
{:collection_id nil
:collection_position nil
:created_at true
:skip_if_empty false
:updated_at true
:archived false
:dashboard_id nil
:parameters []})
(def ^:private daily-email-channel
{:enabled true
:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:schedule_day nil
:recipients []})
(deftest create-test
(testing "POST /api/pulse"
(testing "legacy pulse"
(mt/with-temp* [Card [card-1]
Card [card-2]
Dashboard [{dashboard-id :id} {:name "Birdcage KPIs"}]
Collection [collection]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-model-cleanup [Pulse]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields))))))))
(testing "dashboard subscriptions"
(mt/with-temp* [Collection [collection]
Card [card-1]
Card [card-2]
Dashboard [{permitted-dashboard-id :id} {:name "Birdcage KPIs" :collection_id (u/the-id collection)}]
Dashboard [{blocked-dashboard-id :id} {:name "[redacted]"}]]
(let [filter-params [{:id "abc123", :name "test", :type "date"}]
payload {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:dashboard_id permitted-dashboard-id
:skip_if_empty false
:parameters filter-params}]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-model-cleanup [Pulse]
(testing "successful creation"
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true
:dashboard_id permitted-dashboard-id
:parameters filter-params})
(-> (mt/user-http-request :rasta :post 200 "pulse" payload)
pulse-response
(update :channels remove-extra-channels-fields)))))
(testing "authorization"
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :post 403 "pulse" (assoc payload :dashboard_id blocked-dashboard-id))))))))))))
(deftest create-with-hybrid-pulse-card-test
(testing "POST /api/pulse"
(testing "Create a pulse with a HybridPulseCard and a CardRef, PUT accepts this format, we should make sure POST does as well"
(mt/with-temp* [Card [card-1]
Card [card-2 {:name "The card"
:description "Info"
:display :table}]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/with-model-cleanup [Pulse]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (for [card [card-1 card-2]]
(assoc (pulse-card-details card)
:collection_id true))
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
(-> card-2
(select-keys [:id :name :description :display :collection_id])
(assoc :include_csv false, :include_xls false, :dashboard_id nil,
:dashboard_card_id nil, :parameter_mappings nil))]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields)))))))))))
(deftest create-csv-xls-test
(testing "POST /api/pulse"
(testing "Create a pulse with a csv and xls"
(mt/with-temp* [Card [card-1]
Card [card-2]]
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/with-model-cleanup [Pulse]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(is (= (merge
pulse-defaults
{:name "A Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards [(assoc (pulse-card-details card-1) :include_csv true, :include_xls true, :collection_id true, :dashboard_card_id nil)
(assoc (pulse-card-details card-2) :collection_id true)]
:channels [(merge pulse-channel-defaults
{:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:recipients []})]
:collection_id true})
(-> (mt/user-http-request :rasta :post 200 "pulse" {:name "A Pulse"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card-1)
:include_csv true
:include_xls true
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false})
pulse-response
(update :channels remove-extra-channels-fields))))))))))))
(deftest create-with-collection-position-test
(testing "POST /api/pulse"
(testing "Make sure we can create a Pulse with a Collection position"
(mt/with-model-cleanup [Pulse]
(letfn [(create-pulse! [expected-status-code pulse-name card collection]
(let [response (mt/user-http-request :rasta :post expected-status-code "pulse"
{:name pulse-name
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false
:collection_id (u/the-id collection)
:collection_position 1})]
(testing "response"
(is (= nil
(:errors response))))))]
(let [pulse-name (mt/random-name)]
(mt/with-temp* [Card [card]
Collection [collection]]
(card-api-test/with-cards-in-readable-collection [card]
(create-pulse! 200 pulse-name card collection)
(is (= {:collection_id (u/the-id collection), :collection_position 1}
(mt/derecordize (db/select-one [Pulse :collection_id :collection_position] :name pulse-name)))))))
(testing "...but not if we don't have permissions for the Collection"
(mt/with-non-admin-groups-no-root-collection-perms
(let [pulse-name (mt/random-name)]
(mt/with-temp* [Card [card]
Collection [collection]]
(create-pulse! 403 pulse-name card collection)
(is (= nil
(db/select-one [Pulse :collection_id :collection_position] :name pulse-name))))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PUT /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(def ^:private default-put-card-ref-validation-error
{:errors
{:cards (str "value may be nil, or if non-nil, value must be an array. "
"Each value must satisfy one of the following requirements: "
"1) value must be a map with the following keys "
"`(collection_id, description, display, id, include_csv, include_xls, name, dashboard_id, parameter_mappings)` "
"2) value must be a map with the keys `id`, `include_csv`, `include_xls`, and `dashboard_card_id`. The array cannot be empty.")}})
(deftest update-pulse-validation-test
(testing "PUT /api/pulse/:id"
(doseq [[input expected-error]
{{:name 123}
{:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}}
{:cards 123}
default-put-card-ref-validation-error
{:cards "foobar"}
default-put-card-ref-validation-error
{:cards ["abc"]}
default-put-card-ref-validation-error
{:channels 123}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}
{:channels "foobar"}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}
{:channels ["abc"]}
{:errors {:channels (str "value may be nil, or if non-nil, value must be an array. Each value must be a map. "
"The array cannot be empty.")}}}]
(testing (pr-str input)
(is (= expected-error
(mt/user-http-request :rasta :put 400 "pulse/1" input)))))))
(deftest update-test
(testing "PUT /api/pulse/:id"
(mt/with-temp* [Pulse [pulse]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]
Card [card]]
(let [filter-params [{:id "123abc", :name "species", :type "string"}]]
(with-pulses-in-writeable-collection [pulse]
(card-api-test/with-cards-in-readable-collection [card]
(is (= (merge
pulse-defaults
{:name "Updated Pulse"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards [(assoc (pulse-card-details card)
:collection_id true)]
:channels [(merge pulse-channel-defaults
{:channel_type "slack"
:schedule_type "hourly"
:details {:channels "#general"}
:recipients []})]
:collection_id true
:parameters filter-params})
(-> (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
{:name "Updated Pulse"
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [{:enabled true
:channel_type "slack"
:schedule_type "hourly"
:schedule_hour 12
:schedule_day "mon"
:recipients []
:details {:channels "#general"}}]
:skip_if_empty false
:parameters filter-params})
pulse-response
(update :channels remove-extra-channels-fields))))))))))
(deftest add-card-to-existing-test
(testing "PUT /api/pulse/:id"
(testing "Can we add a card to an existing pulse that has a card?"
;; Specifically this will include a HybridPulseCard (the original card associated with the pulse) and a CardRef
;; (the new card)
(mt/with-temp* [Pulse [pulse {:name "Original Pulse Name"}]
Card [card-1 {:name "Test"
:description "Just Testing"}]
PulseCard [_ {:card_id (u/the-id card-1)
:pulse_id (u/the-id pulse)}]
Card [card-2 {:name "Test2"
:description "Just Testing2"}]]
(with-pulses-in-writeable-collection [pulse]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
;; The FE will include the original HybridPulseCard, similar to how the API returns the card via GET
(let [pulse-cards (:cards (mt/user-http-request :rasta :get 200 (format "pulse/%d" (u/the-id pulse))))]
(is (= (merge
pulse-defaults
{:name "Original Pulse Name"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:cards (mapv (comp #(assoc % :collection_id true) pulse-card-details) [card-1 card-2])
:channels []
:collection_id true})
(-> (mt/user-http-request :rasta :put 200 (format "pulse/%d" (u/the-id pulse))
{:cards (concat pulse-cards
[{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}])})
pulse-response
(update :channels remove-extra-channels-fields)))))))))))
(deftest update-collection-id-test
(testing "Can we update *just* the Collection ID of a Pulse?"
(mt/with-temp* [Pulse [pulse]
Collection [collection]]
(mt/user-http-request :crowberto :put 200 (str "pulse/" (u/the-id pulse))
{:collection_id (u/the-id collection)})
(is (= (db/select-one-field :collection_id Pulse :id (u/the-id pulse))
(u/the-id collection))))))
(deftest change-collection-test
(testing "Can we change the Collection a Pulse is in (assuming we have the permissions to do so)?"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for both new and old collections
(doseq [coll [collection new-collection]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) coll))
;; now make an API call to move collections
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)})
;; Check to make sure the ID has changed in the DB
(is (= (db/select-one-field :collection_id Pulse :id (u/the-id pulse))
(u/the-id new-collection)))))
(testing "...but if we don't have the Permissions for the old collection, we should get an Exception"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for only the *new* collection
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) new-collection)
;; now make an API call to move collections. Should fail
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)}))))))
(testing "...and if we don't have the Permissions for the new collection, we should get an Exception"
(pulse-test/with-pulse-in-collection [db collection pulse]
(mt/with-temp Collection [new-collection]
;; grant Permissions for only the *old* collection
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
;; now make an API call to move collections. Should fail
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse)) {:collection_id (u/the-id new-collection)}))))))))
(deftest update-collection-position-test
(testing "Can we change the Collection position of a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:collection_position 1})
(is (= 1
(db/select-one-field :collection_position Pulse :id (u/the-id pulse)))))
(testing "...and unset (unpin) it as well?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(db/update! Pulse (u/the-id pulse) :collection_position 1)
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:collection_position nil})
(is (= nil
(db/select-one-field :collection_position Pulse :id (u/the-id pulse))))))
(testing "...we shouldn't be able to if we don't have permissions for the Collection"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse))
{:collection_position 1})
(is (= nil
(db/select-one-field :collection_position Pulse :id (u/the-id pulse))))
(testing "shouldn't be able to unset (unpin) a Pulse"
(db/update! Pulse (u/the-id pulse) :collection_position 1)
(mt/user-http-request :rasta :put 403 (str "pulse/" (u/the-id pulse))
{:collection_position nil})
(is (= 1
(db/select-one-field :collection_position Pulse :id (u/the-id pulse)))))))))
(deftest archive-test
(testing "Can we archive a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived true})
(is (= true
(db/select-one-field :archived Pulse :id (u/the-id pulse)))))))
(deftest unarchive-test
(testing "Can we unarchive a Pulse?"
(pulse-test/with-pulse-in-collection [_ collection pulse]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(db/update! Pulse (u/the-id pulse) :archived true)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived false})
(is (= false
(db/select-one-field :archived Pulse :id (u/the-id pulse))))))
(testing "Does unarchiving a Pulse affect its Cards & Recipients? It shouldn't. This should behave as a PATCH-style endpoint!"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-temp* [Collection [collection]
Pulse [pulse {:collection_id (u/the-id collection)}]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [pcr {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]
Card [card]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived true})
(mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
{:archived false})
(is (db/exists? PulseChannel :id (u/the-id pc)))
(is (db/exists? PulseChannelRecipient :id (u/the-id pcr)))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | UPDATING PULSE COLLECTION POSITIONS |
;;; +----------------------------------------------------------------------------------------------------------------+
(defmulti ^:private move-pulse-test-action
{:arglists '([action context & args])}
(fn [action & _]
action))
(defmethod move-pulse-test-action :move
[_ context pulse & {:keys [collection position]}]
(let [pulse (get-in context [:pulse pulse])
response (mt/user-http-request :rasta :put 200 (str "pulse/" (u/the-id pulse))
(merge
(when collection
{:collection_id (u/the-id (get-in context [:collection collection]))})
(when position
{:collection_position position})))]
(is (= nil
(:errors response)))))
(defmethod move-pulse-test-action :insert-pulse
[_ context collection & {:keys [position]}]
(let [collection (get-in context [:collection collection])
response (mt/user-http-request :rasta :post 200 "pulse"
(merge
{:name "x"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id (get-in context [:card 1]))
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [daily-email-channel]
:skip_if_empty false}
(when position
{:collection_position position})))]
(is (= nil
(:errors response)))))
(def ^:private move-test-definitions
[{:message "Check that we can update a Pulse's position in a Collection"
:action [:move :d :position 1]
:expected {"d" 1
"a" 2
"b" 3
"c" 4}}
{:message "Change the position of b to 4, will dec c and d"
:action [:move :b :position 4]
:expected {"a" 1
"c" 2
"d" 3
"b" 4}}
{:message "Change the position of d to 2, should inc b and c"
:action [:move :d :position 2]
:expected {"a" 1
"d" 2
"b" 3
"c" 4}}
{:message "Change the position of a to 4th, will decrement all existing items"
:action [:move :a :position 4]
:expected {"b" 1
"c" 2
"d" 3
"a" 4}}
{:message "Change the position of the d to the 1st, will increment all existing items"
:action [:move :d :position 1]
:expected {"d" 1
"a" 2
"b" 3
"c" 4}}
{:message (str "Check that no position change, but changing collections still triggers a fixup of both "
"collections Moving `c` from collection-1 to collection-2, `c` is now at position 3 in "
"collection 2")
:action [:move :c :collection 2]
:expected [{"a" 1
"b" 2
"d" 3}
{"e" 1
"f" 2
"c" 3
"g" 4
"h" 5}]}
{:message (str "Check that moving a pulse to another collection, with a changed position will fixup "
"both collections Moving `b` to collection 2, giving it a position of 1")
:action [:move :b :collection 2, :position 1]
:expected [{"a" 1
"c" 2
"d" 3}
{"b" 1
"e" 2
"f" 3
"g" 4
"h" 5}]}
{:message "Add a new pulse at position 2, causing existing pulses to be incremented"
:action [:insert-pulse 1 :position 2]
:expected {"a" 1
"x" 2
"b" 3
"c" 4
"d" 5}}
{:message "Add a new pulse without a position, should leave existing positions unchanged"
:action [:insert-pulse 1]
:expected {"x" nil
"a" 1
"b" 2
"c" 3
"d" 4}}])
(deftest move-pulse-test
(testing "PUT /api/pulse/:id"
(doseq [{:keys [message action expected]} move-test-definitions
:let [expected (if (map? expected) [expected] expected)]]
(testing (str "\n" message)
(mt/with-temp* [Collection [collection-1]
Collection [collection-2]
Card [card-1]]
(card-api-test/with-ordered-items collection-1 [Pulse a
Pulse b
Pulse c
Pulse d]
(card-api-test/with-ordered-items collection-2 [Card e
Card f
Dashboard g
Dashboard h]
(let [[action & args] action
context {:pulse {:a a, :b b, :c c, :d d, :e e, :f f, :g g, :h h}
:collection {1 collection-1, 2 collection-2}
:card {1 card-1}}]
(testing (str "\n" (pr-str (cons action args)))
(apply move-pulse-test-action action context args)))
(testing "\nPositions after actions for"
(testing "Collection 1"
(is (= (first expected)
(card-api-test/get-name->collection-position :rasta (u/the-id collection-1)))))
(when (second expected)
(testing "Collection 2"
(is (= (second expected)
(card-api-test/get-name->collection-position :rasta (u/the-id collection-2))))))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DELETE /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest delete-test
(testing "DELETE /api/pulse/:id"
(testing "check that a regular user can delete a Pulse if they have write permissions for its collection (!)"
(mt/with-temp* [Pulse [pulse]
PulseChannel [pc {:pulse_id (u/the-id pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pc), :user_id (mt/user->id :rasta)}]]
(with-pulses-in-writeable-collection [pulse]
(mt/user-http-request :rasta :delete 204 (format "pulse/%d" (u/the-id pulse)))
(is (= nil
(pulse/retrieve-pulse (u/the-id pulse)))))))
(testing "check that a rando (e.g. someone without collection write access) isn't allowed to delete a pulse"
(mt/with-temp-copy-of-db
(mt/with-temp* [Card [card {:dataset_query {:database (mt/id)
:type "query"
:query {:source-table (mt/id :venues)
:aggregation [[:count]]}}}]
Pulse [pulse {:name "Daily Sad Toucans"}]
PulseCard [_ {:pulse_id (u/the-id pulse), :card_id (u/the-id card)}]]
(with-pulses-in-readable-collection [pulse]
;; revoke permissions for default group to this database
(perms/revoke-permissions! (perms-group/all-users) (mt/id))
;; now a user without permissions to the Card in question should *not* be allowed to delete the pulse
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :delete 403 (format "pulse/%d" (u/the-id pulse)))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest list-test
(testing "GET /api/pulse"
(mt/with-temp* [Pulse [pulse-1 {:name "ABCDEF"}]
Pulse [pulse-2 {:name "GHIJKL"}]]
(testing "should come back in alphabetical order"
(with-pulses-in-readable-collection [pulse-1 pulse-2]
;; delete anything else in DB just to be sure; this step may not be necessary any more
(db/delete! Pulse :id [:not-in #{(u/the-id pulse-1)
(u/the-id pulse-2)}])
(is (= [(assoc (pulse-details pulse-1) :can_write false, :collection_id true)
(assoc (pulse-details pulse-2) :can_write false, :collection_id true)]
(for [pulse (mt/user-http-request :rasta :get 200 "pulse")]
(-> pulse
(update :collection_id boolean)))))))
(testing "`can_write` property should get updated correctly based on whether current user can write"
;; delete anything else in DB just to be sure; this step may not be necessary any more
(db/delete! Pulse :id [:not-in #{(u/the-id pulse-1)
(u/the-id pulse-2)}])
(is (= [(assoc (pulse-details pulse-1) :can_write true)
(assoc (pulse-details pulse-2) :can_write true)]
(mt/user-http-request :crowberto :get 200 "pulse")))))
(testing "should not return alerts"
(mt/with-temp* [Pulse [pulse-1 {:name "ABCDEF"}]
Pulse [pulse-2 {:name "GHIJKL"}]
Pulse [pulse-3 {:name "AAAAAA"
:alert_condition "rows"}]]
(with-pulses-in-readable-collection [pulse-1 pulse-2 pulse-3]
(is (= [(assoc (pulse-details pulse-1) :can_write false, :collection_id true)
(assoc (pulse-details pulse-2) :can_write false, :collection_id true)]
(for [pulse (mt/user-http-request :rasta :get 200 "pulse")]
(-> pulse
(update :collection_id boolean))))))))
(testing "by default, archived Pulses should be excluded"
(mt/with-temp* [Pulse [not-archived-pulse {:name "Not Archived"}]
Pulse [archived-pulse {:name "Archived", :archived true}]]
(with-pulses-in-readable-collection [not-archived-pulse archived-pulse]
(is (= #{"Not Archived"}
(set (map :name (mt/user-http-request :rasta :get 200 "pulse"))))))))
(testing "can we fetch archived Pulses?"
(mt/with-temp* [Pulse [not-archived-pulse {:name "Not Archived"}]
Pulse [archived-pulse {:name "Archived", :archived true}]]
(with-pulses-in-readable-collection [not-archived-pulse archived-pulse]
(is (= #{"Archived"}
(set (map :name (mt/user-http-request :rasta :get 200 "pulse?archived=true"))))))))
(testing "can fetch pulses by user ID -- should return pulses created by the user,
or pulses for which the user is a known recipient"
(mt/with-temp* [Pulse [creator-pulse {:name "LuckyCreator" :creator_id (mt/user->id :lucky)}]
Pulse [recipient-pulse {:name "LuckyRecipient"}]
Pulse [other-pulse {:name "Other"}]
PulseChannel [pulse-channel {:pulse_id (u/the-id recipient-pulse)}]
PulseChannelRecipient [_ {:pulse_channel_id (u/the-id pulse-channel),
:user_id (mt/user->id :lucky)}]]
(is (= #{"LuckyCreator" "LuckyRecipient"}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :lucky)))))))
(is (= #{"LuckyRecipient" "Other"}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :rasta)))))))
(is (= #{}
(set (map :name (mt/user-http-request :rasta :get 200 (str "pulse?user_id=" (mt/user->id :trashbird)))))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest get-pulse-test
(testing "GET /api/pulse/:id"
(mt/with-temp Pulse [pulse]
(with-pulses-in-readable-collection [pulse]
(is (= (assoc (pulse-details pulse)
:can_write false
:collection_id true)
(-> (mt/user-http-request :rasta :get 200 (str "pulse/" (u/the-id pulse)))
(update :collection_id boolean))))))
(testing "should 404 for an Alert"
(mt/with-temp Pulse [{pulse-id :id} {:alert_condition "rows"}]
(is (= "Not found."
(with-pulses-in-readable-collection [pulse-id]
(mt/user-http-request :rasta :get 404 (str "pulse/" pulse-id)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | POST /api/pulse/test |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest send-test-pulse-test
(testing "POST /api/pulse/test"
(mt/with-non-admin-groups-no-root-collection-perms
(mt/with-fake-inbox
(mt/dataset sad-toucan-incidents
(mt/with-temp* [Collection [collection]
Card [card {:dataset_query (mt/mbql-query incidents {:aggregation [[:count]]})}]]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
(card-api-test/with-cards-in-readable-collection [card]
(is (= {:ok true}
(mt/user-http-request :rasta :post 200 "pulse/test" {:name "Daily Sad Toucans"
:collection_id (u/the-id collection)
:cards [{:id (u/the-id card)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [{:enabled true
:channel_type "email"
:schedule_type "daily"
:schedule_hour 12
:schedule_day nil
:recipients [(mt/fetch-user :rasta)]}]
:skip_if_empty false})))
(is (= (mt/email-to :rasta {:subject "Pulse: Daily Sad Toucans"
:body {"Daily Sad Toucans" true}})
(mt/regex-email-bodies #"Daily Sad Toucans"))))))))))
;; This test follows a flow that the user/UI would follow by first creating a pulse, then making a small change to
;; that pulse and testing it. The primary purpose of this test is to ensure tha the pulse/test endpoint accepts data
;; of the same format that the pulse GET returns
(deftest update-flow-test
(mt/with-temp* [Card [card-1 {:dataset_query
{:database (mt/id), :type :query, :query {:source-table (mt/id :venues)}}}]
Card [card-2 {:dataset_query
{:database (mt/id), :type :query, :query {:source-table (mt/id :venues)}}}]]
(card-api-test/with-cards-in-readable-collection [card-1 card-2]
(mt/with-fake-inbox
(mt/with-model-cleanup [Pulse]
(mt/with-temp Collection [collection]
(perms/grant-collection-readwrite-permissions! (perms-group/all-users) collection)
;; First create the pulse
(let [{pulse-id :id} (mt/user-http-request :rasta :post 200 "pulse"
{:name "A Pulse"
:collection_id (u/the-id collection)
:skip_if_empty false
:cards [{:id (u/the-id card-1)
:include_csv false
:include_xls false
:dashboard_card_id nil}
{:id (u/the-id card-2)
:include_csv false
:include_xls false
:dashboard_card_id nil}]
:channels [(assoc daily-email-channel :recipients [(mt/fetch-user :rasta)
(mt/fetch-user :crowberto)])]})
;; Retrieve the pulse via GET
result (mt/user-http-request :rasta :get 200 (str "pulse/" pulse-id))
;; Change our fetched copy of the pulse to only have Rasta for the recipients
email-channel (assoc (-> result :channels first) :recipients [(mt/fetch-user :rasta)])]
;; Don't update the pulse, but test the pulse with the updated recipients
(is (= {:ok true}
(mt/user-http-request :rasta :post 200 "pulse/test" (assoc result :channels [email-channel]))))
(is (= (mt/email-to :rasta {:subject "Pulse: A Pulse"
:body {"A Pulse" true}})
(mt/regex-email-bodies #"A Pulse"))))))))))
(deftest dont-run-cards-async-test
(testing "A Card saved with `:async?` true should not be ran async for a Pulse"
(is (map? (#'pulse-api/pulse-card-query-results
{:id 1
:dataset_query {:database (mt/id)
:type :query
:query {:source-table (mt/id :venues)
:limit 1}
:async? true}})))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/form_input |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest form-input-test
(testing "GET /api/pulse/form_input"
(testing "Check that Slack channels come back when configured"
(mt/with-temporary-setting-values [slack-token "something"]
(with-redefs [slack/conversations-list (constantly [{:name "foo"}])
slack/users-list (constantly [{:name "bar"}])]
(is (= [{:name "channel", :type "select", :displayName "Post to", :options ["#foo" "@bar"], :required true}]
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])))))))
(testing "When slack is not configured, `form_input` returns no channels"
(mt/with-temporary-setting-values [slack-token nil]
(is (empty?
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])
(first)
(:options))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | GET /api/pulse/preview_card/:id |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest preview-pulse-test
(testing "GET /api/pulse/preview_card/:id"
(mt/with-temp* [Collection [collection]
Card [card {:dataset_query (mt/mbql-query checkins {:limit 5})}]]
(letfn [(preview [expected-status-code]
(http/client-full-response (mt/user->credentials :rasta)
:get expected-status-code (format "pulse/preview_card_png/%d" (u/the-id card))))]
(testing "Should be able to preview a Pulse"
(let [{{:strs [Content-Type]} :headers, :keys [body]} (preview 200)]
(is (= "image/png"
Content-Type))
(is (some? body))))
(testing "If rendering a Pulse fails (e.g. because font registration failed) the endpoint should return the error message"
(with-redefs [png/register-fonts-if-needed! (fn []
(throw (ex-info "Can't register fonts!"
{}
(NullPointerException.))))]
(let [{{:strs [Content-Type]} :headers, :keys [body]} (mt/suppress-output (preview 500))]
(is (= "application/json;charset=utf-8"
Content-Type))
(is (schema= {:message (s/eq "Can't register fonts!")
:trace s/Any
:via s/Any
s/Keyword s/Any}
body)))))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | DELETE /api/pulse/:pulse-id/subscription |
;;; +----------------------------------------------------------------------------------------------------------------+
(deftest delete-subscription-test
(testing "DELETE /api/pulse/:pulse-id/subscription"
(mt/with-temp* [Pulse [{pulse-id :id} {:name "PI:NAME:<NAME>END_PI" :creator_id (mt/user->id :crowberto)}]
PulseChannel [{channel-id :id} {:pulse_id pulse-id
:channel_type "email"
:schedule_type "daily"
:details {:other "stuff"
:emails ["PI:EMAIL:<EMAIL>END_PI"]}}]]
(testing "Should be able to delete your own subscription"
(mt/with-temp PulseChannelRecipient [pcr {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= nil
(mt/user-http-request :rasta :delete 204 (str "pulse/" pulse-id "/subscription/email"))))))
(testing "Users can't delete someone else's pulse subscription"
(mt/with-temp PulseChannelRecipient [pcr {:pulse_channel_id channel-id :user_id (mt/user->id :rasta)}]
(is (= "Not found."
(mt/user-http-request :lucky :delete 404 (str "pulse/" pulse-id "/subscription/email")))))))))
|
[
{
"context": "re.\"\n [username]\n (dosync\n (let [past-visitor (@visitors username)]\n (if past-visitor\n ",
"end": 200,
"score": 0.568389892578125,
"start": 200,
"tag": "USERNAME",
"value": ""
},
{
"context": " (str \"Hello, \" username))))))\n\n(println (hello \"Bob\"))\n(println (hello \"Cat\"))\n(println (hello \"Bob\")",
"end": 400,
"score": 0.9979239702224731,
"start": 397,
"tag": "NAME",
"value": "Bob"
},
{
"context": "e))))))\n\n(println (hello \"Bob\"))\n(println (hello \"Cat\"))\n(println (hello \"Bob\"))\n(println @visitors)\n\n",
"end": 424,
"score": 0.9989570379257202,
"start": 421,
"tag": "NAME",
"value": "Cat"
},
{
"context": " \"Bob\"))\n(println (hello \"Cat\"))\n(println (hello \"Bob\"))\n(println @visitors)\n\n",
"end": 448,
"score": 0.9976328611373901,
"start": 445,
"tag": "NAME",
"value": "Bob"
}
] |
Clojure/introduction.clj
|
pauldoo/scratch
| 0 |
#!/usr/bin/env clj
(def visitors (ref #{}))
(defn hello
"Writes hello message to *out*. Calls you by username.
Knows if you have been here before."
[username]
(dosync
(let [past-visitor (@visitors username)]
(if past-visitor
(str "Welcome back, " username)
(do
(alter visitors conj username)
(str "Hello, " username))))))
(println (hello "Bob"))
(println (hello "Cat"))
(println (hello "Bob"))
(println @visitors)
|
119394
|
#!/usr/bin/env clj
(def visitors (ref #{}))
(defn hello
"Writes hello message to *out*. Calls you by username.
Knows if you have been here before."
[username]
(dosync
(let [past-visitor (@visitors username)]
(if past-visitor
(str "Welcome back, " username)
(do
(alter visitors conj username)
(str "Hello, " username))))))
(println (hello "<NAME>"))
(println (hello "<NAME>"))
(println (hello "<NAME>"))
(println @visitors)
| true |
#!/usr/bin/env clj
(def visitors (ref #{}))
(defn hello
"Writes hello message to *out*. Calls you by username.
Knows if you have been here before."
[username]
(dosync
(let [past-visitor (@visitors username)]
(if past-visitor
(str "Welcome back, " username)
(do
(alter visitors conj username)
(str "Hello, " username))))))
(println (hello "PI:NAME:<NAME>END_PI"))
(println (hello "PI:NAME:<NAME>END_PI"))
(println (hello "PI:NAME:<NAME>END_PI"))
(println @visitors)
|
[
{
"context": "issue. Please try again,\n or contact [email protected] if the problem persists.\"]\n [:div.bloc",
"end": 2064,
"score": 0.9999048113822937,
"start": 2038,
"tag": "EMAIL",
"value": "[email protected]"
}
] |
src/main/pages/authenticate.cljs
|
instantwebsite/dashboard
| 3 |
(ns pages.authenticate
(:require
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
;;
[reagent.core :as r]
;;
[auth :refer [get-token
get-access-token
persist-token!]]
[api :as api]
[notify :refer [notify!]]
[state :refer [app-state]]
[router :refer [go-to-page ev-go-to-page]]))
(defn location-search []
(.-search js/location))
(defn return-to []
(if (= (location-search) "")
nil
(last
(str/split (location-search)
#"="))))
(defn $authenticate []
(let [error (r/atom nil)]
(r/create-class
{:component-did-mount
(fn []
(let [auth (str/split (str/join "" (rest (-> js/window .-location .-hash))) #"/")
email (first auth)
login-code (second auth)]
(get-token email
login-code
(fn [err profile]
(if err
(reset! error err)
(let [token (select-keys profile [:tokens/api :tokens/plugin])]
(swap! app-state assoc :tokens token)
(persist-token! token)
(swap! app-state assoc :username email)
(api/get-me (fn [res]
(swap! app-state assoc :user (:user res))
(if (return-to)
(go-to-page app-state (return-to))
(go-to-page app-state "/websites"))))))))
(println "Grabbing token and getting access/refresh token")))
:render
(fn []
(if @error
[:div
{:style {:width "500px"
:margin "50px auto"}}
[:div
"Something went wrong. Could be that the token expired or we're having some temporary issue. Please try again,
or contact [email protected] if the problem persists."]
[:div.block]
[:a.button.is-info
{:href "/login"
:onClick (ev-go-to-page app-state "/login")}
"Back to login"]]
[:div "Hold on, authenticating you now..."]))})))
|
22169
|
(ns pages.authenticate
(:require
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
;;
[reagent.core :as r]
;;
[auth :refer [get-token
get-access-token
persist-token!]]
[api :as api]
[notify :refer [notify!]]
[state :refer [app-state]]
[router :refer [go-to-page ev-go-to-page]]))
(defn location-search []
(.-search js/location))
(defn return-to []
(if (= (location-search) "")
nil
(last
(str/split (location-search)
#"="))))
(defn $authenticate []
(let [error (r/atom nil)]
(r/create-class
{:component-did-mount
(fn []
(let [auth (str/split (str/join "" (rest (-> js/window .-location .-hash))) #"/")
email (first auth)
login-code (second auth)]
(get-token email
login-code
(fn [err profile]
(if err
(reset! error err)
(let [token (select-keys profile [:tokens/api :tokens/plugin])]
(swap! app-state assoc :tokens token)
(persist-token! token)
(swap! app-state assoc :username email)
(api/get-me (fn [res]
(swap! app-state assoc :user (:user res))
(if (return-to)
(go-to-page app-state (return-to))
(go-to-page app-state "/websites"))))))))
(println "Grabbing token and getting access/refresh token")))
:render
(fn []
(if @error
[:div
{:style {:width "500px"
:margin "50px auto"}}
[:div
"Something went wrong. Could be that the token expired or we're having some temporary issue. Please try again,
or contact <EMAIL> if the problem persists."]
[:div.block]
[:a.button.is-info
{:href "/login"
:onClick (ev-go-to-page app-state "/login")}
"Back to login"]]
[:div "Hold on, authenticating you now..."]))})))
| true |
(ns pages.authenticate
(:require
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
;;
[reagent.core :as r]
;;
[auth :refer [get-token
get-access-token
persist-token!]]
[api :as api]
[notify :refer [notify!]]
[state :refer [app-state]]
[router :refer [go-to-page ev-go-to-page]]))
(defn location-search []
(.-search js/location))
(defn return-to []
(if (= (location-search) "")
nil
(last
(str/split (location-search)
#"="))))
(defn $authenticate []
(let [error (r/atom nil)]
(r/create-class
{:component-did-mount
(fn []
(let [auth (str/split (str/join "" (rest (-> js/window .-location .-hash))) #"/")
email (first auth)
login-code (second auth)]
(get-token email
login-code
(fn [err profile]
(if err
(reset! error err)
(let [token (select-keys profile [:tokens/api :tokens/plugin])]
(swap! app-state assoc :tokens token)
(persist-token! token)
(swap! app-state assoc :username email)
(api/get-me (fn [res]
(swap! app-state assoc :user (:user res))
(if (return-to)
(go-to-page app-state (return-to))
(go-to-page app-state "/websites"))))))))
(println "Grabbing token and getting access/refresh token")))
:render
(fn []
(if @error
[:div
{:style {:width "500px"
:margin "50px auto"}}
[:div
"Something went wrong. Could be that the token expired or we're having some temporary issue. Please try again,
or contact PI:EMAIL:<EMAIL>END_PI if the problem persists."]
[:div.block]
[:a.button.is-info
{:href "/login"
:onClick (ev-go-to-page app-state "/login")}
"Back to login"]]
[:div "Hold on, authenticating you now..."]))})))
|
[
{
"context": "uest id.\"\n \"CMR-Request-Id\")\n\n(def TOKEN_HEADER \"echo-token\")\n\n(def CONTENT_TYPE_HEADER \"Content-Type\")\n\n(def",
"end": 678,
"score": 0.655855119228363,
"start": 668,
"tag": "KEY",
"value": "echo-token"
}
] |
common-app-lib/src/cmr/common_app/api/routes.clj
|
jflewis/Common-Metadata-Repository
| 0 |
(ns cmr.common-app.api.routes
"Defines routes that are common across multiple applications."
(:require
[cheshire.core :as json]
[cmr.acl.core :as acl]
[cmr.common.api.context :as cxt]
[cmr.common.cache :as cache]
[cmr.common.jobs :as jobs]
[cmr.common.log :refer [debug info warn error]]
[cmr.common.mime-types :as mt]
[cmr.common.xml :as cx]
[compojure.core :refer [context GET POST]]
[ring.middleware.json :as ring-json]
[ring.util.codec :as rc]
[ring.util.response :as ring-resp]))
(def RESPONSE_REQUEST_ID_HEADER
"The HTTP response header field containing the current request id."
"CMR-Request-Id")
(def TOKEN_HEADER "echo-token")
(def CONTENT_TYPE_HEADER "Content-Type")
(def HITS_HEADER "CMR-Hits")
(def TOOK_HEADER "CMR-Took")
(def SCROLL_ID_HEADER "CMR-Scroll-Id")
(def CORS_ORIGIN_HEADER
"This CORS header is to restrict access to the resource to be only from the defined origins,
value of \"*\" means all request origins have access to the resource"
"Access-Control-Allow-Origin")
(def CORS_METHODS_HEADER
"This CORS header is to define the allowed access methods"
"Access-Control-Allow-Methods")
(def CORS_CUSTOM_ALLOWED_HEADER
"This CORS header is to define the allowed custom headers"
"Access-Control-Allow-Headers")
(def CORS_CUSTOM_EXPOSED_HEADER
"This CORS header is to define the exposed custom headers"
"Access-Control-Expose-Headers")
(def CORS_MAX_AGE_HEADER
"This CORS header is to define how long in seconds the response of the preflight request can be cached"
"Access-Control-Max-Age")
(defn search-response-headers
"Generate headers for search response. CORS response headers can be tested through
dev-system/resources/cors_headers_test.html"
[content-type results]
(merge {CONTENT_TYPE_HEADER (mt/with-utf-8 content-type)
CORS_CUSTOM_EXPOSED_HEADER "CMR-Hits, CMR-Request-Id, CMR-Scroll-Id"
CORS_ORIGIN_HEADER "*"}
(when (:hits results) {HITS_HEADER (str (:hits results))})
(when (:took results) {TOOK_HEADER (str (:took results))})
(when (:scroll-id results) {SCROLL_ID_HEADER (str (:scroll-id results))})))
(defn search-response
"Generate the response map for finding concepts"
[{:keys [results result-format] :as response}]
{:status 200
:headers (search-response-headers
(if (string? result-format)
result-format
(mt/format->mime-type result-format))
response)
:body results})
(def options-response
"Generate the response map when requesting options"
{:status 200
:headers {CONTENT_TYPE_HEADER "text/plain; charset=utf-8"
CORS_ORIGIN_HEADER "*"
CORS_METHODS_HEADER "POST, GET, OPTIONS"
CORS_CUSTOM_ALLOWED_HEADER "Echo-Token, Client-Id, CMR-Request-Id, CMR-Scroll-Id"
;; the value in seconds for how long the response to the preflight request can be cached
;; set to 30 days
CORS_MAX_AGE_HEADER "2592000"}})
(def cache-api-routes
"Create routes for the cache querying/management api"
(context "/caches" []
;; Get the list of caches
(GET "/" {:keys [params request-context headers]}
(acl/verify-ingest-management-permission request-context :read)
(let [caches (map name (keys (get-in request-context [:system :caches])))]
{:status 200
:body (json/generate-string caches)}))
;; Get the keys for the given cache
(GET "/:cache-name" {{:keys [cache-name] :as params} :params
request-context :request-context
headers :headers}
(acl/verify-ingest-management-permission request-context :read)
(let [cache (cache/context->cache request-context (keyword cache-name))]
(when cache
(let [result (cache/get-keys cache)]
{:status 200
:body (json/generate-string result)}))))
;; Get the value for the given key for the given cache
(GET "/:cache-name/:cache-key" {{:keys [cache-name cache-key] :as params} :params
request-context :request-context
headers :headers}
(acl/verify-ingest-management-permission request-context :read)
(let [cache-key (keyword cache-key)
cache (cache/context->cache request-context (keyword cache-name))
result (cache/get-value cache cache-key)]
(when result
{:status 200
:body (json/generate-string result)})))
(POST "/clear-cache" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(cache/reset-caches request-context)
{:status 200})))
(defn job-api-routes
"Creates common routes for managing jobs such as pausing and resuming. The caller must have
system ingest management update permission to call any of the jobs routes."
([]
(job-api-routes nil))
([additional-job-routes]
(context "/jobs" []
;; Pause all jobs
(POST "/pause" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(jobs/pause-jobs (get-in request-context [:system :scheduler]))
{:status 204})
;; Resume all jobs
(POST "/resume" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(jobs/resume-jobs (get-in request-context [:system :scheduler]))
{:status 204})
;; Retrieve status of jobs - whether they are paused or active
(GET "/status" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(let [paused? (jobs/paused? (get-in request-context [:system :scheduler]))]
{:status 200
:body (json/generate-string {:paused paused?})}))
additional-job-routes)))
(defn pretty-request?
"Returns true if the request indicates the response should be returned in a human readable
fashion. This can be specified either through a pretty=true in the URL query parameters or
through a Cmr-Pretty HTTP header."
[request]
(let [{:keys [headers params]} request]
(or (= "true" (get params "pretty"))
(= "true" (get headers "cmr-pretty")))))
(defn pretty-print-json
[json-str]
(-> json-str
json/parse-string
(json/generate-string {:pretty true})))
(defn update-response-body-with-fn
[response f]
(let [^String new-body (f (:body response))]
(-> response
(assoc-in [:body] new-body)
(assoc-in [:headers "Content-Length"] (str (count (.getBytes new-body "UTF-8"))))
(ring-resp/charset "UTF-8"))))
(defn- pretty-print-body
"Update the body of the response to a pretty printed string based on the content type"
[response]
(let [mime-type (mt/content-type-mime-type (:headers response))
find-re (fn [re] (and mime-type (re-find re mime-type)))]
(if (string? (:body response))
(cond
(find-re #"application/.*json.*")
(update-response-body-with-fn response pretty-print-json)
(find-re #"application/.*xml.*")
(update-response-body-with-fn response cx/pretty-print-xml)
:else response)
(update-response-body-with-fn response #(json/generate-string % {:pretty true})))))
(defn pretty-print-response-handler
"Middleware which pretty prints the response if the parameter pretty in the
URL query is set to true of if the header Cmr-Pretty is set to true."
[handler]
(fn [request]
(let [pretty? (pretty-request? request)
request (-> request
(update-in [:params] dissoc "pretty")
(update-in [:query-params] dissoc "pretty"))]
(if pretty?
(pretty-print-body (handler request))
((ring-json/wrap-json-response handler) request)))))
(defn add-request-id-response-handler
"Adds a request id header to every response to facilitate clientside debugging."
[handler]
(fn [{context :request-context :as request}]
(if-let [request-id (cxt/context->request-id context)]
(-> request
(handler)
(assoc-in [:headers RESPONSE_REQUEST_ID_HEADER] request-id))
((ring-json/wrap-json-response handler) request))))
|
56870
|
(ns cmr.common-app.api.routes
"Defines routes that are common across multiple applications."
(:require
[cheshire.core :as json]
[cmr.acl.core :as acl]
[cmr.common.api.context :as cxt]
[cmr.common.cache :as cache]
[cmr.common.jobs :as jobs]
[cmr.common.log :refer [debug info warn error]]
[cmr.common.mime-types :as mt]
[cmr.common.xml :as cx]
[compojure.core :refer [context GET POST]]
[ring.middleware.json :as ring-json]
[ring.util.codec :as rc]
[ring.util.response :as ring-resp]))
(def RESPONSE_REQUEST_ID_HEADER
"The HTTP response header field containing the current request id."
"CMR-Request-Id")
(def TOKEN_HEADER "<KEY>")
(def CONTENT_TYPE_HEADER "Content-Type")
(def HITS_HEADER "CMR-Hits")
(def TOOK_HEADER "CMR-Took")
(def SCROLL_ID_HEADER "CMR-Scroll-Id")
(def CORS_ORIGIN_HEADER
"This CORS header is to restrict access to the resource to be only from the defined origins,
value of \"*\" means all request origins have access to the resource"
"Access-Control-Allow-Origin")
(def CORS_METHODS_HEADER
"This CORS header is to define the allowed access methods"
"Access-Control-Allow-Methods")
(def CORS_CUSTOM_ALLOWED_HEADER
"This CORS header is to define the allowed custom headers"
"Access-Control-Allow-Headers")
(def CORS_CUSTOM_EXPOSED_HEADER
"This CORS header is to define the exposed custom headers"
"Access-Control-Expose-Headers")
(def CORS_MAX_AGE_HEADER
"This CORS header is to define how long in seconds the response of the preflight request can be cached"
"Access-Control-Max-Age")
(defn search-response-headers
"Generate headers for search response. CORS response headers can be tested through
dev-system/resources/cors_headers_test.html"
[content-type results]
(merge {CONTENT_TYPE_HEADER (mt/with-utf-8 content-type)
CORS_CUSTOM_EXPOSED_HEADER "CMR-Hits, CMR-Request-Id, CMR-Scroll-Id"
CORS_ORIGIN_HEADER "*"}
(when (:hits results) {HITS_HEADER (str (:hits results))})
(when (:took results) {TOOK_HEADER (str (:took results))})
(when (:scroll-id results) {SCROLL_ID_HEADER (str (:scroll-id results))})))
(defn search-response
"Generate the response map for finding concepts"
[{:keys [results result-format] :as response}]
{:status 200
:headers (search-response-headers
(if (string? result-format)
result-format
(mt/format->mime-type result-format))
response)
:body results})
(def options-response
"Generate the response map when requesting options"
{:status 200
:headers {CONTENT_TYPE_HEADER "text/plain; charset=utf-8"
CORS_ORIGIN_HEADER "*"
CORS_METHODS_HEADER "POST, GET, OPTIONS"
CORS_CUSTOM_ALLOWED_HEADER "Echo-Token, Client-Id, CMR-Request-Id, CMR-Scroll-Id"
;; the value in seconds for how long the response to the preflight request can be cached
;; set to 30 days
CORS_MAX_AGE_HEADER "2592000"}})
(def cache-api-routes
"Create routes for the cache querying/management api"
(context "/caches" []
;; Get the list of caches
(GET "/" {:keys [params request-context headers]}
(acl/verify-ingest-management-permission request-context :read)
(let [caches (map name (keys (get-in request-context [:system :caches])))]
{:status 200
:body (json/generate-string caches)}))
;; Get the keys for the given cache
(GET "/:cache-name" {{:keys [cache-name] :as params} :params
request-context :request-context
headers :headers}
(acl/verify-ingest-management-permission request-context :read)
(let [cache (cache/context->cache request-context (keyword cache-name))]
(when cache
(let [result (cache/get-keys cache)]
{:status 200
:body (json/generate-string result)}))))
;; Get the value for the given key for the given cache
(GET "/:cache-name/:cache-key" {{:keys [cache-name cache-key] :as params} :params
request-context :request-context
headers :headers}
(acl/verify-ingest-management-permission request-context :read)
(let [cache-key (keyword cache-key)
cache (cache/context->cache request-context (keyword cache-name))
result (cache/get-value cache cache-key)]
(when result
{:status 200
:body (json/generate-string result)})))
(POST "/clear-cache" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(cache/reset-caches request-context)
{:status 200})))
(defn job-api-routes
"Creates common routes for managing jobs such as pausing and resuming. The caller must have
system ingest management update permission to call any of the jobs routes."
([]
(job-api-routes nil))
([additional-job-routes]
(context "/jobs" []
;; Pause all jobs
(POST "/pause" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(jobs/pause-jobs (get-in request-context [:system :scheduler]))
{:status 204})
;; Resume all jobs
(POST "/resume" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(jobs/resume-jobs (get-in request-context [:system :scheduler]))
{:status 204})
;; Retrieve status of jobs - whether they are paused or active
(GET "/status" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(let [paused? (jobs/paused? (get-in request-context [:system :scheduler]))]
{:status 200
:body (json/generate-string {:paused paused?})}))
additional-job-routes)))
(defn pretty-request?
"Returns true if the request indicates the response should be returned in a human readable
fashion. This can be specified either through a pretty=true in the URL query parameters or
through a Cmr-Pretty HTTP header."
[request]
(let [{:keys [headers params]} request]
(or (= "true" (get params "pretty"))
(= "true" (get headers "cmr-pretty")))))
(defn pretty-print-json
[json-str]
(-> json-str
json/parse-string
(json/generate-string {:pretty true})))
(defn update-response-body-with-fn
[response f]
(let [^String new-body (f (:body response))]
(-> response
(assoc-in [:body] new-body)
(assoc-in [:headers "Content-Length"] (str (count (.getBytes new-body "UTF-8"))))
(ring-resp/charset "UTF-8"))))
(defn- pretty-print-body
"Update the body of the response to a pretty printed string based on the content type"
[response]
(let [mime-type (mt/content-type-mime-type (:headers response))
find-re (fn [re] (and mime-type (re-find re mime-type)))]
(if (string? (:body response))
(cond
(find-re #"application/.*json.*")
(update-response-body-with-fn response pretty-print-json)
(find-re #"application/.*xml.*")
(update-response-body-with-fn response cx/pretty-print-xml)
:else response)
(update-response-body-with-fn response #(json/generate-string % {:pretty true})))))
(defn pretty-print-response-handler
"Middleware which pretty prints the response if the parameter pretty in the
URL query is set to true of if the header Cmr-Pretty is set to true."
[handler]
(fn [request]
(let [pretty? (pretty-request? request)
request (-> request
(update-in [:params] dissoc "pretty")
(update-in [:query-params] dissoc "pretty"))]
(if pretty?
(pretty-print-body (handler request))
((ring-json/wrap-json-response handler) request)))))
(defn add-request-id-response-handler
"Adds a request id header to every response to facilitate clientside debugging."
[handler]
(fn [{context :request-context :as request}]
(if-let [request-id (cxt/context->request-id context)]
(-> request
(handler)
(assoc-in [:headers RESPONSE_REQUEST_ID_HEADER] request-id))
((ring-json/wrap-json-response handler) request))))
| true |
(ns cmr.common-app.api.routes
"Defines routes that are common across multiple applications."
(:require
[cheshire.core :as json]
[cmr.acl.core :as acl]
[cmr.common.api.context :as cxt]
[cmr.common.cache :as cache]
[cmr.common.jobs :as jobs]
[cmr.common.log :refer [debug info warn error]]
[cmr.common.mime-types :as mt]
[cmr.common.xml :as cx]
[compojure.core :refer [context GET POST]]
[ring.middleware.json :as ring-json]
[ring.util.codec :as rc]
[ring.util.response :as ring-resp]))
(def RESPONSE_REQUEST_ID_HEADER
"The HTTP response header field containing the current request id."
"CMR-Request-Id")
(def TOKEN_HEADER "PI:KEY:<KEY>END_PI")
(def CONTENT_TYPE_HEADER "Content-Type")
(def HITS_HEADER "CMR-Hits")
(def TOOK_HEADER "CMR-Took")
(def SCROLL_ID_HEADER "CMR-Scroll-Id")
(def CORS_ORIGIN_HEADER
"This CORS header is to restrict access to the resource to be only from the defined origins,
value of \"*\" means all request origins have access to the resource"
"Access-Control-Allow-Origin")
(def CORS_METHODS_HEADER
"This CORS header is to define the allowed access methods"
"Access-Control-Allow-Methods")
(def CORS_CUSTOM_ALLOWED_HEADER
"This CORS header is to define the allowed custom headers"
"Access-Control-Allow-Headers")
(def CORS_CUSTOM_EXPOSED_HEADER
"This CORS header is to define the exposed custom headers"
"Access-Control-Expose-Headers")
(def CORS_MAX_AGE_HEADER
"This CORS header is to define how long in seconds the response of the preflight request can be cached"
"Access-Control-Max-Age")
(defn search-response-headers
"Generate headers for search response. CORS response headers can be tested through
dev-system/resources/cors_headers_test.html"
[content-type results]
(merge {CONTENT_TYPE_HEADER (mt/with-utf-8 content-type)
CORS_CUSTOM_EXPOSED_HEADER "CMR-Hits, CMR-Request-Id, CMR-Scroll-Id"
CORS_ORIGIN_HEADER "*"}
(when (:hits results) {HITS_HEADER (str (:hits results))})
(when (:took results) {TOOK_HEADER (str (:took results))})
(when (:scroll-id results) {SCROLL_ID_HEADER (str (:scroll-id results))})))
(defn search-response
"Generate the response map for finding concepts"
[{:keys [results result-format] :as response}]
{:status 200
:headers (search-response-headers
(if (string? result-format)
result-format
(mt/format->mime-type result-format))
response)
:body results})
(def options-response
"Generate the response map when requesting options"
{:status 200
:headers {CONTENT_TYPE_HEADER "text/plain; charset=utf-8"
CORS_ORIGIN_HEADER "*"
CORS_METHODS_HEADER "POST, GET, OPTIONS"
CORS_CUSTOM_ALLOWED_HEADER "Echo-Token, Client-Id, CMR-Request-Id, CMR-Scroll-Id"
;; the value in seconds for how long the response to the preflight request can be cached
;; set to 30 days
CORS_MAX_AGE_HEADER "2592000"}})
(def cache-api-routes
"Create routes for the cache querying/management api"
(context "/caches" []
;; Get the list of caches
(GET "/" {:keys [params request-context headers]}
(acl/verify-ingest-management-permission request-context :read)
(let [caches (map name (keys (get-in request-context [:system :caches])))]
{:status 200
:body (json/generate-string caches)}))
;; Get the keys for the given cache
(GET "/:cache-name" {{:keys [cache-name] :as params} :params
request-context :request-context
headers :headers}
(acl/verify-ingest-management-permission request-context :read)
(let [cache (cache/context->cache request-context (keyword cache-name))]
(when cache
(let [result (cache/get-keys cache)]
{:status 200
:body (json/generate-string result)}))))
;; Get the value for the given key for the given cache
(GET "/:cache-name/:cache-key" {{:keys [cache-name cache-key] :as params} :params
request-context :request-context
headers :headers}
(acl/verify-ingest-management-permission request-context :read)
(let [cache-key (keyword cache-key)
cache (cache/context->cache request-context (keyword cache-name))
result (cache/get-value cache cache-key)]
(when result
{:status 200
:body (json/generate-string result)})))
(POST "/clear-cache" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(cache/reset-caches request-context)
{:status 200})))
(defn job-api-routes
"Creates common routes for managing jobs such as pausing and resuming. The caller must have
system ingest management update permission to call any of the jobs routes."
([]
(job-api-routes nil))
([additional-job-routes]
(context "/jobs" []
;; Pause all jobs
(POST "/pause" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(jobs/pause-jobs (get-in request-context [:system :scheduler]))
{:status 204})
;; Resume all jobs
(POST "/resume" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(jobs/resume-jobs (get-in request-context [:system :scheduler]))
{:status 204})
;; Retrieve status of jobs - whether they are paused or active
(GET "/status" {:keys [request-context params headers]}
(acl/verify-ingest-management-permission request-context :update)
(let [paused? (jobs/paused? (get-in request-context [:system :scheduler]))]
{:status 200
:body (json/generate-string {:paused paused?})}))
additional-job-routes)))
(defn pretty-request?
"Returns true if the request indicates the response should be returned in a human readable
fashion. This can be specified either through a pretty=true in the URL query parameters or
through a Cmr-Pretty HTTP header."
[request]
(let [{:keys [headers params]} request]
(or (= "true" (get params "pretty"))
(= "true" (get headers "cmr-pretty")))))
(defn pretty-print-json
[json-str]
(-> json-str
json/parse-string
(json/generate-string {:pretty true})))
(defn update-response-body-with-fn
[response f]
(let [^String new-body (f (:body response))]
(-> response
(assoc-in [:body] new-body)
(assoc-in [:headers "Content-Length"] (str (count (.getBytes new-body "UTF-8"))))
(ring-resp/charset "UTF-8"))))
(defn- pretty-print-body
"Update the body of the response to a pretty printed string based on the content type"
[response]
(let [mime-type (mt/content-type-mime-type (:headers response))
find-re (fn [re] (and mime-type (re-find re mime-type)))]
(if (string? (:body response))
(cond
(find-re #"application/.*json.*")
(update-response-body-with-fn response pretty-print-json)
(find-re #"application/.*xml.*")
(update-response-body-with-fn response cx/pretty-print-xml)
:else response)
(update-response-body-with-fn response #(json/generate-string % {:pretty true})))))
(defn pretty-print-response-handler
"Middleware which pretty prints the response if the parameter pretty in the
URL query is set to true of if the header Cmr-Pretty is set to true."
[handler]
(fn [request]
(let [pretty? (pretty-request? request)
request (-> request
(update-in [:params] dissoc "pretty")
(update-in [:query-params] dissoc "pretty"))]
(if pretty?
(pretty-print-body (handler request))
((ring-json/wrap-json-response handler) request)))))
(defn add-request-id-response-handler
"Adds a request id header to every response to facilitate clientside debugging."
[handler]
(fn [{context :request-context :as request}]
(if-let [request-id (cxt/context->request-id context)]
(-> request
(handler)
(assoc-in [:headers RESPONSE_REQUEST_ID_HEADER] request-id))
((ring-json/wrap-json-response handler) request))))
|
[
{
"context": " :rarity :special}})\n\n [{:name \"Arden Angel\"\n :cost \"{4}{W}{W}\"\n :typelist [\"Creature",
"end": 3901,
"score": 0.9992356300354004,
"start": 3890,
"tag": "NAME",
"value": "Arden Angel"
},
{
"context": " {:text \"At the beginning of your upkeep, if Arden Angel is in your graveyard, choose a number from 1 to 4",
"end": 4094,
"score": 0.958659291267395,
"start": 4083,
"tag": "NAME",
"value": "Arden Angel"
},
{
"context": "r from 1 to 4 at random. If it's 1, you may return Arden Angel onto the battlefield.\"}]}\n\n {:name \"Ashu",
"end": 4187,
"score": 0.8479071855545044,
"start": 4182,
"tag": "NAME",
"value": "Arden"
},
{
"context": "rden Angel onto the battlefield.\"}]}\n\n {:name \"Ashuza's Breath\"\n :cost \"{1}{R}\"\n :typelist [\"Sorcery\"]\n ",
"end": 4248,
"score": 0.9873997569084167,
"start": 4233,
"tag": "NAME",
"value": "Ashuza's Breath"
},
{
"context": " :typelist [\"Sorcery\"]\n :rulelist [{:text \"Ashuza's Breath deals X damage to each creature, where X",
"end": 4327,
"score": 0.7954251170158386,
"start": 4321,
"tag": "NAME",
"value": "Ashuza"
},
{
"context": "er chosen at random from 0 to 2.\"}]}\n\n {:name \"Camato Scout\"\n :cost \"{1}{U}{U}\"\n :typelist [\"Creature",
"end": 4449,
"score": 0.9905728101730347,
"start": 4437,
"tag": "NAME",
"value": "Camato Scout"
},
{
"context": "pow \"2\"\n :tgh \"3\"\n :rulelist [{:text \"When Camato Scout enters the battlefield, it gains landwalk of a ba",
"end": 4589,
"score": 0.7907559871673584,
"start": 4577,
"tag": "NAME",
"value": "Camato Scout"
},
{
"context": "\"This effect lasts indefinitely.\"}]}\n\n {:name \"Hapato's Might\"\n :cost \"{2}{B}\"\n :typelist [\"Instant\"]\n ",
"end": 4763,
"score": 0.9914590716362,
"start": 4749,
"tag": "NAME",
"value": "Hapato's Might"
},
{
"context": "ber chosen randomly from 0 to 6.\"}]}\n\n {:name \"Lydari Druid\"\n :cost \"{2}{G}\"\n :typelist [\"Creature\" \"",
"end": 4960,
"score": 0.9905727505683899,
"start": 4948,
"tag": "NAME",
"value": "Lydari Druid"
},
{
"context": "pow \"2\"\n :tgh \"2\"\n :rulelist [{:text \"When Lydari Druid enters the battlefield, for each land, choose a b",
"end": 5095,
"score": 0.9371696710586548,
"start": 5083,
"tag": "NAME",
"value": "Lydari Druid"
},
{
"context": "\"This effect lasts indefinitely.\"}]}\n\n {:name \"Lydari Elephant\"\n :cost \"{4}{G}\"\n :typelist [\"Creature\" \"",
"end": 5298,
"score": 0.9841993451118469,
"start": 5283,
"tag": "NAME",
"value": "Lydari Elephant"
},
{
"context": "ers randomly chosen from 3 to 7.\"}]}\n\n {:name \"Murgish Cemetery\"\n :cost \"{4}{B}{B}\"\n :typelist [\"Enchantm",
"end": 5557,
"score": 0.994661808013916,
"start": 5541,
"tag": "NAME",
"value": "Murgish Cemetery"
},
{
"context": "ber randomly chosen from 2 to 6.\"}]}\n\n {:name \"Saji's Torrent\"\n :cost \"{1}{U}\"\n :typelist [\"Instant\"]\n ",
"end": 5793,
"score": 0.8901723027229309,
"start": 5779,
"tag": "NAME",
"value": "Saji's Torrent"
},
{
"context": "hat many creatures and tap them.\"}]}\n\n {:name \"Tornellan Protector\"\n :cost \"{2}{W}\"\n :typelist [\"Creature\" \"",
"end": 5987,
"score": 0.8131504058837891,
"start": 5968,
"tag": "NAME",
"value": "Tornellan Protector"
},
{
"context": "that creature or player instead.\"}]}\n\n {:name \"Velican Dragon\"\n :cost \"{5}{R}{R}\"\n :typelist [\"Creature",
"end": 6346,
"score": 0.9798073768615723,
"start": 6332,
"tag": "NAME",
"value": "Velican Dragon"
},
{
"context": " :rarity :special}})\n\n [{:name \"Aswan Jaguar\"\n :cost \"{1}{G}{G}\"\n :typelist [\"Creature",
"end": 6829,
"score": 0.9968487620353699,
"start": 6817,
"tag": "NAME",
"value": "Aswan Jaguar"
},
{
"context": " :pow \"2\"\n :tgh \"2\"\n :rulelist [{:text \"As Aswan Jaguar enters the battlefield, choose a creature type at",
"end": 6955,
"score": 0.9499568939208984,
"start": 6943,
"tag": "NAME",
"value": "Aswan Jaguar"
},
{
"context": "n type. It can't be regenerated.\"}]}\n\n {:name \"Call from the Grave\"\n :cost \"{2}{B}\"\n :typelist [\"S",
"end": 7235,
"score": 0.9276164770126343,
"start": 7226,
"tag": "NAME",
"value": "Call from"
},
{
"context": " be regenerated.\"}]}\n\n {:name \"Call from the Grave\"\n :cost \"{2}{B}\"\n :typelist [\"Sorcery\"]\n ",
"end": 7245,
"score": 0.7240959405899048,
"start": 7242,
"tag": "NAME",
"value": "ave"
},
{
"context": "rd's converted mana cost to you.\"}]}\n\n {:name \"Faerie Dragon\"\n :cost \"{2}{G}{G}\"\n :typelist [\"Creature",
"end": 7578,
"score": 0.9996458292007446,
"start": 7565,
"tag": "NAME",
"value": "Faerie Dragon"
},
{
"context": "anent remain unchanged.\"}\n {:text \"Faerie Dragon deals 3 damage to a creature or player chosen at ",
"end": 8745,
"score": 0.9717885851860046,
"start": 8732,
"tag": "NAME",
"value": "Faerie Dragon"
},
{
"context": "om to its owner's hand.\"}\n {:text \"Faerie Dragon deals 1 damage to a creature or player chosen at ",
"end": 10081,
"score": 0.9454492330551147,
"start": 10068,
"tag": "NAME",
"value": "Faerie Dragon"
},
{
"context": "m.\"}\n {:text \"A creature other than Faerie Dragon chosen at random becomes 0/2 until end of turn.\"}",
"end": 10200,
"score": 0.8221215009689331,
"start": 10187,
"tag": "NAME",
"value": "Faerie Dragon"
},
{
"context": "f creatures chosen at random.\"}]}\n\n {:name \"Gem Bazaar\"\n :typelist [\"Land\"]\n :rulelist [{:text \"",
"end": 10499,
"score": 0.8495740294456482,
"start": 10493,
"tag": "NAME",
"value": "Bazaar"
},
{
"context": ". Then choose a color at random.\"}]}\n\n {:name \"Goblin Polka Band\"\n :cost \"{R}{R}\"\n :typelist [\"Creature\" \"",
"end": 10766,
"score": 0.9963226914405823,
"start": 10749,
"tag": "NAME",
"value": "Goblin Polka Band"
},
{
"context": "ore to activate for each target.\"}]}\n\n {:name \"Necropolis of Azar\"\n :cost \"{2}{B}{B}\"\n :typelist [\"Enchantm",
"end": 11128,
"score": 0.8887723684310913,
"start": 11110,
"tag": "NAME",
"value": "Necropolis of Azar"
},
{
"context": "s chosen at random from 1 to 3.\"}]}\n\n {:name \"Orcish Catapult\"\n :cost \"{X}{R}{R}\"\n :typelist [\"Instant\"",
"end": 11585,
"score": 0.651526689529419,
"start": 11571,
"tag": "NAME",
"value": "rcish Catapult"
},
{
"context": "ber chosen randomly from 0 to 2.\"}]}\n\n {:name \"Whimsy\"\n :cost \"{X}{U}{U}\"\n :typelist [\"Sorcery\"",
"end": 13411,
"score": 0.9681375622749329,
"start": 13405,
"tag": "NAME",
"value": "Whimsy"
}
] |
src/loa/cleanup/extra.clj
|
karmag/loa
| 4 |
(ns loa.cleanup.extra)
;;-------------------------------------------------
;; Planes
(def celestine-reef
{:name "Celestine Reef"
:typelist ["Plane" "Luvion"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Creatures without flying or islandwalk can't attack."}
{:text "Whenever you roll {C}, until a player planeswalks, you can't lose the game and your opponents can't win the game."}]})
(def horizon-boughs
{:name "Horizon Boughs"
:typelist ["Plane" "Pyrulea"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "All permanents untap during each player's untap step."}
{:text "Whenever you roll {C}, you may search your library for up to three basic land cards, put them onto the battlefield tapped, then shuffle your library."}]})
(def mirrored-depths
{:name "Mirrored Depths"
:typelist ["Plane" "Karsus"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Whenever a player casts a spell, that player flips a coin. If he or she loses the flip, counter that spell."}
{:text "Whenever you roll {C}, target player reveals the top card of his or her library. If it's a nonland card, you may cast it without paying its mana cost."}]})
(def tember-city
{:name "Tember City"
:typelist ["Plane" "Kinshala"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Whenever a player taps a land for mana, Tember City deals 1 damage to that player."}
{:text "Whenever you roll {C}, each other player sacrifices a nonland permanent."}]})
;;-------------------------------------------------
;; Schemes
(def perhaps-youve-met-my-cohort
{:name "Perhaps You've Met My Cohort"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, search your library for a planeswalker card, put it onto the battlefield, then shuffle your library."}]})
(def plots-that-span-centuries
{:name "Plots That Span Centuries"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, the next time you would set a scheme in motion, set three schemes in motion instead."}]})
(def your-inescapable-doom
{:name "Your Inescapable Doom"
:typelist ["Ongoing" "Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "At the beginning of your end step, put a doom counter on this scheme, then this scheme deals damage equal to the number of doom counters on it to the opponent with the highest life total among your opponents. If two or more players are tied for highest life total, you choose one."}]})
(def imprison-this-insolent-wretch
{:name "Imprison This Insolent Wretch"
:typelist ["Ongoing" "Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, choose an opponent."}
{:text "Permanents the chosen player controls don't untap during his or her untap step."}
{:text "When the chosen player is attacked or becomes the target of a spell or ability, abandon this scheme."}]})
(def drench-the-soil-in-their-blood
{:name "Drench the Soil in Their Blood"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, after the main phase, there is an additional combat phase followed by an additional main phase. Creatures you control gain vigilance until end of turn."}]})
;;-------------------------------------------------
;; Dreamcast
(def dreamcast-cards
(map
#(assoc % :sets {0 {:set-name "Dreamcast"
:rarity :special}})
[{:name "Arden Angel"
:cost "{4}{W}{W}"
:typelist ["Creature" "Angel"]
:pow "4"
:tgh "4"
:rulelist [{:text "Flying"}
{:text "At the beginning of your upkeep, if Arden Angel is in your graveyard, choose a number from 1 to 4 at random. If it's 1, you may return Arden Angel onto the battlefield."}]}
{:name "Ashuza's Breath"
:cost "{1}{R}"
:typelist ["Sorcery"]
:rulelist [{:text "Ashuza's Breath deals X damage to each creature, where X is a number chosen at random from 0 to 2."}]}
{:name "Camato Scout"
:cost "{1}{U}{U}"
:typelist ["Creature" "Merfolk" "Scout"]
:pow "2"
:tgh "3"
:rulelist [{:text "When Camato Scout enters the battlefield, it gains landwalk of a basic land type chosen at random."
:reminder "This effect lasts indefinitely."}]}
{:name "Hapato's Might"
:cost "{2}{B}"
:typelist ["Instant"]
:rulelist [{:text "Target creature gets +X/+0 until end of turn, where X is a number chosen randomly from 0 to 6."}]}
{:name "Lydari Druid"
:cost "{2}{G}"
:typelist ["Creature" "Human" "Druid"]
:pow "2"
:tgh "2"
:rulelist [{:text "When Lydari Druid enters the battlefield, for each land, choose a basic land type at random. That land becomes that land type."
:reminder "This effect lasts indefinitely."}]}
{:name "Lydari Elephant"
:cost "{4}{G}"
:typelist ["Creature" "Elephant"]
:pow "*"
:tgh "*"
:rulelist [{:text "Lydari Elephant enters the battlefield as a X/Y creature, where X and Y are numbers randomly chosen from 3 to 7."}]}
{:name "Murgish Cemetery"
:cost "{4}{B}{B}"
:typelist ["Enchantment"]
:rulelist [{:text "{3}{B}, Discard a card: Put an X/X black Zombie token onto the battlefield, where X is a number randomly chosen from 2 to 6."}]}
{:name "Saji's Torrent"
:cost "{1}{U}"
:typelist ["Instant"]
:rulelist [{:text "Choose a number from 0 to 5 at random, then choose that many creatures and tap them."}]}
{:name "Tornellan Protector"
:cost "{2}{W}"
:typelist ["Creature" "Human" "Cleric"]
:pow "1"
:tgh "2"
:rulelist [{:text "{T}: Choose a number from 1 to 3 at random. Until end of turn, if a source would deal damage to target creature or player, it deals that much damage minus the chosen number to that creature or player instead."}]}
{:name "Velican Dragon"
:cost "{5}{R}{R}"
:typelist ["Creature" "Dragon"]
:pow "5"
:tgh "5"
:rulelist [{:text "Flying"}
{:text "Whenever Velican Dragon becomes blocked, it gets +X/+0 until end of turn, where X is a number chosen at random from 0 to 5."}]}
]))
;;-------------------------------------------------
;; Astral
(def astral-cards
(map
#(assoc % :sets {0 {:set-name "Astral"
:rarity :special}})
[{:name "Aswan Jaguar"
:cost "{1}{G}{G}"
:typelist ["Creature" "Cat"]
:pow "2"
:tgh "2"
:rulelist [{:text "As Aswan Jaguar enters the battlefield, choose a creature type at random from among all creature types that a creature card in target opponent's decklist has."}
{:text "{G}{G}, {T}: Destroy target creature with the chosen type. It can't be regenerated."}]}
{:name "Call from the Grave"
:cost "{2}{B}"
:typelist ["Sorcery"]
:rulelist [{:text "Choose a player at random. Choose a creature card in that player's graveyard at random and put it onto the battlefield under your control. Call from the Grave deals damage equal to that creature card's converted mana cost to you."}]}
{:name "Faerie Dragon"
:cost "{2}{G}{G}"
:typelist ["Creature" "Dragon"]
:pow "1"
:tgh "3"
:rulelist [{:text "Flying"}
{:text "{1}{G}{G}: Perform a random action from the following list:"}
{:text "A creature chosen at random gains trample and gets +X/+0 until end of turn, where X is its power. At the beginning of the next end step, destroy that creature if it attacked this turn."}
{:text "You may tap or untap an artifact, creature, or land chosen at random."}
{:text "If a creature chosen at random has toughness 5 or greater, it gets +4/-4 until end of turn. Otherwise, it gets +4/-X until end of turn, where X is its toughness minus 1."}
{:text "A spell or permanent chosen at random becomes green." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes white." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes red." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "Faerie Dragon deals 3 damage to a creature or player chosen at random."}
{:text "A creature chosen at random gains flying until end of turn."}
{:text "A creature chosen at random gets +3/+3 until end of turn."}
{:text "A creature chosen at random gains banding until end of turn." :reminder "Any creatures with banding, and up to one without, can attack in a band. Bands are blocked as a group. If any creatures with banding a player controls are blocking or being blocked by a creature, that player divides that creature's combat damage, not its controller, among any of the creatures it's being blocked by or is blocking."}
{:text "A spell or permanent chosen at random becomes black." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes blue." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A creature chosen at random can't be regenerated this turn."}
{:text "If a creature chosen at random has power 2 or less, it is unblockable this turn."}
{:text "A creature chosen at random gets -2/-0 until end of turn."}
{:text "Return a creature chosen at random to its owner's hand."}
{:text "Faerie Dragon deals 1 damage to a creature or player chosen at random."}
{:text "A creature other than Faerie Dragon chosen at random becomes 0/2 until end of turn."}
{:text "Exile a creature chosen at random. Its controller gains life equal to its power."}
{:text "Randomly distribute X -0/-1 counters among a random number of creatures chosen at random."}]}
{:name "Gem Bazaar"
:typelist ["Land"]
:rulelist [{:text "As Gem Bazaar enters the battlefield, choose a color at random."}
{:text "{T}: Add one mana of the last chosen color to your mana pool. Then choose a color at random."}]}
{:name "Goblin Polka Band"
:cost "{R}{R}"
:typelist ["Creature" "Goblin"]
:pow "1"
:tgh "1"
:rulelist [{:text "{2}, {T}: Choose any number of target creatures at random. Tap those creatures. Goblins tapped this way do not untap during their controllers' next untap steps. This ability costs R more to activate for each target."}]}
{:name "Necropolis of Azar"
:cost "{2}{B}{B}"
:typelist ["Enchantment"]
:rulelist [{:text "Whenever a nonblack creature is put into a graveyard from the battlefield, put a husk counter on Necropolis of Azar."}
{:text "{5}, Remove a husk counter from Necropolis of Azar: Put a X/Y black Spawn creature token named Spawn of Azar with swampwalk onto the battlefield, where X and Y are numbers chosen at random from 1 to 3."}]}
{:name "Orcish Catapult"
:cost "{X}{R}{R}"
:typelist ["Instant"]
:rulelist [{:text "Randomly distribute X -0/-1 counters among a random number of random target creatures."}]}
{:name "Pandora's Box"
:cost "{5}"
:typelist ["Artifact"]
:rulelist [{:text "{3}, {T}: Choose a creature card at random from all players' decklists. For each player, flip a coin. If the flip ends up heads, put a token that's a copy of that creature card onto the battlefield under that player's control."}]}
{:name "Power Struggle"
:cost "{2}{U}{U}{U}"
:typelist ["Enchantment"]
:rulelist [{:text "At the beginning of each player's upkeep, exchange control of a target artifact, creature or land that player controls, chosen at random, and a random target permanent that shares one of those types with it a player who is his or her opponent chosen at random."}]}
{:name "Prismatic Dragon"
:cost "{2}{W}{W}"
:typelist ["Creature" "Dragon"]
:pow "2"
:tgh "3"
:rulelist [{:text "Flying"}
{:text "At the beginning of your upkeep, Prismatic Dragon becomes a color chosen at random." :reminder "This effect lasts indefinitely."}
{:text "{2}: Prismatic Dragon becomes a color chosen at random." :reminder "This effect lasts indefinitely."}]}
{:name "Rainbow Knights"
:cost "{W}{W}"
:typelist ["Creature" "Human" "Knight"]
:pow "2"
:tgh "1"
:rulelist [{:text "As Rainbow Knights enters the battlefield, it gains protection from a color chosen at random." :reminder "This effect lasts indefinitely."}
{:text "{1}: Rainbow Knights gains first strike until end of turn."}
{:text "{W}{W}: Rainbow Knights gets +X/+0 until end of turn, where X is a number chosen randomly from 0 to 2."}]}
{:name "Whimsy"
:cost "{X}{U}{U}"
:typelist ["Sorcery"]
:rulelist [{:text "Perform X random actions from the following list:"}
{:text "Return a permanent that isn't enchanted chosen at random to its owner's hand."}
{:text "Untap a artifact, creature or land chosen at random."}
{:text "Tap a artifact, creature or land chosen at random."}
{:text "Whimsy deals 4 damage to a creature or player chosen at random."}
{:text "A player chosen at random draws three cards."}
{:text "Destroy an artifact chosen at random. It can't be regenerated. That artifact's controller gains life equal to its converted mana cost."}
{:text "Destroy an artifact or enchantment chosen at random."}
{:text "A player chosen at random gains 3 life."}
{:text "Prevent the next 3 damage that would be dealt to a creature or player chosen at random this turn."}
{:text "Destroy a creature or land chosen at random. It can't be regenerated."}
{:text "A player chosen at random puts the top two cards of his or her library into his or her graveyard."}
{:text "Put a 1/1 colorless Insect artifact creature token with flying named Wasp onto the battlefield." :reminder "It can't be blocked except by creatures with flying or reach."}
{:text "Destroy all artifacts, creatures and enchantments."}
{:text "Flip a coin. If you lose the flip, Whimsy deals 5 damage to you. If you win the flip, put a 5/5 colorless Djinn artifact creature token with flying onto the battlefield."}
{:text "Choose a creature card at random from all players' decklists. For each player, flip a coin. If the flip ends up heads, put a token that's a copy of that creature card onto the battlefield under that player's control."}
{:text "A player chosen at random discards a card."}
{:text "Prevent all combat damage that would be dealt this turn."}
{:text "Draw a card and reveal it. If it isn't a land card, discard it."}]}]))
;;-------------------------------------------------
;; helpers
(defn- add-rule-number [card]
(update-in card [:rulelist]
(fn [rules]
(map (fn [index rule]
(assoc rule :number index))
(iterate inc 1)
rules))))
;;-------------------------------------------------
;; interface
(defn get-extra-cards []
(map add-rule-number
(concat [celestine-reef horizon-boughs mirrored-depths tember-city]
[perhaps-youve-met-my-cohort plots-that-span-centuries
your-inescapable-doom imprison-this-insolent-wretch
drench-the-soil-in-their-blood]
dreamcast-cards
astral-cards)))
|
87936
|
(ns loa.cleanup.extra)
;;-------------------------------------------------
;; Planes
(def celestine-reef
{:name "Celestine Reef"
:typelist ["Plane" "Luvion"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Creatures without flying or islandwalk can't attack."}
{:text "Whenever you roll {C}, until a player planeswalks, you can't lose the game and your opponents can't win the game."}]})
(def horizon-boughs
{:name "Horizon Boughs"
:typelist ["Plane" "Pyrulea"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "All permanents untap during each player's untap step."}
{:text "Whenever you roll {C}, you may search your library for up to three basic land cards, put them onto the battlefield tapped, then shuffle your library."}]})
(def mirrored-depths
{:name "Mirrored Depths"
:typelist ["Plane" "Karsus"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Whenever a player casts a spell, that player flips a coin. If he or she loses the flip, counter that spell."}
{:text "Whenever you roll {C}, target player reveals the top card of his or her library. If it's a nonland card, you may cast it without paying its mana cost."}]})
(def tember-city
{:name "Tember City"
:typelist ["Plane" "Kinshala"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Whenever a player taps a land for mana, Tember City deals 1 damage to that player."}
{:text "Whenever you roll {C}, each other player sacrifices a nonland permanent."}]})
;;-------------------------------------------------
;; Schemes
(def perhaps-youve-met-my-cohort
{:name "Perhaps You've Met My Cohort"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, search your library for a planeswalker card, put it onto the battlefield, then shuffle your library."}]})
(def plots-that-span-centuries
{:name "Plots That Span Centuries"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, the next time you would set a scheme in motion, set three schemes in motion instead."}]})
(def your-inescapable-doom
{:name "Your Inescapable Doom"
:typelist ["Ongoing" "Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "At the beginning of your end step, put a doom counter on this scheme, then this scheme deals damage equal to the number of doom counters on it to the opponent with the highest life total among your opponents. If two or more players are tied for highest life total, you choose one."}]})
(def imprison-this-insolent-wretch
{:name "Imprison This Insolent Wretch"
:typelist ["Ongoing" "Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, choose an opponent."}
{:text "Permanents the chosen player controls don't untap during his or her untap step."}
{:text "When the chosen player is attacked or becomes the target of a spell or ability, abandon this scheme."}]})
(def drench-the-soil-in-their-blood
{:name "Drench the Soil in Their Blood"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, after the main phase, there is an additional combat phase followed by an additional main phase. Creatures you control gain vigilance until end of turn."}]})
;;-------------------------------------------------
;; Dreamcast
(def dreamcast-cards
(map
#(assoc % :sets {0 {:set-name "Dreamcast"
:rarity :special}})
[{:name "<NAME>"
:cost "{4}{W}{W}"
:typelist ["Creature" "Angel"]
:pow "4"
:tgh "4"
:rulelist [{:text "Flying"}
{:text "At the beginning of your upkeep, if <NAME> is in your graveyard, choose a number from 1 to 4 at random. If it's 1, you may return <NAME> Angel onto the battlefield."}]}
{:name "<NAME>"
:cost "{1}{R}"
:typelist ["Sorcery"]
:rulelist [{:text "<NAME>'s Breath deals X damage to each creature, where X is a number chosen at random from 0 to 2."}]}
{:name "<NAME>"
:cost "{1}{U}{U}"
:typelist ["Creature" "Merfolk" "Scout"]
:pow "2"
:tgh "3"
:rulelist [{:text "When <NAME> enters the battlefield, it gains landwalk of a basic land type chosen at random."
:reminder "This effect lasts indefinitely."}]}
{:name "<NAME>"
:cost "{2}{B}"
:typelist ["Instant"]
:rulelist [{:text "Target creature gets +X/+0 until end of turn, where X is a number chosen randomly from 0 to 6."}]}
{:name "<NAME>"
:cost "{2}{G}"
:typelist ["Creature" "Human" "Druid"]
:pow "2"
:tgh "2"
:rulelist [{:text "When <NAME> enters the battlefield, for each land, choose a basic land type at random. That land becomes that land type."
:reminder "This effect lasts indefinitely."}]}
{:name "<NAME>"
:cost "{4}{G}"
:typelist ["Creature" "Elephant"]
:pow "*"
:tgh "*"
:rulelist [{:text "Lydari Elephant enters the battlefield as a X/Y creature, where X and Y are numbers randomly chosen from 3 to 7."}]}
{:name "<NAME>"
:cost "{4}{B}{B}"
:typelist ["Enchantment"]
:rulelist [{:text "{3}{B}, Discard a card: Put an X/X black Zombie token onto the battlefield, where X is a number randomly chosen from 2 to 6."}]}
{:name "<NAME>"
:cost "{1}{U}"
:typelist ["Instant"]
:rulelist [{:text "Choose a number from 0 to 5 at random, then choose that many creatures and tap them."}]}
{:name "<NAME>"
:cost "{2}{W}"
:typelist ["Creature" "Human" "Cleric"]
:pow "1"
:tgh "2"
:rulelist [{:text "{T}: Choose a number from 1 to 3 at random. Until end of turn, if a source would deal damage to target creature or player, it deals that much damage minus the chosen number to that creature or player instead."}]}
{:name "<NAME>"
:cost "{5}{R}{R}"
:typelist ["Creature" "Dragon"]
:pow "5"
:tgh "5"
:rulelist [{:text "Flying"}
{:text "Whenever Velican Dragon becomes blocked, it gets +X/+0 until end of turn, where X is a number chosen at random from 0 to 5."}]}
]))
;;-------------------------------------------------
;; Astral
(def astral-cards
(map
#(assoc % :sets {0 {:set-name "Astral"
:rarity :special}})
[{:name "<NAME>"
:cost "{1}{G}{G}"
:typelist ["Creature" "Cat"]
:pow "2"
:tgh "2"
:rulelist [{:text "As <NAME> enters the battlefield, choose a creature type at random from among all creature types that a creature card in target opponent's decklist has."}
{:text "{G}{G}, {T}: Destroy target creature with the chosen type. It can't be regenerated."}]}
{:name "<NAME> the Gr<NAME>"
:cost "{2}{B}"
:typelist ["Sorcery"]
:rulelist [{:text "Choose a player at random. Choose a creature card in that player's graveyard at random and put it onto the battlefield under your control. Call from the Grave deals damage equal to that creature card's converted mana cost to you."}]}
{:name "<NAME>"
:cost "{2}{G}{G}"
:typelist ["Creature" "Dragon"]
:pow "1"
:tgh "3"
:rulelist [{:text "Flying"}
{:text "{1}{G}{G}: Perform a random action from the following list:"}
{:text "A creature chosen at random gains trample and gets +X/+0 until end of turn, where X is its power. At the beginning of the next end step, destroy that creature if it attacked this turn."}
{:text "You may tap or untap an artifact, creature, or land chosen at random."}
{:text "If a creature chosen at random has toughness 5 or greater, it gets +4/-4 until end of turn. Otherwise, it gets +4/-X until end of turn, where X is its toughness minus 1."}
{:text "A spell or permanent chosen at random becomes green." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes white." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes red." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "<NAME> deals 3 damage to a creature or player chosen at random."}
{:text "A creature chosen at random gains flying until end of turn."}
{:text "A creature chosen at random gets +3/+3 until end of turn."}
{:text "A creature chosen at random gains banding until end of turn." :reminder "Any creatures with banding, and up to one without, can attack in a band. Bands are blocked as a group. If any creatures with banding a player controls are blocking or being blocked by a creature, that player divides that creature's combat damage, not its controller, among any of the creatures it's being blocked by or is blocking."}
{:text "A spell or permanent chosen at random becomes black." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes blue." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A creature chosen at random can't be regenerated this turn."}
{:text "If a creature chosen at random has power 2 or less, it is unblockable this turn."}
{:text "A creature chosen at random gets -2/-0 until end of turn."}
{:text "Return a creature chosen at random to its owner's hand."}
{:text "<NAME> deals 1 damage to a creature or player chosen at random."}
{:text "A creature other than <NAME> chosen at random becomes 0/2 until end of turn."}
{:text "Exile a creature chosen at random. Its controller gains life equal to its power."}
{:text "Randomly distribute X -0/-1 counters among a random number of creatures chosen at random."}]}
{:name "Gem <NAME>"
:typelist ["Land"]
:rulelist [{:text "As Gem Bazaar enters the battlefield, choose a color at random."}
{:text "{T}: Add one mana of the last chosen color to your mana pool. Then choose a color at random."}]}
{:name "<NAME>"
:cost "{R}{R}"
:typelist ["Creature" "Goblin"]
:pow "1"
:tgh "1"
:rulelist [{:text "{2}, {T}: Choose any number of target creatures at random. Tap those creatures. Goblins tapped this way do not untap during their controllers' next untap steps. This ability costs R more to activate for each target."}]}
{:name "<NAME>"
:cost "{2}{B}{B}"
:typelist ["Enchantment"]
:rulelist [{:text "Whenever a nonblack creature is put into a graveyard from the battlefield, put a husk counter on Necropolis of Azar."}
{:text "{5}, Remove a husk counter from Necropolis of Azar: Put a X/Y black Spawn creature token named Spawn of Azar with swampwalk onto the battlefield, where X and Y are numbers chosen at random from 1 to 3."}]}
{:name "O<NAME>"
:cost "{X}{R}{R}"
:typelist ["Instant"]
:rulelist [{:text "Randomly distribute X -0/-1 counters among a random number of random target creatures."}]}
{:name "Pandora's Box"
:cost "{5}"
:typelist ["Artifact"]
:rulelist [{:text "{3}, {T}: Choose a creature card at random from all players' decklists. For each player, flip a coin. If the flip ends up heads, put a token that's a copy of that creature card onto the battlefield under that player's control."}]}
{:name "Power Struggle"
:cost "{2}{U}{U}{U}"
:typelist ["Enchantment"]
:rulelist [{:text "At the beginning of each player's upkeep, exchange control of a target artifact, creature or land that player controls, chosen at random, and a random target permanent that shares one of those types with it a player who is his or her opponent chosen at random."}]}
{:name "Prismatic Dragon"
:cost "{2}{W}{W}"
:typelist ["Creature" "Dragon"]
:pow "2"
:tgh "3"
:rulelist [{:text "Flying"}
{:text "At the beginning of your upkeep, Prismatic Dragon becomes a color chosen at random." :reminder "This effect lasts indefinitely."}
{:text "{2}: Prismatic Dragon becomes a color chosen at random." :reminder "This effect lasts indefinitely."}]}
{:name "Rainbow Knights"
:cost "{W}{W}"
:typelist ["Creature" "Human" "Knight"]
:pow "2"
:tgh "1"
:rulelist [{:text "As Rainbow Knights enters the battlefield, it gains protection from a color chosen at random." :reminder "This effect lasts indefinitely."}
{:text "{1}: Rainbow Knights gains first strike until end of turn."}
{:text "{W}{W}: Rainbow Knights gets +X/+0 until end of turn, where X is a number chosen randomly from 0 to 2."}]}
{:name "<NAME>"
:cost "{X}{U}{U}"
:typelist ["Sorcery"]
:rulelist [{:text "Perform X random actions from the following list:"}
{:text "Return a permanent that isn't enchanted chosen at random to its owner's hand."}
{:text "Untap a artifact, creature or land chosen at random."}
{:text "Tap a artifact, creature or land chosen at random."}
{:text "Whimsy deals 4 damage to a creature or player chosen at random."}
{:text "A player chosen at random draws three cards."}
{:text "Destroy an artifact chosen at random. It can't be regenerated. That artifact's controller gains life equal to its converted mana cost."}
{:text "Destroy an artifact or enchantment chosen at random."}
{:text "A player chosen at random gains 3 life."}
{:text "Prevent the next 3 damage that would be dealt to a creature or player chosen at random this turn."}
{:text "Destroy a creature or land chosen at random. It can't be regenerated."}
{:text "A player chosen at random puts the top two cards of his or her library into his or her graveyard."}
{:text "Put a 1/1 colorless Insect artifact creature token with flying named Wasp onto the battlefield." :reminder "It can't be blocked except by creatures with flying or reach."}
{:text "Destroy all artifacts, creatures and enchantments."}
{:text "Flip a coin. If you lose the flip, Whimsy deals 5 damage to you. If you win the flip, put a 5/5 colorless Djinn artifact creature token with flying onto the battlefield."}
{:text "Choose a creature card at random from all players' decklists. For each player, flip a coin. If the flip ends up heads, put a token that's a copy of that creature card onto the battlefield under that player's control."}
{:text "A player chosen at random discards a card."}
{:text "Prevent all combat damage that would be dealt this turn."}
{:text "Draw a card and reveal it. If it isn't a land card, discard it."}]}]))
;;-------------------------------------------------
;; helpers
(defn- add-rule-number [card]
(update-in card [:rulelist]
(fn [rules]
(map (fn [index rule]
(assoc rule :number index))
(iterate inc 1)
rules))))
;;-------------------------------------------------
;; interface
(defn get-extra-cards []
(map add-rule-number
(concat [celestine-reef horizon-boughs mirrored-depths tember-city]
[perhaps-youve-met-my-cohort plots-that-span-centuries
your-inescapable-doom imprison-this-insolent-wretch
drench-the-soil-in-their-blood]
dreamcast-cards
astral-cards)))
| true |
(ns loa.cleanup.extra)
;;-------------------------------------------------
;; Planes
(def celestine-reef
{:name "Celestine Reef"
:typelist ["Plane" "Luvion"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Creatures without flying or islandwalk can't attack."}
{:text "Whenever you roll {C}, until a player planeswalks, you can't lose the game and your opponents can't win the game."}]})
(def horizon-boughs
{:name "Horizon Boughs"
:typelist ["Plane" "Pyrulea"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "All permanents untap during each player's untap step."}
{:text "Whenever you roll {C}, you may search your library for up to three basic land cards, put them onto the battlefield tapped, then shuffle your library."}]})
(def mirrored-depths
{:name "Mirrored Depths"
:typelist ["Plane" "Karsus"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Whenever a player casts a spell, that player flips a coin. If he or she loses the flip, counter that spell."}
{:text "Whenever you roll {C}, target player reveals the top card of his or her library. If it's a nonland card, you may cast it without paying its mana cost."}]})
(def tember-city
{:name "Tember City"
:typelist ["Plane" "Kinshala"]
:sets {0 {:set-name "Planechase"
:rarity :promo}}
:rulelist [{:text "Whenever a player taps a land for mana, Tember City deals 1 damage to that player."}
{:text "Whenever you roll {C}, each other player sacrifices a nonland permanent."}]})
;;-------------------------------------------------
;; Schemes
(def perhaps-youve-met-my-cohort
{:name "Perhaps You've Met My Cohort"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, search your library for a planeswalker card, put it onto the battlefield, then shuffle your library."}]})
(def plots-that-span-centuries
{:name "Plots That Span Centuries"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, the next time you would set a scheme in motion, set three schemes in motion instead."}]})
(def your-inescapable-doom
{:name "Your Inescapable Doom"
:typelist ["Ongoing" "Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "At the beginning of your end step, put a doom counter on this scheme, then this scheme deals damage equal to the number of doom counters on it to the opponent with the highest life total among your opponents. If two or more players are tied for highest life total, you choose one."}]})
(def imprison-this-insolent-wretch
{:name "Imprison This Insolent Wretch"
:typelist ["Ongoing" "Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, choose an opponent."}
{:text "Permanents the chosen player controls don't untap during his or her untap step."}
{:text "When the chosen player is attacked or becomes the target of a spell or ability, abandon this scheme."}]})
(def drench-the-soil-in-their-blood
{:name "Drench the Soil in Their Blood"
:typelist ["Scheme"]
:sets {0 {:set-name "Archenemy"
:rarity :promo}}
:rulelist [{:text "When you set this scheme in motion, after the main phase, there is an additional combat phase followed by an additional main phase. Creatures you control gain vigilance until end of turn."}]})
;;-------------------------------------------------
;; Dreamcast
(def dreamcast-cards
(map
#(assoc % :sets {0 {:set-name "Dreamcast"
:rarity :special}})
[{:name "PI:NAME:<NAME>END_PI"
:cost "{4}{W}{W}"
:typelist ["Creature" "Angel"]
:pow "4"
:tgh "4"
:rulelist [{:text "Flying"}
{:text "At the beginning of your upkeep, if PI:NAME:<NAME>END_PI is in your graveyard, choose a number from 1 to 4 at random. If it's 1, you may return PI:NAME:<NAME>END_PI Angel onto the battlefield."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{1}{R}"
:typelist ["Sorcery"]
:rulelist [{:text "PI:NAME:<NAME>END_PI's Breath deals X damage to each creature, where X is a number chosen at random from 0 to 2."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{1}{U}{U}"
:typelist ["Creature" "Merfolk" "Scout"]
:pow "2"
:tgh "3"
:rulelist [{:text "When PI:NAME:<NAME>END_PI enters the battlefield, it gains landwalk of a basic land type chosen at random."
:reminder "This effect lasts indefinitely."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{2}{B}"
:typelist ["Instant"]
:rulelist [{:text "Target creature gets +X/+0 until end of turn, where X is a number chosen randomly from 0 to 6."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{2}{G}"
:typelist ["Creature" "Human" "Druid"]
:pow "2"
:tgh "2"
:rulelist [{:text "When PI:NAME:<NAME>END_PI enters the battlefield, for each land, choose a basic land type at random. That land becomes that land type."
:reminder "This effect lasts indefinitely."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{4}{G}"
:typelist ["Creature" "Elephant"]
:pow "*"
:tgh "*"
:rulelist [{:text "Lydari Elephant enters the battlefield as a X/Y creature, where X and Y are numbers randomly chosen from 3 to 7."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{4}{B}{B}"
:typelist ["Enchantment"]
:rulelist [{:text "{3}{B}, Discard a card: Put an X/X black Zombie token onto the battlefield, where X is a number randomly chosen from 2 to 6."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{1}{U}"
:typelist ["Instant"]
:rulelist [{:text "Choose a number from 0 to 5 at random, then choose that many creatures and tap them."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{2}{W}"
:typelist ["Creature" "Human" "Cleric"]
:pow "1"
:tgh "2"
:rulelist [{:text "{T}: Choose a number from 1 to 3 at random. Until end of turn, if a source would deal damage to target creature or player, it deals that much damage minus the chosen number to that creature or player instead."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{5}{R}{R}"
:typelist ["Creature" "Dragon"]
:pow "5"
:tgh "5"
:rulelist [{:text "Flying"}
{:text "Whenever Velican Dragon becomes blocked, it gets +X/+0 until end of turn, where X is a number chosen at random from 0 to 5."}]}
]))
;;-------------------------------------------------
;; Astral
(def astral-cards
(map
#(assoc % :sets {0 {:set-name "Astral"
:rarity :special}})
[{:name "PI:NAME:<NAME>END_PI"
:cost "{1}{G}{G}"
:typelist ["Creature" "Cat"]
:pow "2"
:tgh "2"
:rulelist [{:text "As PI:NAME:<NAME>END_PI enters the battlefield, choose a creature type at random from among all creature types that a creature card in target opponent's decklist has."}
{:text "{G}{G}, {T}: Destroy target creature with the chosen type. It can't be regenerated."}]}
{:name "PI:NAME:<NAME>END_PI the GrPI:NAME:<NAME>END_PI"
:cost "{2}{B}"
:typelist ["Sorcery"]
:rulelist [{:text "Choose a player at random. Choose a creature card in that player's graveyard at random and put it onto the battlefield under your control. Call from the Grave deals damage equal to that creature card's converted mana cost to you."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{2}{G}{G}"
:typelist ["Creature" "Dragon"]
:pow "1"
:tgh "3"
:rulelist [{:text "Flying"}
{:text "{1}{G}{G}: Perform a random action from the following list:"}
{:text "A creature chosen at random gains trample and gets +X/+0 until end of turn, where X is its power. At the beginning of the next end step, destroy that creature if it attacked this turn."}
{:text "You may tap or untap an artifact, creature, or land chosen at random."}
{:text "If a creature chosen at random has toughness 5 or greater, it gets +4/-4 until end of turn. Otherwise, it gets +4/-X until end of turn, where X is its toughness minus 1."}
{:text "A spell or permanent chosen at random becomes green." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes white." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes red." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "PI:NAME:<NAME>END_PI deals 3 damage to a creature or player chosen at random."}
{:text "A creature chosen at random gains flying until end of turn."}
{:text "A creature chosen at random gets +3/+3 until end of turn."}
{:text "A creature chosen at random gains banding until end of turn." :reminder "Any creatures with banding, and up to one without, can attack in a band. Bands are blocked as a group. If any creatures with banding a player controls are blocking or being blocked by a creature, that player divides that creature's combat damage, not its controller, among any of the creatures it's being blocked by or is blocking."}
{:text "A spell or permanent chosen at random becomes black." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A spell or permanent chosen at random becomes blue." :reminder "Mana symbols on that permanent remain unchanged."}
{:text "A creature chosen at random can't be regenerated this turn."}
{:text "If a creature chosen at random has power 2 or less, it is unblockable this turn."}
{:text "A creature chosen at random gets -2/-0 until end of turn."}
{:text "Return a creature chosen at random to its owner's hand."}
{:text "PI:NAME:<NAME>END_PI deals 1 damage to a creature or player chosen at random."}
{:text "A creature other than PI:NAME:<NAME>END_PI chosen at random becomes 0/2 until end of turn."}
{:text "Exile a creature chosen at random. Its controller gains life equal to its power."}
{:text "Randomly distribute X -0/-1 counters among a random number of creatures chosen at random."}]}
{:name "Gem PI:NAME:<NAME>END_PI"
:typelist ["Land"]
:rulelist [{:text "As Gem Bazaar enters the battlefield, choose a color at random."}
{:text "{T}: Add one mana of the last chosen color to your mana pool. Then choose a color at random."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{R}{R}"
:typelist ["Creature" "Goblin"]
:pow "1"
:tgh "1"
:rulelist [{:text "{2}, {T}: Choose any number of target creatures at random. Tap those creatures. Goblins tapped this way do not untap during their controllers' next untap steps. This ability costs R more to activate for each target."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{2}{B}{B}"
:typelist ["Enchantment"]
:rulelist [{:text "Whenever a nonblack creature is put into a graveyard from the battlefield, put a husk counter on Necropolis of Azar."}
{:text "{5}, Remove a husk counter from Necropolis of Azar: Put a X/Y black Spawn creature token named Spawn of Azar with swampwalk onto the battlefield, where X and Y are numbers chosen at random from 1 to 3."}]}
{:name "OPI:NAME:<NAME>END_PI"
:cost "{X}{R}{R}"
:typelist ["Instant"]
:rulelist [{:text "Randomly distribute X -0/-1 counters among a random number of random target creatures."}]}
{:name "Pandora's Box"
:cost "{5}"
:typelist ["Artifact"]
:rulelist [{:text "{3}, {T}: Choose a creature card at random from all players' decklists. For each player, flip a coin. If the flip ends up heads, put a token that's a copy of that creature card onto the battlefield under that player's control."}]}
{:name "Power Struggle"
:cost "{2}{U}{U}{U}"
:typelist ["Enchantment"]
:rulelist [{:text "At the beginning of each player's upkeep, exchange control of a target artifact, creature or land that player controls, chosen at random, and a random target permanent that shares one of those types with it a player who is his or her opponent chosen at random."}]}
{:name "Prismatic Dragon"
:cost "{2}{W}{W}"
:typelist ["Creature" "Dragon"]
:pow "2"
:tgh "3"
:rulelist [{:text "Flying"}
{:text "At the beginning of your upkeep, Prismatic Dragon becomes a color chosen at random." :reminder "This effect lasts indefinitely."}
{:text "{2}: Prismatic Dragon becomes a color chosen at random." :reminder "This effect lasts indefinitely."}]}
{:name "Rainbow Knights"
:cost "{W}{W}"
:typelist ["Creature" "Human" "Knight"]
:pow "2"
:tgh "1"
:rulelist [{:text "As Rainbow Knights enters the battlefield, it gains protection from a color chosen at random." :reminder "This effect lasts indefinitely."}
{:text "{1}: Rainbow Knights gains first strike until end of turn."}
{:text "{W}{W}: Rainbow Knights gets +X/+0 until end of turn, where X is a number chosen randomly from 0 to 2."}]}
{:name "PI:NAME:<NAME>END_PI"
:cost "{X}{U}{U}"
:typelist ["Sorcery"]
:rulelist [{:text "Perform X random actions from the following list:"}
{:text "Return a permanent that isn't enchanted chosen at random to its owner's hand."}
{:text "Untap a artifact, creature or land chosen at random."}
{:text "Tap a artifact, creature or land chosen at random."}
{:text "Whimsy deals 4 damage to a creature or player chosen at random."}
{:text "A player chosen at random draws three cards."}
{:text "Destroy an artifact chosen at random. It can't be regenerated. That artifact's controller gains life equal to its converted mana cost."}
{:text "Destroy an artifact or enchantment chosen at random."}
{:text "A player chosen at random gains 3 life."}
{:text "Prevent the next 3 damage that would be dealt to a creature or player chosen at random this turn."}
{:text "Destroy a creature or land chosen at random. It can't be regenerated."}
{:text "A player chosen at random puts the top two cards of his or her library into his or her graveyard."}
{:text "Put a 1/1 colorless Insect artifact creature token with flying named Wasp onto the battlefield." :reminder "It can't be blocked except by creatures with flying or reach."}
{:text "Destroy all artifacts, creatures and enchantments."}
{:text "Flip a coin. If you lose the flip, Whimsy deals 5 damage to you. If you win the flip, put a 5/5 colorless Djinn artifact creature token with flying onto the battlefield."}
{:text "Choose a creature card at random from all players' decklists. For each player, flip a coin. If the flip ends up heads, put a token that's a copy of that creature card onto the battlefield under that player's control."}
{:text "A player chosen at random discards a card."}
{:text "Prevent all combat damage that would be dealt this turn."}
{:text "Draw a card and reveal it. If it isn't a land card, discard it."}]}]))
;;-------------------------------------------------
;; helpers
(defn- add-rule-number [card]
(update-in card [:rulelist]
(fn [rules]
(map (fn [index rule]
(assoc rule :number index))
(iterate inc 1)
rules))))
;;-------------------------------------------------
;; interface
(defn get-extra-cards []
(map add-rule-number
(concat [celestine-reef horizon-boughs mirrored-depths tember-city]
[perhaps-youve-met-my-cohort plots-that-span-centuries
your-inescapable-doom imprison-this-insolent-wretch
drench-the-soil-in-their-blood]
dreamcast-cards
astral-cards)))
|
[
{
"context": ")))\n\n(defn get-bot-username\n []\n (get bot-user :username))\n\n\n;; TODO: Send the list of supported commands ",
"end": 1441,
"score": 0.7813332676887512,
"start": 1433,
"tag": "USERNAME",
"value": "username"
},
{
"context": "t-members-count 2)\n [first-name \"тебе\" \"любых\" \"ответь\"]\n [\"народ\" \"ва",
"end": 13123,
"score": 0.9979138374328613,
"start": 13119,
"tag": "NAME",
"value": "тебе"
},
{
"context": "rs-count 2)\n [first-name \"тебе\" \"любых\" \"ответь\"]\n [\"народ\" \"вам\" \"ваши",
"end": 13131,
"score": 0.9338381886482239,
"start": 13126,
"tag": "NAME",
"value": "любых"
},
{
"context": " 2)\n [first-name \"тебе\" \"любых\" \"ответь\"]\n [\"народ\" \"вам\" \"ваших\" \"ответ",
"end": 13140,
"score": 0.9963765144348145,
"start": 13134,
"tag": "NAME",
"value": "ответь"
},
{
"context": "-fn get-bot-readiness-msg\n :response-params [:bot-username]}\n\n :settings-msg\n {:response-fn get-settin",
"end": 61696,
"score": 0.9914934039115906,
"start": 61684,
"tag": "USERNAME",
"value": "bot-username"
},
{
"context": ")))\n\n(defmethod send! :text\n [token {:keys [chat-id msg-id] :as _ids}\n {:keys [text options] :as _r",
"end": 73079,
"score": 0.5836814045906067,
"start": 73077,
"tag": "KEY",
"value": "id"
},
{
"context": "e? true))))\n\n(defn- delete-text!\n [token {:keys [chat-id msg-id] :as _ids}]\n (if (is-bot-evicted-from-cha",
"end": 78783,
"score": 0.8043001294136047,
"start": 78776,
"tag": "KEY",
"value": "chat-id"
},
{
"context": "-name-request-msg]\n :param-vals {:user user}\n :on-success #(set-bot-msg! chat-id ",
"end": 91511,
"score": 0.7794216275215149,
"start": 91507,
"tag": "USERNAME",
"value": "user"
},
{
"context": "selection-msg]\n :param-vals {:user user\n :selected nil\n ",
"end": 92732,
"score": 0.6937043070793152,
"start": 92728,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ith-account-operation!\n [chat-id {user-id :id :as user}\n bot-msg-type input-name acc-op-fn]\n (let [ch",
"end": 97289,
"score": 0.7221534252166748,
"start": 97285,
"tag": "USERNAME",
"value": "user"
},
{
"context": "edesc-request-msg]\n :param-vals {:user user\n :exp-it-desc (:desc (se",
"end": 102314,
"score": 0.9713965058326721,
"start": 102310,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ecode-request-msg]\n :param-vals {:user user\n :exp-it-desc (:desc (se",
"end": 102953,
"score": 0.956916868686676,
"start": 102949,
"tag": "USERNAME",
"value": "user"
},
{
"context": " [{callback-query-id :id\n {user-id :id :as user} :from\n {msg-id :message_id {chat-id :id} ",
"end": 116483,
"score": 0.5719205737113953,
"start": 116479,
"tag": "USERNAME",
"value": "user"
},
{
"context": " [{callback-query-id :id\n {user-id :id :as user} :from\n {msg-id :message_id {chat-id :id} ",
"end": 125985,
"score": 0.8639412522315979,
"start": 125981,
"tag": "USERNAME",
"value": "user"
},
{
"context": " [{callback-query-id :id\n {user-id :id :as user} :from\n {msg-id :message_id {chat-id :id} ",
"end": 127942,
"score": 0.8249772787094116,
"start": 127938,
"tag": "USERNAME",
"value": "user"
},
{
"context": "t-id :id _type :type chat-title :title _username :username :as chat} :chat\n {_user-id :id first-name ",
"end": 138913,
"score": 0.6918755769729614,
"start": 138905,
"tag": "USERNAME",
"value": "username"
},
{
"context": "st_name _last-name :last_name\n _username :username _is-bot :is_bot _lang :language_code :as _user} :",
"end": 139025,
"score": 0.9893507957458496,
"start": 139017,
"tag": "USERNAME",
"value": "username"
},
{
"context": "_name _last-name :last_name\n _username :username _is-bot :is_bot _lang :language_code :as _user} :",
"end": 140759,
"score": 0.529034435749054,
"start": 140751,
"tag": "USERNAME",
"value": "username"
},
{
"context": " {emoji :emoji} :sticker\n {user-id :id :as user} :from\n {chat-id :id} :chat\n :as me",
"end": 146332,
"score": 0.6430350542068481,
"start": 146328,
"tag": "USERNAME",
"value": "user"
},
{
"context": "-care!\n [{text :text\n {user-id :id :as user} :from\n {chat-id :id} :chat\n :as me",
"end": 147328,
"score": 0.9488369822502136,
"start": 147324,
"tag": "USERNAME",
"value": "user"
},
{
"context": " {emoji :emoji} :sticker\n {user-id :id :as user} :from\n {chat-id :id} :chat\n :as me",
"end": 148360,
"score": 0.9455066323280334,
"start": 148356,
"tag": "USERNAME",
"value": "user"
},
{
"context": " (handle-with-care!\n [{text :text\n {first-name :first_name} :from\n {chat-id :id} :chat\n ",
"end": 150278,
"score": 0.8715610504150391,
"start": 150268,
"tag": "NAME",
"value": "first-name"
},
{
"context": "ith-care!\n [{text :text\n {first-name :first_name} :from\n {chat-id :id} :chat\n :as me",
"end": 150290,
"score": 0.9814446568489075,
"start": 150280,
"tag": "NAME",
"value": "first_name"
},
{
"context": "_name _last-name :last_name\n _username :username _is-bot :is_bot _lang :language_code :as _user} :",
"end": 151572,
"score": 0.9857676029205322,
"start": 151564,
"tag": "USERNAME",
"value": "username"
},
{
"context": "-id :id _type :type _chat-title :title _username :username :as chat} :chat\n _sender-chat :sender_ch",
"end": 151701,
"score": 0.8561350107192993,
"start": 151693,
"tag": "USERNAME",
"value": "username"
}
] |
src/general_expenses_accountant/core.clj
|
marksto/general-expenses-accountant
| 3 |
(ns general-expenses-accountant.core
"Bot API and business logic (core functionality)"
(:require [clojure.set :as set]
[clojure.string :as str]
[clojure.core.async :refer [go chan timeout >! <! close!]]
[morse
[api :as m-api]
[handlers :as m-hlr]]
[mount.core :refer [defstate]]
[slingshot.slingshot :as slingshot]
[taoensso
[encore :as encore]
[timbre :as log]]
[general-expenses-accountant.config :as config]
[general-expenses-accountant.domain.chat :as chats]
[general-expenses-accountant.domain.tlog :as tlogs]
[general-expenses-accountant.md-v2 :as md-v2]
[general-expenses-accountant.tg-bot-api :as tg-api]
[general-expenses-accountant.tg-client :as tg-client]
[general-expenses-accountant.utils.coll :as u-coll]
[general-expenses-accountant.utils.nums :as u-nums])
(:import [java.util Locale]))
;; STATE
(defstate ^:private bot-user
:start (encore/if-let [token (config/get-prop :bot-api-token)
bot-user (tg-client/get-me token)]
(do
(log/debug "Identified myself:" bot-user)
bot-user)
(do
(log/fatal "Unable to identify myself")
(System/exit 3))))
(defn get-bot-username
[]
(get bot-user :username))
;; TODO: Send the list of supported commands w/ 'setMyCommands'.
;; TODO: Normally, this should be transformed into a 'cloffeine' cache
;; which periodically auto-evicts the cast-off chats data. Then,
;; the initial data should be truncated, e.g. by an 'updated_at'
;; timestamps, and the data for chats from the incoming requests
;; should be (re)loaded from the DB on demand.
(defstate ^:private *bot-data
:start (let [chats (chats/select-all)
ids (map :id chats)]
(log/debug "Total chats uploaded from the DB:" (count chats))
(atom (zipmap ids chats))))
(defn- get-bot-data
[]
@*bot-data)
(defn- update-bot-data!
([upd-fn]
(swap! *bot-data upd-fn))
([upd-fn & upd-fn-args]
(apply swap! *bot-data upd-fn upd-fn-args)))
(defn- conditionally-update-bot-data!
([pred upd-fn]
(with-local-vars [succeed true]
(let [updated-bot-data
(update-bot-data!
(fn [bot-data]
(if (pred bot-data)
(upd-fn bot-data)
(do
(var-set succeed false)
bot-data))))]
(when @succeed
updated-bot-data))))
([pred upd-fn & upd-fn-args]
(conditionally-update-bot-data! pred #(apply upd-fn % upd-fn-args))))
;; TODO: Get rid of this atom after debugging is complete. This is not needed for the app.
(defonce ^:private *transactions (atom {}))
(defn- add-transaction!
[new-transaction]
{:pre [(contains? new-transaction :chat-id)]}
(swap! *transactions update (:chat-id new-transaction) conj new-transaction))
;; ACCOUNTING TYPES
;; From the business logic perspective there are 2 main use cases for the bot:
;; 1. personal accounting — when a user creates a group chat for himself
;; and the bot;
;; 2. group accounting — when multiple users create a group chat and add
;; the bot there to track their general expenses.
;; The only difference between the two is that an account of a ':general' type
;; is automatically created for a group accounting and what format is used for
;; new expense notification messages.
(def ^:private min-chat-members-for-group-accounting
"The number of users in a group chat (including the bot itself)
required for it to be used for the general expenses accounting."
3)
;; NB: The approach to the design of the "virtual members" (those who aren't
;; backed with a user but nevertheless occupy a personal account) in the
;; personal accounting case.
;; - Do they count when determining the use case for a chat?
;; At the moment, they DO NOT count. Only real chat members do.
;; - Are they merely different accounts for personal budgeting?
;; This bot was not intended for a full-featured accounting.
(defn- is-chat-for-group-accounting?
"Determines the use case for a chat by the number of its members."
[chat-members-count]
(and (some? chat-members-count) ;; a private chat with the bot
(>= chat-members-count min-chat-members-for-group-accounting)))
;; MESSAGE TEMPLATES & CALLBACK DATA
(def ^:private cd-back "<back>")
(def ^:private cd-undo "<undo>")
(def ^:private cd-done "<done>")
(def ^:private cd-accounts "<accounts>")
(def ^:private cd-accounts-create "<accounts/create>")
(def ^:private cd-accounts-rename "<accounts/rename>")
(def ^:private cd-accounts-revoke "<accounts/revoke>")
(def ^:private cd-accounts-reinstate "<accounts/reinstate>")
(def ^:private cd-expense-items "<expense_items>")
(def ^:private cd-expense-items-create "<expense_items/create>")
(def ^:private cd-expense-items-redesc "<expense_items/redesc>")
(def ^:private cd-expense-items-recode "<expense_items/recode>")
(def ^:private cd-expense-items-delete "<expense_items/delete>")
(def ^:private cd-shares "<shares>")
;; TODO: What about <language_and_currency>?
(def ^:private id-separator "::")
(def ^:private cd-group-chat-prefix (str "gc" id-separator))
(def ^:private cd-expense-item-prefix (str "ei" id-separator))
(def ^:private cd-account-prefix (str "ac" id-separator))
(def ^:private cd-account-type-prefix (str "at" id-separator))
(def ^:private cd-digits-set #{"1" "2" "3" "4" "5" "6" "7" "8" "9" "0" ","})
(def ^:private cd-ar-ops-set #{"+" "–"})
(def ^:private cd-cancel "C")
(def ^:private cd-clear "<-")
(def ^:private cd-enter "OK")
;; TODO: Proper localization (with fn).
(def ^:private back-button-text "<< назад")
(def ^:private undo-button-text "Отмена")
(def ^:private done-button-text "Готово")
(def ^:private unknown-failure-text "Что-то пошло не так.")
(def ^:private default-general-acc-name "общие расходы")
(def ^:private account-types-names {:acc-type/personal {:single "Личный" :plural "Личные"}
:acc-type/group {:single "Групповой" :plural "Групповые"}
:acc-type/general {:single "Общий"}})
(def ^:private select-account-txt "Выберите счёт:")
(def ^:private select-payer-account-txt "Выберите тех, кто понёс расход:")
;; "Error while saving data. Please, try again later." (en)
(def ^:private data-persistence-error "Ошибка при сохранении данных. Пожалуйста, повторите попытку позже.")
(def ^:private no-debtor-account-error "Нет возможности выбрать счёт для данного расхода.")
(def ^:private no-group-to-record-error "Нет возможности выбрать группу для записи расходов.")
(defn- join-into-text
([strings-or-colls]
(join-into-text strings-or-colls "\n\n"))
([strings-or-colls sep]
(str/join sep (flatten strings-or-colls))))
(defn- format-list
([items-coll]
(format-list items-coll nil))
([items-coll {:keys [bullet item-sep text-map-fn escape-md?]
:or {bullet "•"
item-sep "\n"
text-map-fn identity}
:as _?opts}]
(let [list-str (->> items-coll
(map #(str (when (some? bullet)
(str bullet " "))
(text-map-fn %)))
(str/join item-sep))]
(if escape-md? (md-v2/escape list-str) list-str))))
(defn- format-currency
[amount lang]
(String/format (Locale/forLanguageTag lang)
"%.2f" ;; receives BigDecimal
(to-array [(bigdec amount)])))
;; TODO: Use the newly introduced 'placeholder' option.
(def ^:private force-reply-options
(tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup :force-reply {:selective true})
:parse-mode "MarkdownV2"}))
(defn- build-items-selection-markup
[items-buttons ?extra-buttons]
(let [extra-buttons (when (some? ?extra-buttons)
(for [extra-btn ?extra-buttons]
[extra-btn]))
;; NB: A 'vec' is used to keep extra buttons below the regular ones.
all-kbd-btns (into (vec items-buttons) extra-buttons)]
{:reply-markup (tg-api/build-reply-markup :inline-keyboard all-kbd-btns)}))
(defn- get-select-one-item-markup
([items name-extr-fn key-extr-fn val-extr-fn]
(get-select-one-item-markup items name-extr-fn key-extr-fn val-extr-fn nil))
([items name-extr-fn key-extr-fn val-extr-fn ?extra-buttons]
(let [items-btns (for [item items]
[(tg-api/build-inline-kbd-btn (name-extr-fn item)
(key-extr-fn item)
(val-extr-fn item))])]
(build-items-selection-markup items-btns ?extra-buttons))))
(defn- get-select-multiple-items-markup
([selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn]
(get-select-multiple-items-markup selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn nil))
([selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn
?extra-buttons]
(let [sel-items-btns (for [item selected-items]
[(tg-api/build-inline-kbd-btn (str "✔ " (name-extr-fn item))
(key-extr-fn item)
(val-extr-fn item))])
rem-items-btns (for [item remaining-items]
[(tg-api/build-inline-kbd-btn (name-extr-fn item)
(key-extr-fn item)
(val-extr-fn item))])
all-items-btns (concat sel-items-btns rem-items-btns)]
(build-items-selection-markup all-items-btns ?extra-buttons))))
(defn- get-group-ref-option-id
[group-ref]
(str cd-group-chat-prefix (:id group-ref)))
(defn- group-refs->options
[group-refs]
(get-select-one-item-markup group-refs
:title
(constantly :callback-data)
get-group-ref-option-id))
(defn- get-expense-item-display-value
[[code data]]
(str (str/upper-case code) " (" (:desc data) ")"))
(defn- get-expense-item-option-id
[[code _data]]
(str cd-expense-item-prefix code))
(defn- expense-items->options
[expense-items & extra-buttons]
(get-select-one-item-markup (seq expense-items)
get-expense-item-display-value
(constantly :callback-data)
get-expense-item-option-id
extra-buttons))
(defn- get-account-option-id
[acc]
(str cd-account-prefix (name (:type acc)) id-separator (:id acc)))
(defn- accounts->options
[accounts & extra-buttons]
(get-select-one-item-markup accounts
:name
(constantly :callback-data)
get-account-option-id
extra-buttons))
(defn- get-account-type-option-id
[acc-type]
(str cd-account-type-prefix (name acc-type)))
(defn- account-types->options
[account-types & extra-buttons]
(get-select-one-item-markup account-types
#(get-in account-types-names [% :single])
(constantly :callback-data)
get-account-type-option-id
extra-buttons))
(def ^:private back-button
(tg-api/build-inline-kbd-btn back-button-text :callback-data cd-back))
(defn- get-retry-commands-msg
[commands]
{:type :text
:text (format
(str unknown-failure-text " Пожалуйста, повторите %s %s %s.")
(if (next commands) "команды" "команду")
(->> commands
(map (partial str "/"))
(str/join ", "))
(if (next commands) "по-отдельности" "через какое-то время"))})
(def ^:private retry-resend-message-msg
{:type :text
:text (str unknown-failure-text " Пожалуйста, отправьте сообщение снова.")})
(def ^:private retry-callback-query-notification
{:type :callback
:options {:text (str unknown-failure-text " Пожалуйста, повторите действие.")}})
; group chats
; - basic messages
;; TODO: Make messages texts localizable:
;; - take the ':language_code' of the chat initiator (no personal settings)
;; - externalize texts, keep only their keys (to get them via 'l10n')
(defn- get-introduction-msg
[chat-members-count first-name]
{:type :text
:text (apply format "Привет, %s! Я — бот-бухгалтер. И я призван помочь %s с учётом %s общих расходов.\n
Для того, чтобы начать работу, просто %s на следующее сообщение."
(if (= chat-members-count 2)
[first-name "тебе" "любых" "ответь"]
["народ" "вам" "ваших" "ответьте каждый"]))})
(defn- get-personal-account-name-request-msg
[existing-chat? ?chat-members]
{:type :text
:text (let [request-txt (md-v2/escape "как будет называться ваш личный счёт?")
part-one (if (some? ?chat-members)
(let [mentions (for [user ?chat-members]
(tg-api/get-user-mention-text user))]
(str (str/join " " mentions) ", " request-txt))
(str/capitalize request-txt))
part-two (md-v2/escape
(if (and existing-chat? (empty? ?chat-members))
"Пожалуйста, проигнорийруте это сообщение, если у вас уже есть личный счёт в данной группе."
"Пожалуйста, ответьте на данное сообщение."))]
(join-into-text [part-one part-two]))
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:force-reply {:selective (some? ?chat-members)})
:parse-mode "MarkdownV2"})})
(defn- get-personal-accounts-left-msg
[count]
{:type :text
:text (format "Ожидаем остальных... Осталось %s." count)})
(defn- get-bot-readiness-msg
[bot-username]
{:type :text
:text "Я готов к ведению учёта. Давайте же начнём!"
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Перейти в чат для ввода расходов"
:url (str "https://t.me/" bot-username))]])})})
; - settings
(defn- get-settings-msg
[first-time?]
{:type :text
;; TODO: Shorten this text and spread its content between the mgmt views?
:text (format "%s можно настроить, чтобы учитывались:
- счета — не только личные, но и групповые;
- статьи расходов — подходящие по смыслу и удобные вам;
- доли — для статей расходов и ситуаций, когда 50/50 вам не подходит." ;; "По умолчанию равны для любых счетов и статей расходов."
(if (true? first-time?) "Также меня" "Меня"))
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Счета" :callback-data cd-accounts)
(tg-api/build-inline-kbd-btn "Статьи" :callback-data cd-expense-items)
(tg-api/build-inline-kbd-btn "Доли" :callback-data cd-shares)]])})})
(def ^:private successful-changes-msg
{:type :text
:text "Изменения внесены успешно."})
(def ^:private canceled-changes-msg
{:type :text
:text "Внесение изменений отменено."})
; - accounts mgmt
(defn- get-accounts-mgmt-options-msg
[accounts-by-type]
{:type :text
:text (join-into-text
["Список счетов данной группы:"
(map (fn [[acc-type accounts]]
(case acc-type
(:acc-type/personal :acc-type/group)
(str (md-v2/format-bold (get-in account-types-names [acc-type :plural])) "\n"
(format-list accounts {:text-map-fn :name
:escape-md? true}))
:acc-type/general
(md-v2/format-bold "Счёт для общих расходов")))
accounts-by-type)
"Выберите, что вы хотите сделать:"])
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Создать новый" :callback-data cd-accounts-create)]
[(tg-api/build-inline-kbd-btn "Переименовать" :callback-data cd-accounts-rename)]
[(tg-api/build-inline-kbd-btn "Упразднить" :callback-data cd-accounts-revoke)]
[(tg-api/build-inline-kbd-btn "Восстановить" :callback-data cd-accounts-reinstate)]
[back-button]])
:parse-mode "MarkdownV2"})})
(defn- get-account-selection-msg
([accounts txt]
(get-account-selection-msg accounts txt nil))
([accounts txt ?extra-buttons]
{:pre [(seq accounts)]}
{:type :text
:text txt
:options (tg-api/build-message-options
(apply accounts->options accounts ?extra-buttons))}))
(defn- get-account-type-selection-msg
[account-types extra-buttons]
{:pre [(seq account-types)]}
{:type :text
;; Group account is used to share the expenses between the group members.
;; Personal account is needed in case the person is not present in Telegram.
:text (join-into-text
["Какие счета для чего нужны?"
(str (md-v2/format-bold (get-in account-types-names [:acc-type/group :single])) " — "
(md-v2/escape "используется для распределения расходов между членами группы."))
(str (md-v2/format-bold (get-in account-types-names [:acc-type/personal :single])) " — "
(md-v2/escape "используется в случае, если человека нет в Telegram, но учитывать его при расчётах нужно."))
"Выберите тип счёта:"])
:options (tg-api/build-message-options
(merge (apply account-types->options account-types extra-buttons)
{:parse-mode "MarkdownV2"}))})
(defn- get-new-account-name-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", как бы вы хотели назвать новый счёт?"))
:options force-reply-options})
(defn- get-the-account-name-is-already-taken-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", данное имя счёта уже занято. Выберите другое имя."))
:options force-reply-options})
(defn- get-group-members-selection-msg
[user selected remaining]
(let [extra-buttons [(tg-api/build-inline-kbd-btn undo-button-text :callback-data cd-undo)
(tg-api/build-inline-kbd-btn done-button-text :callback-data cd-done)]]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", выберите члена(ов) группы:"))
:options (tg-api/build-message-options
(merge (get-select-multiple-items-markup selected remaining
:name
(constantly :callback-data)
get-account-option-id
extra-buttons)
{:parse-mode "MarkdownV2"}))}))
(defn- get-new-group-members-msg
[acc-names]
{:pre [(seq acc-names)]}
{:type :text
:text (str "Члены новой группы:\n"
(format-list acc-names))})
(def ^:private no-group-members-selected-notification
{:type :callback
:options {:text "Не выбрано ни одного участника группы"}})
(defn- get-account-rename-request-msg
[user acc-name]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", как бы вы хотели переименовать счёт \"" acc-name "\"?")))
:options force-reply-options})
(def ^:private no-eligible-accounts-notification
{:type :callback
:options {:text "Подходящих счетов не найдено"}})
; - expense items mgmt
(defn- get-expense-items-mgmt-options-msg
[expense-items]
(let [expense-items-seq (seq expense-items)]
{:type :text
:text (if expense-items-seq
(join-into-text
["Список статей расходов:"
(format-list expense-items-seq {:text-map-fn get-expense-item-display-value
:escape-md? true})
"Выберите, что вы хотите сделать:"])
(md-v2/escape "Статьи расходов не заданы."))
:options (let [action-btns (cond-> [[(tg-api/build-inline-kbd-btn "Добавить новую" :callback-data cd-expense-items-create)]]
(some? expense-items-seq)
(conj [(tg-api/build-inline-kbd-btn "Изменить описание" :callback-data cd-expense-items-redesc)]
[(tg-api/build-inline-kbd-btn "Изменить код" :callback-data cd-expense-items-recode)]
[(tg-api/build-inline-kbd-btn "Удалить" :callback-data cd-expense-items-delete)]))]
(tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard (conj action-btns [back-button]))
:parse-mode "MarkdownV2"}))}))
(defn- get-new-expense-item-desc-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", как бы вы описали новую статью расходов? Что в неё входит?"))
:options force-reply-options})
(defn- get-new-expense-item-code-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", придумайте кодовое обозначение для данной статью расходов. Это может быть простой текст, например \"пр\" для продуктов, или эмодзи, например ☕️ для еды вне дома."))
:options force-reply-options})
(defn- get-the-expense-item-code-is-already-used-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", данный код уже используется для другой статьи расходов. Выберите другой код."))
:options force-reply-options})
(defn- get-the-expense-item-cannot-be-deleted-msg
[exp-it-code exp-it-desc]
{:type :text
:text (format "Статья расходов \"%s (%s)\" не может быть удалена, поскольку была использована ранее."
exp-it-code exp-it-desc)})
(def ^:private no-eligible-expense-items-notification
{:type :callback
:options {:text "Подходящих статей расходов не найдено"}})
(defn- get-expense-item-redesc-request-msg
[user exp-it-desc]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", как бы вы по-другому описали статью расходов \"" exp-it-desc "\"?")))
:options force-reply-options})
(defn- get-expense-item-recode-request-msg
[user exp-it-desc]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", задайте новый код для статьи расходов \"" exp-it-desc "\".")))
:options force-reply-options})
;; TODO: Add messages for 'shares' here.
; - expenses
(defn- get-new-expense-msg
[expense-amount expense-details payer-acc-name debtor-acc-name]
(let [formatted-amount (format-currency expense-amount "ru")
title-txt (when (some? payer-acc-name)
(str (md-v2/format-bold (md-v2/escape payer-acc-name)) "\n"))
details-txt (->> [(str formatted-amount "₽")
debtor-acc-name
expense-details]
(filter some?)
(str/join " / ")
md-v2/escape)]
{:type :text
:text (str title-txt details-txt)
:options (tg-api/build-message-options
{:parse-mode "MarkdownV2"})}))
; - warnings
(def ^:private waiting-for-user-input-notification
{:type :callback
:options {:text "Ожидание ответа пользователя в чате"}})
(def ^:private waiting-for-other-user-notification
{:type :callback
:options {:text "Ответ ожидается от другого пользователя"}})
(def ^:private message-already-in-use-notification
{:type :callback
:options {:text "С этим сообщением уже взаимодействуют"}})
(def ^:private ignored-callback-query-notification
{:type :callback
:options {:text "Запрос не может быть обработан"}})
; private chats
(defn- get-private-introduction-msg
[first-name]
{:type :text
:text (str "Привет, " first-name "! Чтобы добавить новый расход просто напиши мне сумму.")})
(def ^:private invalid-input-msg
{:type :text
:text "Пожалуйста, введите число. Например, \"145,99\"."})
(def ^:private inline-calculator-markup
(tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "7" :callback-data "7")
(tg-api/build-inline-kbd-btn "8" :callback-data "8")
(tg-api/build-inline-kbd-btn "9" :callback-data "9")
(tg-api/build-inline-kbd-btn "C" :callback-data cd-cancel)]
[(tg-api/build-inline-kbd-btn "4" :callback-data "4")
(tg-api/build-inline-kbd-btn "5" :callback-data "5")
(tg-api/build-inline-kbd-btn "6" :callback-data "6")
(tg-api/build-inline-kbd-btn "+" :callback-data "+")]
[(tg-api/build-inline-kbd-btn "1" :callback-data "1")
(tg-api/build-inline-kbd-btn "2" :callback-data "2")
(tg-api/build-inline-kbd-btn "3" :callback-data "3")
(tg-api/build-inline-kbd-btn "–" :callback-data "–")]
[(tg-api/build-inline-kbd-btn "0" :callback-data "0")
(tg-api/build-inline-kbd-btn "," :callback-data ",")
(tg-api/build-inline-kbd-btn "←" :callback-data cd-clear)
(tg-api/build-inline-kbd-btn "OK" :callback-data cd-enter)]]))
(defn- get-interactive-input-msg
([text]
(get-interactive-input-msg text nil))
([text ?extra-opts]
{:type :text
:text (str (md-v2/escape "Новый расход:\n= ") text)
:options (tg-api/build-message-options
(merge {:parse-mode "MarkdownV2"} ?extra-opts))}))
(defn- get-inline-calculator-msg
[user-input]
(get-interactive-input-msg
(md-v2/escape (str user-input "_"))
{:reply-markup inline-calculator-markup}))
(defn- get-interactive-input-success-msg
[amount]
(get-interactive-input-msg
(md-v2/escape (format-currency amount "ru"))))
(def ^:private interactive-input-disclaimer-msg
{:type :text
:text "Введите /cancel, чтобы выйти из режима калькуляции и ввести данные вручную."})
(def ^:private invalid-input-notification
{:type :callback
:options {:text "Ошибка в выражении! Вычисление невозможно."}})
(defn- get-added-to-new-group-msg
[chat-title]
{:type :text
:text (str "Вас добавили в группу \"" chat-title "\".")})
(defn- get-removed-from-group-msg
[chat-title]
{:type :text
:text (str "Вы покинули группу \"" chat-title "\".")})
(defn- get-group-selection-msg
[group-refs]
{:pre [(seq group-refs)]}
{:type :text
:text "Выберите, к какой группе отнести расход:"
:options (tg-api/build-message-options
(group-refs->options group-refs))})
(defn- get-expense-item-selection-msg
([expense-items]
(get-expense-item-selection-msg expense-items nil))
([expense-items ?extra-buttons]
{:pre [(seq expense-items)]}
{:type :text
:text "Выберите статью расходов:"
:options (tg-api/build-message-options
(apply expense-items->options expense-items ?extra-buttons))}))
(defn- get-expense-manual-description-msg
[user-name]
{:type :text
:text (str user-name ", опишите расход в двух словах:")
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup :force-reply)})})
(def ^:private expense-added-successfully-msg
{:type :text
:text "Запись успешно внесена в ваш гроссбух."})
(defn- get-failed-to-add-new-expense-msg
[reason]
{:type :text
:text (str/join " " ["Не удалось добавить новый расход." reason])})
;; AUXILIARY FUNCTIONS
(defn get-datetime-in-tg-format
[]
(quot (System/currentTimeMillis) 1000))
(defn- is-failure?
"Checks if something resulted in a failure."
[res]
(and (keyword? res)
(= "failure" (namespace res))))
;; - CHATS
(defn- does-chat-exist?
[chat-id]
(contains? (get-bot-data) chat-id))
(def ^:private default-chat-state :initial)
(defn- setup-new-chat!
[chat-id new-chat]
(when-not (does-chat-exist? chat-id) ;; petty RC
(let [new-chat (chats/create! (assoc new-chat :id chat-id))]
(update-bot-data! assoc chat-id new-chat)
new-chat)))
;; TODO: Add a logical ID attr, e.g. UID, to track all group versions.
(defn- setup-new-group-chat!
[chat-id chat-title chat-members-count]
(setup-new-chat! chat-id {:type :chat-type/group
:data {:state default-chat-state
:title chat-title
:members-count chat-members-count
:accounts {:last-id -1}}}))
(defn- setup-new-supergroup-chat!
[chat-id migrate-from-id]
(setup-new-chat! chat-id {:type :chat-type/supergroup
:data migrate-from-id}))
(defn- setup-new-private-chat!
[chat-id group-chat-id]
(setup-new-chat! chat-id {:type :chat-type/private,
:data {:state default-chat-state
:groups #{group-chat-id}}}))
(defn- get-real-chat-id
"Returns the chat 'id' with built-in insurance for the 'supergroup' chats."
([chat-id]
(get-real-chat-id (get-bot-data) chat-id))
([bot-data chat-id]
(let [chat (get bot-data chat-id)]
(if (= :chat-type/supergroup (:type chat))
(:data chat) ;; target group chat-id
chat-id))))
(defn- get-chat-data
"Returns the JSON data associated with a chat with the specified 'chat-id'."
([chat-id]
(get-chat-data (get-bot-data) chat-id))
([bot-data chat-id]
(when-let [real-chat-id (get-real-chat-id bot-data chat-id)]
(get-in bot-data [real-chat-id :data]))))
(defn- -update-chat!
[chat-to-upd]
(if (chats/update! chat-to-upd)
(:data chat-to-upd)
(throw (ex-info "Failed to persist an updated chat" {:chat chat-to-upd}))))
(defn- update-chat-data!
[chat-id upd-fn & upd-fn-args]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
bot-data (apply update-bot-data!
update-in [real-chat-id :data] upd-fn upd-fn-args)
upd-chat (get bot-data real-chat-id)]
(-update-chat! upd-chat)))
(defn- conditionally-update-chat-data!
[chat-id pred upd-fn & upd-fn-args]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
bot-data (apply conditionally-update-bot-data!
#(pred (get-in % [real-chat-id :data]))
update-in [real-chat-id :data] upd-fn upd-fn-args)
upd-chat (get bot-data real-chat-id)]
(when (some? upd-chat)
(-update-chat! upd-chat))))
(defn- assoc-in-chat-data!
[chat-id [key & ks] ?value]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
full-path (concat [real-chat-id :data key] ks)
bot-data (if (nil? ?value)
(update-bot-data! update-in (butlast full-path)
dissoc (last full-path))
(update-bot-data! assoc-in full-path ?value))
upd-chat (get bot-data real-chat-id)]
(-update-chat! upd-chat)))
(defn- get-chat-state
"Determines the state of the given chat. Returns 'nil' in case the group chat
or user is unknown (the input is 'nil') and a valid default in case there is
no preset state.
NB: Be aware that calling this function, e.g. during a state change,
may cause a race condition (RC) and result in an obsolete value."
[chat-data]
(get chat-data :state
(when (some? chat-data) default-chat-state)))
(defn- change-chat-state!
[chat-id chat-type-states new-state]
{:pre [(does-chat-exist? chat-id)]}
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [curr-state (get-chat-state chat-data)
possible-new-states (or (-> chat-type-states curr-state :to)
(-> chat-type-states curr-state))]
(if (contains? possible-new-states new-state)
(let [state-init-fn (-> chat-type-states new-state :init-fn)]
(cond-> chat-data
(some? state-init-fn) (state-init-fn)
:and-most-importantly (assoc :state new-state)))
(do
(log/errorf "Failed to change state to '%s' for chat=%s with current state '%s'"
new-state chat-id curr-state)
chat-data)))))]
(get-chat-state updated-chat-data)))
;; - BOT STATUS
(defn- does-bot-manage-the-chat?
[{?chat-id :chat-id ?chat-state :chat-state}]
{:pre [(or (some? ?chat-id) (some? ?chat-state))]}
(let [chat-state (or ?chat-state
(and (does-chat-exist? ?chat-id)
(get-chat-state (get-chat-data ?chat-id))))]
(= :managed chat-state)))
(defn- is-bot-evicted-from-chat?
[chat-id]
(and (does-chat-exist? chat-id)
(= :evicted (get-chat-state (get-chat-data chat-id)))))
;; - ACCOUNTS
(defn- ->general-account
[id name created members]
{:id id
:type :acc-type/general
:name name
:created created
:members (set members)})
(defn- ->personal-account
[id name created ?user-id ?msg-id]
(cond-> {:id id
:type :acc-type/personal
:name name
:created created}
(some? ?user-id) (assoc :user-id ?user-id)
(some? ?msg-id) (assoc :msg-id ?msg-id)))
(defn- ->group-account
[id name created created-by members]
{:id id
:type :acc-type/group
:name name
:created created
:created-by created-by
:members (set members)})
(defn- is-account-revoked?
[acc]
(contains? acc :revoked))
(defn- is-account-active?
[acc]
(not (is-account-revoked? acc)))
;; - CHATS > ACCOUNTS
(defn- get-members-count
[chat-data]
(:members-count chat-data))
(defn- update-members-count!
[chat-id update-fn]
(update-chat-data! chat-id
update :members-count update-fn))
(defn- get-accounts-of-type
([chat-data acc-type]
(map val (get-in chat-data [:accounts acc-type])))
([chat-data acc-type ?filter-pred]
(cond->> (get-accounts-of-type chat-data acc-type)
(some? ?filter-pred) (filter ?filter-pred))))
(defn- get-account-by-id
[chat-data acc-type acc-id]
(get-in chat-data [:accounts acc-type acc-id]))
(defn- get-accounts-next-id
[chat-data]
(-> chat-data :accounts :last-id inc))
(defn- find-account-by-name
[chat-data acc-type acc-name]
;; NB: Personal and group account names must be unique.
(first (get-accounts-of-type chat-data acc-type
#(= (:name %) acc-name))))
(defn- create-named-account!
"Attempts to create a named type account with a name uniqueness check."
[chat-id acc-type acc-name constructor-fn]
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-account-by-name % acc-type acc-name))
(fn [chat-data]
(let [next-id (get-accounts-next-id chat-data)
upd-accounts-next-id #(assoc-in % [:accounts :last-id] next-id)]
(constructor-fn (upd-accounts-next-id chat-data) next-id))))]
(if (some? updated-chat-data)
(find-account-by-name updated-chat-data acc-type acc-name)
:failure/the-account-name-is-already-taken)))
;; - CHATS > ACCOUNTS > GENERAL
(defn- get-current-general-account
"Retrieves the current (the one that will be used) account of 'general' type
from the provided chat data.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact '?filter-pred'.
In the latter case, the most recent general account will be returned."
([chat-data]
(get-current-general-account chat-data is-account-active?))
([chat-data ?filter-pred]
(let [gen-accs (get-accounts-of-type chat-data
:acc-type/general
?filter-pred)]
(if (< 1 (count gen-accs))
(do
(log/warnf "There is more than 1 suitable general account in chat=%s"
(:id chat-data)) ;; it might be ok for custom 'filter-pred'
(apply max-key :id gen-accs))
(first gen-accs)))))
(defn- create-general-account!
[chat-id created-dt & {:keys [remove-member add-member] :as _opts}]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [old-gen-acc (get-current-general-account chat-data)
old-members (->> (get-accounts-of-type chat-data
:acc-type/personal
is-account-active?)
(map :id)
set)
new-members (cond-> old-members
(some? add-member) (conj add-member)
(some? remove-member) (disj remove-member))
upd-old-general-acc-fn
(fn [cd]
(if (some? old-gen-acc)
(assoc-in cd
[:accounts :acc-type/general (:id old-gen-acc) :revoked]
created-dt)
cd))
add-new-general-acc-fn
(fn [cd]
;; IMPLEMENTATION NOTE:
;; Here the chat 'members-count' have to already be updated!
(if (is-chat-for-group-accounting? (get-members-count cd))
(let [next-id (get-accounts-next-id cd)
acc-name (:name old-gen-acc default-general-acc-name)
new-general-acc (->general-account
next-id acc-name created-dt new-members)]
(-> cd
(assoc-in [:accounts :last-id] next-id)
(assoc-in [:accounts :acc-type/general next-id] new-general-acc)))
cd))]
(-> chat-data
upd-old-general-acc-fn
add-new-general-acc-fn))))]
(get-current-general-account updated-chat-data)))
;; - CHATS > ACCOUNTS > PERSONAL
(defn- get-personal-account-id
"A convenient way to get both user and virtual accounts ID."
[chat-data {?user-id :user-id ?acc-name :name :as _ids}]
{:pre [(or (some? ?user-id) (some? ?acc-name))]}
(if (some? ?user-id)
(get-in chat-data [:user-account-mapping ?user-id])
(:id (find-account-by-name chat-data :acc-type/personal ?acc-name))))
(defn- set-personal-account-id
[chat-data user-id pers-acc-id]
{:pre [(some? user-id)]}
(assoc-in chat-data [:user-account-mapping user-id] pers-acc-id))
(defn- get-personal-account
[chat-data {?user-id :user-id ?acc-name :name ?acc-id :id :as ids}]
{:pre [(or (some? ?user-id) (some? ?acc-name) (some? ?acc-id))]}
(cond
(some? ?acc-id)
(get-account-by-id chat-data :acc-type/personal ?acc-id)
(some? ?acc-name)
(find-account-by-name chat-data :acc-type/personal ?acc-name)
(some? ?user-id)
(let [pers-acc-id (get-personal-account-id chat-data ids)]
(get-account-by-id chat-data :acc-type/personal pers-acc-id))))
(defn- create-personal-account!
[chat-id acc-name created-dt & {?user-id :user-id ?first-msg-id :first-msg-id :as _opts}]
(if (or (nil? ?user-id)
(let [pers-acc (get-personal-account (get-chat-data chat-id) {:user-id ?user-id})] ;; petty RC
(or (nil? pers-acc) (is-account-revoked? pers-acc))))
(create-named-account!
chat-id :acc-type/personal acc-name
(fn [chat-data acc-id]
(let [pers-acc (->personal-account acc-id acc-name created-dt
?user-id ?first-msg-id)]
(cond-> (assoc-in chat-data [:accounts :acc-type/personal acc-id] pers-acc)
(some? ?user-id) (set-personal-account-id ?user-id acc-id)))))
:failure/user-already-has-an-active-account))
;; - CHATS > ACCOUNTS > GROUP
(defn- get-group-account
[chat-data {?acc-name :name ?acc-id :id :as _ids}]
{:pre [(or (some? ?acc-name) (some? ?acc-id))]}
(cond
(some? ?acc-id)
(get-account-by-id chat-data :acc-type/group ?acc-id)
(some? ?acc-name)
(find-account-by-name chat-data :acc-type/group ?acc-name)))
(defn- create-group-account!
[chat-id acc-name created-dt created-by members-ids]
(create-named-account!
chat-id :acc-type/group acc-name
(fn [chat-data acc-id]
(let [group-acc (->group-account acc-id acc-name created-dt created-by members-ids)]
(assoc-in chat-data [:accounts :acc-type/group acc-id] group-acc)))))
;; - CHATS > BOT MESSAGES
(defn- get-bot-msg
[chat-data msg-id]
(get-in chat-data [:bot-messages msg-id]))
(defn- set-bot-msg!
[chat-id msg-id {:keys [type] :as ?props}]
{:pre [(or (nil? ?props) (some? type))]}
(assoc-in-chat-data! chat-id [:bot-messages msg-id] ?props))
(defn- find-bot-messages
[chat-data {:keys [type to-user] :as _props}]
(cond->> (:bot-messages chat-data)
(some? type) (filter #(= type (-> % val :type)))
(some? to-user) (filter #(= to-user (-> % val :to-user)))))
(defn- drop-bot-msg!
[chat-id {:keys [type to-user] :as props}]
{:pre [(or (some? type) (some? to-user))]}
(let [to-drop (map key (find-bot-messages (get-chat-data chat-id) props))]
(update-chat-data! chat-id
update-in [:bot-messages] #(apply dissoc % to-drop))
to-drop))
(defn- get-original-bot-msg
[chat-id reply-msg]
;; NB: There's always only one original msg.
(->> (:bot-messages (get-chat-data chat-id))
(filter #(tg-api/is-reply-to? (key %) reply-msg))
(map (fn [[k v]] (assoc v :msg-id k)))
first))
(defn- check-bot-msg
[bot-msg {:keys [type to-user] :as props}]
{:pre [(or (some? type) (some? to-user))]}
(when (some? bot-msg)
(every? #(= (val %) (-> % key bot-msg)) props)))
(defn- change-bot-msg-state!
[chat-id msg-id msg-type-states new-state]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [bot-msg (get-bot-msg chat-data msg-id)
curr-state (:state bot-msg)]
(if (or (nil? curr-state) ;; to set an initial state
(contains? (get msg-type-states curr-state) new-state))
(assoc-in chat-data [:bot-messages msg-id :state] new-state)
(do
(log/errorf "Failed to change state from '%s' to '%s' for message=%s in chat=%s"
curr-state new-state msg-id chat-id)
chat-data)))))]
(:state (get-bot-msg updated-chat-data msg-id))))
;; - CHATS > GROUP CHAT
(defn- get-chat-title
[chat-data]
(:title chat-data))
(defn- set-chat-title!
[chat-id chat-title]
(assoc-in-chat-data! chat-id [:title] chat-title))
;; - CHATS > GROUP CHAT > EXPENSE ITEMS
;; TODO: Optionally sort them according popularity.
(defn- get-group-chat-expense-items
[chat-data]
(:expense-items chat-data))
(defn- find-expense-item
[chat-data exp-it-code]
(get (get-group-chat-expense-items chat-data) exp-it-code))
(defn- create-group-chat-expense-item!
[chat-id {:keys [exp-it-code exp-it-data]}]
{:pre [(some? exp-it-code) (some? exp-it-data)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-expense-item % exp-it-code))
#(assoc-in % [:expense-items exp-it-code] exp-it-data))]
(if (some? updated-chat-data)
(find-expense-item updated-chat-data exp-it-code)
:failure/the-expense-item-code-is-already-used)))
(defn- update-group-chat-expense-item!
[chat-id {:keys [exp-it-code exp-it-data]}]
{:pre [(some? exp-it-code) (some? exp-it-data)]}
(let [updated-chat-data
(update-chat-data!
chat-id
update-in [:expense-items exp-it-code] merge exp-it-data)]
(find-expense-item updated-chat-data exp-it-code)))
(defn- change-group-chat-expense-item-code!
[chat-id {:keys [exp-it-code new-exp-it-code]}]
{:pre [(some? exp-it-code) (some? new-exp-it-code)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-expense-item % new-exp-it-code))
(fn [chat-data]
(-> chat-data
(update :expense-items dissoc exp-it-code)
(assoc-in [:expense-items new-exp-it-code]
(get-in chat-data [:expense-items exp-it-code])))))]
(if (some? updated-chat-data)
(find-expense-item updated-chat-data new-exp-it-code)
:failure/the-expense-item-code-is-already-used)))
(defn- can-expense-item-be-deleted?
[[_code data]]
(not (and (contains? data :pops)
(< 0 (:pops data)))))
(defn- delete-group-chat-expense-item!
[chat-id exp-it-to-delete]
{:pre [(some? exp-it-to-delete)]}
(let [exp-it-code (first exp-it-to-delete)
updated-chat-data
(conditionally-update-chat-data!
chat-id
#(let [exp-it (find-expense-item % exp-it-code)]
(can-expense-item-be-deleted? [exp-it-code exp-it]))
#(update % :expense-items dissoc exp-it-code))]
(if (some? updated-chat-data)
true
:failure/the-expense-item-cannot-be-deleted)))
(defn- data->expense-item
"Retrieves a group chat's expense item by parsing the callback button data."
[callback-btn-data chat-data]
(let [exp-it-code (str/replace-first callback-btn-data cd-expense-item-prefix "")]
[exp-it-code (find-expense-item chat-data exp-it-code)]))
;; - CHATS > GROUP CHAT > ACCOUNTS
(def ^:private all-account-types
[:acc-type/personal :acc-type/group :acc-type/general])
(defn- get-group-chat-accounts
"Retrieves accounts of all or specific types (if the 'acc-types' is present)
for a group chat with the specified 'chat-id'.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact 'filter-pred'."
;; TODO: Sort them according popularity.
([chat-id]
(get-group-chat-accounts chat-id
{:acc-types all-account-types}))
([chat-id {:keys [acc-types filter-pred sort-by-popularity]
:or {acc-types all-account-types
filter-pred is-account-active?}}]
(if (< 1 (count acc-types))
;; multiple types
(->> acc-types
(mapcat #(get-group-chat-accounts chat-id
{:acc-types [%]
:filter-pred filter-pred})))
;; single type
(when-let [chat-data (get-chat-data chat-id)]
(get-accounts-of-type chat-data (first acc-types) filter-pred)))))
(defn- get-group-chat-accounts-by-type
"Retrieves accounts, grouped in a map by account type, for a group chat with
the specified 'chat-id'.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact '?filter-pred'."
([chat-id]
(get-group-chat-accounts-by-type chat-id is-account-active?))
([chat-id ?filter-pred]
(group-by :type
(get-group-chat-accounts chat-id
{:acc-types all-account-types
:filter-pred ?filter-pred}))))
(defn- is-not-virtual-member?
[acc]
(and (is-account-active? acc)
(some? (:user-id acc))))
(defn- get-number-of-missing-personal-accounts
"Returns the number of missing personal accounts in a group chat,
which have to be created before the group chat is ready for the
expenses accounting."
[chat-id]
(let [chat-members-count (get-members-count (get-chat-data chat-id))
existing-pers-accs (->> {:acc-types [:acc-type/personal]
:filter-pred is-not-virtual-member?}
(get-group-chat-accounts chat-id)
count)]
(- chat-members-count existing-pers-accs 1)))
(defn- is-group-acc-member?
[chat-id group-acc user-id]
(let [chat-data (get-chat-data chat-id)
pers-acc-id (get-personal-account-id chat-data {:user-id user-id})
group-acc-members (:members group-acc)]
(contains? group-acc-members pers-acc-id)))
(defn- all-group-acc-members-are-inactive?
[chat-id group-acc]
(let [group-acc-members (:members group-acc)]
(->> {:acc-types [:acc-type/personal]
:filter-pred #(and (is-account-active? %)
(contains? group-acc-members (:id %)))}
(get-group-chat-accounts chat-id)
empty?)))
(defn- can-rename-account?
[chat-id user-id]
(fn [acc]
(and (is-account-active? acc)
(or (and (= :acc-type/personal (:type acc))
(contains? #{user-id nil} (:user-id acc)))
(and (= :acc-type/group (:type acc))
(or (= (:created-by acc) user-id)
(is-group-acc-member? chat-id acc user-id)
(all-group-acc-members-are-inactive? chat-id acc)))))))
(defn- can-revoke-account?
[chat-id user-id]
(fn [acc]
(and (is-account-active? acc)
(or (and (= :acc-type/personal (:type acc))
(not= (:user-id acc) user-id))
(and (= :acc-type/group (:type acc))
(or (= (:created-by acc) user-id)
(is-group-acc-member? chat-id acc user-id)
(all-group-acc-members-are-inactive? chat-id acc)))))))
(defn- can-reinstate-account?
[_chat-id _user-id]
(fn [acc]
(is-account-revoked? acc)))
(defn- get-group-chat-account
[chat-data {acc-type :type :as props}]
(case acc-type
:acc-type/personal
(get-personal-account chat-data props)
:acc-type/group
(get-group-account chat-data props)
:acc-type/general
(get-current-general-account chat-data)))
(defn- is-group-chat-eligible-for-selection?
"Checks the ability of a specified user to select a given group chat."
[chat-id user-id]
(let [chat-data (get-chat-data chat-id)
pers-acc (get-group-chat-account chat-data {:type :acc-type/personal
:user-id user-id})]
(is-account-active? pers-acc)))
(defn- data->account
"Retrieves a group chat's account by parsing the callback button data."
[callback-btn-data chat-data]
(let [account (str/replace-first callback-btn-data cd-account-prefix "")
account-path (str/split account (re-pattern id-separator))]
(get-group-chat-account chat-data
{:type (keyword "acc-type" (nth account-path 0))
:id (u-nums/parse-int (nth account-path 1))})))
(defn- create-group-chat-account!
[chat-id {:keys [acc-type acc-name created-dt created-by members]}]
{:pre [(some? acc-type) (some? acc-name) (some? created-dt)]}
(case acc-type
:acc-type/personal (when-some [pers-acc (create-personal-account! chat-id acc-name created-dt)]
(create-general-account! chat-id created-dt)
pers-acc)
:acc-type/group (let [members-ids (map :id members)]
(create-group-account! chat-id acc-name created-dt created-by members-ids))))
(defn- change-group-chat-account-name!
[chat-id {:keys [acc-type acc-id new-acc-name]}]
{:pre [(some? acc-type) (some? acc-id) (some? new-acc-name)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-account-by-name % acc-type new-acc-name))
assoc-in [:accounts acc-type acc-id :name] new-acc-name)]
(if (some? updated-chat-data)
(get-group-chat-account updated-chat-data {:type acc-type
:id acc-id})
:failure/the-account-name-is-already-taken)))
(defn- change-account-activity-status!
"Changes the activity status of a personal or group account (just marks it as
'revoked' or removes this mark) and, for personal accounts only, updates the
general account (revokes an existing and creates a new version, if needed)."
[chat-id acc {:keys [revoke? reinstate? datetime] :as _activity_status_upd}]
{:pre [(or (some? revoke?) (some? reinstate?))
(not (and (some? revoke?) (some? reinstate?)))
(contains? #{:acc-type/personal :acc-type/group} (:type acc))]}
(let [acc-id (:id acc)
acc-type (:type acc)
updated-chat-data
(conditionally-update-chat-data!
chat-id
#(some? (get-account-by-id % acc-type acc-id))
(fn [chat-data]
(cond-> chat-data
(true? revoke?)
(assoc-in [:accounts acc-type acc-id :revoked] datetime)
(true? reinstate?)
(update-in [:accounts acc-type acc-id] dissoc :revoked))))]
(when (= :acc-type/personal (:type acc))
(let [member-action (cond
(true? revoke?) :remove-member
(true? reinstate?) :add-member)]
(create-general-account! chat-id datetime member-action acc-id)))
(get-account-by-id updated-chat-data acc-type acc-id)))
;; - CHATS > GROUP CHAT > USER INPUT
(defn- get-user-input-data
[chat-data user-id input-name]
(get-in chat-data [:input user-id input-name]))
(defn- set-user-input-data!
[chat-id user-id input-name ?input-data]
(if (nil? ?input-data)
(update-chat-data! chat-id
update-in [:input user-id] dissoc input-name)
(update-chat-data! chat-id
assoc-in [:input user-id input-name] ?input-data)))
(defn- drop-user-input-data!
[chat-id user-id]
(update-chat-data! chat-id
update-in [:input] dissoc user-id))
(defn- clean-up-chat-data!
[chat-id {:keys [bot-messages input]}]
(doseq [bot-msg bot-messages]
(drop-bot-msg! chat-id bot-msg))
(doseq [user-input input]
(if (contains? user-input :name)
(set-user-input-data! chat-id (:user user-input) (:name user-input) nil)
(drop-user-input-data! chat-id (:user user-input)))))
(defn- release-message-lock!
"Releases the \"input lock\" acquired by the user for the message in chat."
[chat-id user-id msg-id]
(update-chat-data!
chat-id
(fn [chat-data]
(let [user-locked (get-user-input-data chat-data user-id :locked-messages)]
(if (contains? user-locked msg-id)
(update-in chat-data [:input user-id :locked-messages] set/difference #{msg-id})
chat-data))))
nil)
(defn- acquire-message-lock!
"Acquires an \"input lock\" for a specific message in chat and the specified
user, but only if the message has not yet been locked by another user.
IMPLEMENTATION NOTE:
The chat data stores IDs of all locked message for each member in ':input',
so that none of the users can intercept the input of another and interfere
with it. These locks are time-limited — to protect against forgetful users'
inactivity.
Moreover, since the user-specific input data is auto-erased when the user
leaves/is removed from the chat, these message locks will also be released
automatically, and immediately."
[chat-id user-id msg-id]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [all-locked (->> (vals (:input chat-data))
(map :locked-messages)
(reduce #(set/union %1 %2) #{}))
user-locked (get-user-input-data chat-data user-id :locked-messages)]
(if (or (not (contains? all-locked msg-id))
(contains? user-locked msg-id))
(update-in chat-data [:input user-id :locked-messages] set/union #{msg-id})
chat-data))))
user-locked (get-user-input-data updated-chat-data user-id :locked-messages)
has-message-lock? (contains? user-locked msg-id)]
(when has-message-lock?
(go
(<! (timeout (* 5 60 1000))) ;; after 5 minutes
(release-message-lock! chat-id user-id msg-id)))
has-message-lock?))
;; - CHATS > PRIVATE CHAT
(defn- can-write-to-user?
[user-id]
(let [chat-state (-> user-id get-chat-data get-chat-state)]
(and (some? chat-state)
(not= default-chat-state chat-state))))
(defn- get-private-chat-groups
[chat-data]
(get chat-data :groups))
;; NB: This is a design decision to only accumulate groups and not delete them.
(defn- update-private-chat-groups!
([chat-id new-group-chat-id]
(let [updated-chat-data
(update-chat-data! chat-id
update :groups conj new-group-chat-id)]
(get-private-chat-groups updated-chat-data)))
([chat-id old-group-chat-id new-group-chat-id]
(let [swap-ids-fn
(comp set (partial replace {old-group-chat-id new-group-chat-id}))
updated-chat-data (update-chat-data! chat-id
update :groups swap-ids-fn)]
(get-private-chat-groups updated-chat-data))))
(defn- ->group-ref
[group-chat-id group-chat-title]
{:id group-chat-id
:title group-chat-title})
;; - CHATS > PRIVATE CHAT > USER INPUT
(defn- get-user-input
[chat-data]
(get chat-data :user-input))
(defn- update-user-input!
[chat-id {:keys [type data] :as _operation}]
(let [append-digit
(fn [old-val]
(if (or (nil? old-val)
(empty? old-val))
(when (not= "0" data) data)
(str (or old-val "") data)))
append-ar-op
(fn [old-val]
(if (or (nil? old-val)
(empty? old-val))
old-val ;; do not allow
(let [last-char (-> old-val
str/trim
last
str)]
(if (contains? cd-ar-ops-set
last-char)
old-val ;; do not allow
(str (or old-val "")
" " data " ")))))
cancel
(fn [old-val]
(let [trimmed (str/trim old-val)]
(if (< 0 (count trimmed))
(-> trimmed
(subs 0 (dec (count trimmed)))
str/trim)
trimmed)))
clear
(constantly nil)
updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [old-val (get chat-data :user-input)
new-val ((case type
:append-digit append-digit
:append-ar-op append-ar-op
:cancel cancel
:clear clear) old-val)]
(assoc chat-data :user-input new-val))))]
(get-user-input updated-chat-data)))
;; - CHATS > SUPERGROUP CHAT
(defn- migrate-group-chat-to-supergroup!
[chat-id migrate-to-chat-id]
(let [new-chat (setup-new-supergroup-chat! migrate-to-chat-id chat-id)
chat-data (if (some? new-chat)
(:data new-chat)
(get-chat-data chat-id))
group-users (-> chat-data
(get :user-account-mapping)
keys)]
;; NB: Here we iterate only real users, and this is exactly what we need.
(doseq [user-id group-users]
(update-private-chat-groups! user-id chat-id migrate-to-chat-id))))
;; RESPONSES
(def ^:private responses
{:chat-type/group
{:introduction-msg
{:response-fn get-introduction-msg
:response-params [:chat-members-count :first-name]}
:personal-account-name-request-msg
{:response-fn get-personal-account-name-request-msg
:response-params [:existing-chat? :chat-members]}
:personal-accounts-left-msg
{:response-fn get-personal-accounts-left-msg
:response-params [:count]}
:bot-readiness-msg
{:response-fn get-bot-readiness-msg
:response-params [:bot-username]}
:settings-msg
{:response-fn get-settings-msg
:response-params [:first-time?]}
:new-account-name-request-msg
{:response-fn get-new-account-name-request-msg
:response-params [:user]}
:the-account-name-is-already-taken-msg
{:response-fn get-the-account-name-is-already-taken-msg
:response-params [:user]}
:group-members-selection-msg
{:response-fn get-group-members-selection-msg
:response-params [:user :selected :remaining]}
:new-group-members-msg
{:response-fn get-new-group-members-msg
:response-params [:acc-names]}
:account-rename-request-msg
{:response-fn get-account-rename-request-msg
:response-params [:user :acc-name]}
:new-expense-item-desc-request-msg
{:response-fn get-new-expense-item-desc-request-msg
:response-params [:user]}
:new-expense-item-code-request-msg
{:response-fn get-new-expense-item-code-request-msg
:response-params [:user]}
:the-expense-item-code-is-already-used-msg
{:response-fn get-the-expense-item-code-is-already-used-msg
:response-params [:user]}
:the-expense-item-cannot-be-deleted-msg
{:response-fn get-the-expense-item-cannot-be-deleted-msg
:response-params [:exp-it-code :exp-it-desc]}
:expense-item-redesc-request-msg
{:response-fn get-expense-item-redesc-request-msg
:response-params [:user :exp-it-desc]}
:expense-item-recode-request-msg
{:response-fn get-expense-item-recode-request-msg
:response-params [:user :exp-it-desc]}
:successful-changes-msg
{:response-fn (constantly successful-changes-msg)}
:canceled-changes-msg
{:response-fn (constantly canceled-changes-msg)}
:waiting-for-user-input-notification
{:response-fn (constantly waiting-for-user-input-notification)}
:waiting-for-other-user-notification
{:response-fn (constantly waiting-for-other-user-notification)}
:message-already-in-use-notification
{:response-fn (constantly message-already-in-use-notification)}
:no-eligible-accounts-notification
{:response-fn (constantly no-eligible-accounts-notification)}
:no-group-members-selected-notification
{:response-fn (constantly no-group-members-selected-notification)}
:no-eligible-expense-items-notification
{:response-fn (constantly no-eligible-expense-items-notification)}
; message-specific
:settings
{:accounts-mgmt-options-msg
{:response-fn get-accounts-mgmt-options-msg
:response-params [:accounts-by-type]}
:account-type-selection-msg
{:response-fn get-account-type-selection-msg
:response-params [:account-types :extra-buttons]}
:account-selection-msg
{:response-fn get-account-selection-msg
:response-params [:accounts :txt :extra-buttons]}
:expense-items-mgmt-options-msg
{:response-fn get-expense-items-mgmt-options-msg
:response-params [:expense-items]}
:expense-item-selection-msg
{:response-fn get-expense-item-selection-msg
:response-params [:expense-items :extra-buttons]}
:restored-settings-msg
{:response-fn (partial get-settings-msg false)}}}
:chat-type/private
{:private-introduction-msg
{:response-fn get-private-introduction-msg
:response-params [:first-name]}
:inline-calculator-msg
{:response-fn get-inline-calculator-msg
:response-params [:new-user-input]}
:interactive-input-success-msg
{:response-fn get-interactive-input-success-msg
:response-params [:parsed-val]}
:interactive-input-disclaimer-msg
{:response-fn (constantly interactive-input-disclaimer-msg)}
:invalid-input-msg
{:response-fn (constantly invalid-input-msg)}
:group-selection-msg
{:response-fn get-group-selection-msg
:response-params [:group-refs]}
:expense-item-selection-msg
{:response-fn get-expense-item-selection-msg
:response-params [:expense-items]}
:expense-manual-description-msg
{:response-fn get-expense-manual-description-msg
:response-params [:first-name]}
:account-selection-msg
{:response-fn get-account-selection-msg
:response-params [:accounts :txt]}
:new-expense-msg
{:response-fn get-new-expense-msg
:response-params [:expense-amount :expense-details
:payer-acc-name :debtor-acc-name]}
:added-to-new-group-msg
{:response-fn get-added-to-new-group-msg
:response-params [:chat-title]}
:removed-from-group-msg
{:response-fn get-removed-from-group-msg
:response-params [:chat-title]}
:invalid-input-notification
{:response-fn (constantly invalid-input-notification)}
:expense-added-successfully-msg
{:response-fn (constantly expense-added-successfully-msg)}
:failed-to-add-new-expense-msg
{:response-fn get-failed-to-add-new-expense-msg
:response-params [:reason]}}})
;; STATES & STATE TRANSITIONS
;; TODO: Re-write with an existing state machine (FSM) library.
(defn- to-response
[{:keys [response-fn response-params]} ?param-vals]
(when (some? response-fn)
(apply response-fn (map (or ?param-vals {}) response-params))))
(defn- handle-state-transition!
[event state-transitions change-state-fn]
(let [transition-keys (:transition event)
transition (get-in state-transitions transition-keys)
chat-type (first transition-keys)
response-keys (u-coll/collect [chat-type] (:response transition))
response-data (get-in responses response-keys)]
(change-state-fn (:to-state transition))
(to-response response-data (:param-vals event))))
; chat states
;; TODO: There is a serious issue of a chat transition happening right before the exception happens.
;; Both private chats state and group chats' message state are vulnerable to this.
;; Solution: surround all update handlers with transaction boundaries.
(def ^:private group-chat-states
{:initial #{:managed
:evicted}
:managed #{:managed
:evicted}
:evicted #{:managed}})
(def ^:private private-chat-states
{:initial #{:input}
:input {:to #{:group-selection
:expense-detailing
:interactive-input
:input}
:init-fn (fn [chat-data]
(select-keys chat-data [:groups]))}
:interactive-input #{:group-selection
:expense-detailing
:input}
:group-selection #{:expense-detailing
:input}
:expense-detailing #{:account-selection
:input}
:account-selection #{:input}})
(def ^:private chat-state-transitions
{:chat-type/group
{:mark-managed
{:to-state :managed
:response :bot-readiness-msg}
:mark-evicted
{:to-state :evicted}}
:chat-type/private
{:request-amount
{:to-state :input
:response :private-introduction-msg}
:show-calculator
{:to-state :interactive-input
:response :inline-calculator-msg}
:select-group
{:to-state :group-selection
:response :group-selection-msg}
:select-expense-item
{:to-state :expense-detailing
:response :expense-item-selection-msg}
:request-expense-desc
{:to-state :expense-detailing
:response :expense-manual-description-msg}
:select-account
{:to-state :account-selection
:response :account-selection-msg}
:cancel-input
{:to-state :input}
:notify-input-success
{:to-state :input
:response :expense-added-successfully-msg}
:notify-input-failure
{:to-state :input
:response :failed-to-add-new-expense-msg}}})
(defn- handle-chat-state-transition!
[chat-id event]
(let [chat-type (first (:transition event))
chat-type-states (case chat-type
:chat-type/group group-chat-states
:chat-type/private private-chat-states)
change-state-fn (partial change-chat-state! chat-id chat-type-states)]
(handle-state-transition! event chat-state-transitions change-state-fn)))
; message states
(def ^:private group-msg-states
{:settings
{:initial #{:accounts-mgmt
:expense-items-mgmt
:shares-mgmt}
:accounts-mgmt #{:account-type-selection
:account-renaming
:account-revocation
:account-reinstatement
:initial}
:account-type-selection #{:accounts-mgmt
:initial}
:account-renaming #{:accounts-mgmt
:initial}
:account-revocation #{:accounts-mgmt
:initial}
:account-reinstatement #{:accounts-mgmt
:initial}
:expense-items-mgmt #{:expense-item-description
:expense-item-encoding
:expense-item-deletion
:initial}
:expense-item-description #{:expense-items-mgmt
:initial}
:expense-item-encoding #{:expense-items-mgmt
:initial}
:expense-item-deletion #{:expense-items-mgmt
:initial}
:shares-mgmt #{:initial}}})
(def ^:private msg-state-transitions
{:chat-type/group
{:settings
{:manage-accounts
{:to-state :accounts-mgmt
:response [:settings :accounts-mgmt-options-msg]}
:select-acc-type
{:to-state :account-type-selection
:response [:settings :account-type-selection-msg]}
:rename-account
{:to-state :account-renaming
:response [:settings :account-selection-msg]}
:revoke-account
{:to-state :account-revocation
:response [:settings :account-selection-msg]}
:reinstate-account
{:to-state :account-reinstatement
:response [:settings :account-selection-msg]}
:manage-expense-items
{:to-state :expense-items-mgmt
:response [:settings :expense-items-mgmt-options-msg]}
:redesc-expense-item
{:to-state :expense-item-description
:response [:settings :expense-item-selection-msg]}
:recode-expense-item
{:to-state :expense-item-encoding
:response [:settings :expense-item-selection-msg]}
:delete-expense-item
{:to-state :expense-item-deletion
:response [:settings :expense-item-selection-msg]}
:manage-shares
{:to-state :shares-mgmt}
:restore
{:to-state :initial
:response [:settings :restored-settings-msg]}}}})
(defn- handle-msg-state-transition!
[chat-id msg-id msg-event]
(let [chat-type (first (:transition msg-event))
all-msg-types-states (case chat-type
:chat-type/group group-msg-states)
msg-type (second (:transition msg-event))
msg-type-states (get all-msg-types-states msg-type)
change-state-fn (partial change-bot-msg-state! chat-id msg-id msg-type-states)]
(handle-state-transition! msg-event msg-state-transitions change-state-fn)))
;; RECIPROCAL ACTIONS
;; TODO: Switch to Event-Driven model. Is simpler?
;; HTTP requests should be transformed into events
;; that are handled by appropriate listeners (fns)
;; that, in turn, may result in emitting events.
;; - ABSTRACT ACTIONS
(defmulti ^:private send!
(fn [_token _ids response _opts] (:type response)))
(defmethod send! :text
[token {:keys [chat-id msg-id] :as _ids}
{:keys [text options] :as _response} {:keys [replace?] :as _opts}]
(if (is-bot-evicted-from-chat? chat-id)
(log/debug "Dropped sending a message to an evicted chat=" chat-id)
;; NB: Looks for the 'replace?' among the passed options to replace
;; the existing response message rather than sending a new one.
(if-not (true? replace?)
(m-api/send-text token chat-id options text)
(m-api/edit-text token chat-id msg-id options text))))
(defmethod send! :inline
[token {:keys [inline-query-id] :as _ids}
{:keys [results options] :as _response} _opts]
(m-api/answer-inline token inline-query-id options results))
(defmethod send! :callback
[token {:keys [callback-query-id] :as _ids}
{:keys [options] :as _response} _opts]
(tg-client/answer-callback-query token callback-query-id options))
(defn- make-tg-bot-api-request!
"Makes a request to the Telegram Bot API. By default, this function awaits the feedback
(a Telegram's response) synchronously and returns a pre-defined code ':finished-sync'.
Options are key-value pairs and may be one of:
:async?
An indicator to make the whole process asynchronous (causes the fn
to return immediately with the ':launched-async' code)
:on-failure
A fn used to handle an exception in case of the request failure
:on-success
A fn used to handle the Telegram's response in case of the successful request
NB: Properly wrapped in try-catch and logged to highlight the exact HTTP client error."
[request-fn {:keys [async? on-failure on-success] :as _?options}]
(let [token (config/get-prop :bot-api-token)
handle-tg-bot-api-req (fn []
(try
(request-fn token)
(catch Throwable t
(if (some? on-failure)
(on-failure t)
(log/error t "Failed making a Telegram Bot API request"))
:req-failed)))
handle-tg-response-fn (fn [tg-response]
(log/debug "Telegram returned:" tg-response)
(try
;; TODO: There are 2 possible outcomes. Do we need to differentiate them somehow?
;; - successful request ('ok' equals true)
;; - unsuccessful request ('ok' equals false, error is in the 'description')
(when (and (some? on-success)
(true? (:ok tg-response)))
(on-success (:result tg-response)))
(catch Exception e
(log/error e "Failed to handle the response from Telegram"))))
handle-when-succeeded (fn [res]
(when-not (= :req-failed res)
(handle-tg-response-fn res)))]
(if (true? async?)
(letfn [(with-one-off-channel [req-fn handle-fn]
(let [resp-chan (chan)]
(go (handle-fn (<! resp-chan))
(close! resp-chan))
(go (>! resp-chan (req-fn)))))]
(with-one-off-channel handle-tg-bot-api-req handle-when-succeeded)
:launched-async)
(do
(handle-when-succeeded (handle-tg-bot-api-req))
:finished-sync))))
(defn- respond!
"Uniformly responds to the user action, whether it a message, inline or callback query,
or some event (e.g. service message or chat member status update).
This fn takes an optional parameter, which is an options map of a specific API method."
([ids response]
(respond! ids response nil))
([ids response ?options]
(make-tg-bot-api-request!
(fn [token]
(send! token ids response ?options))
(assoc ?options
;; TODO: Add the 'response' to the 'failed-responses' queue for the bot Admin
;; to be able to manually handle it later, if this feature is necessary.
:on-failure #(log/errorf % "Failed to respond to %s with %s" ids response)))))
(defn- respond!*
"A variant of the 'respond!' function that is used with the 'keys' of one of
the predefined responses, rather than with an arbitrary response value."
[ids response-keys & {:keys [param-vals] :as ?options}]
{:pre [(vector? response-keys)]}
(encore/when-let [response-data (get-in responses response-keys)
response (to-response response-data param-vals)]
(respond! ids response
(dissoc ?options :param-vals))))
;; TODO: GET RID OF MOST OF THESE !-FNS MAKING THEM PURE AND PASSING THEM DATA!
(defn- proceed-with-chat-and-respond!
"Continues the course of transitions between the states of the chat and sends
a message (answers an inline/callback query) in response to a user/an event."
[{:keys [chat-id] :as ids} event & {:as ?options}]
{:pre [(some? chat-id)]}
(when-let [response (handle-chat-state-transition! chat-id event)]
(respond! ids response ?options)))
(defn- proceed-with-msg-and-respond!
"Continues the course of transitions between the states of the extant message
in some chat and replaces its content in response to a user/an event."
[{:keys [chat-id msg-id] :as ids} msg-event & {:as ?options}]
{:pre [(some? chat-id) (some? msg-id)]}
(when-let [response (handle-msg-state-transition! chat-id msg-id msg-event)]
(respond! ids response
(assoc ?options :replace? true))))
(defn- delete-text!
[token {:keys [chat-id msg-id] :as _ids}]
(if (is-bot-evicted-from-chat? chat-id)
(log/debug "Dropped deleting the bot's response from an evicted chat=" chat-id)
(m-api/delete-text token chat-id msg-id)))
(defn- delete-response!
"Deletes one of the bot's previous response messages.
NB: - A message can only be deleted if it was sent less than 48 hours ago.
- Bots can delete outgoing messages in private chats, groups, and supergroups.
This fn takes an optional parameter, which is an options map of a specific API method."
([ids]
(delete-response! ids nil))
([ids ?options]
(make-tg-bot-api-request!
(fn [token]
(delete-text! token ids))
(assoc ?options
:on-failure #(log/errorf % "Failed to delete the response message %s" ids)))))
;; - SPECIFIC ACTIONS
(defn- send-retry-command!
[{{chat-id :id} :chat :as message}]
(let [commands-to-retry (tg-client/get-commands {:message message})]
(respond! {:chat-id chat-id}
(get-retry-commands-msg commands-to-retry))))
(defn- send-retry-message!
[{{chat-id :id} :chat :as _message}]
(respond! {:chat-id chat-id}
retry-resend-message-msg))
(defn- send-retry-callback-query!
[{callback-query-id :id :as _callback-query}]
(respond! {:callback-query-id callback-query-id}
retry-callback-query-notification))
(defn- notify-of-inconsistent-chat-state!
[{{chat-id :id} :chat :as _chat-member-updated-or-message}]
(log/errorf "Chat=%s has entered an inconsistent state" chat-id)
'(notify-bot-admin)) ;; TODO: Implement Admin notifications feature.
; private chats
(defn- report-to-user!
[user-id response-keys param-vals]
(when (can-write-to-user? user-id)
(respond!* {:chat-id user-id} response-keys :param-vals param-vals)))
(defn- proceed-with-adding-new-expense!
[chat-id debtor-acc]
(let [chat-data (get-chat-data chat-id)
group-chat-id (:group chat-data)
group-chat-data (get-chat-data group-chat-id)
payer-acc-id (get-personal-account-id
group-chat-data {:user-id chat-id})
debtor-acc-id (:id debtor-acc)
expense-amount (:amount chat-data)
expense-details (or (:expense-item chat-data)
(:expense-desc chat-data))
new-transaction {:chat-id group-chat-id
:payer-acc-id payer-acc-id
:debtor-acc-id debtor-acc-id
:expense-amount expense-amount
:expense-details expense-details}]
(slingshot/try+
(add-transaction! (tlogs/create! new-transaction))
(catch Exception e
;; TODO: Retry to log the failed transaction?
(log/error e "Failed to log transaction:" new-transaction)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason data-persistence-error}}))
(else
(let [pers-accs-count (->> {:acc-types [:acc-type/personal]}
(get-group-chat-accounts chat-id)
count)
payer-acc-name (when-not (or (= pers-accs-count 1)
(= payer-acc-id debtor-acc-id))
(:name (get-group-chat-account
group-chat-data {:type :acc-type/personal
:id payer-acc-id})))
debtor-acc-name (when-not (= pers-accs-count 1)
(:name debtor-acc))]
(respond!* {:chat-id group-chat-id}
[:chat-type/private :new-expense-msg]
:param-vals {:expense-amount expense-amount
:expense-details expense-details
:payer-acc-name payer-acc-name
:debtor-acc-name debtor-acc-name}))
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-success]})))))
;; TODO: Abstract this away — "selecting 1 of N, with a special case for N=1".
(defn- proceed-with-account!
[chat-id]
(let [group-chat-id (:group (get-chat-data chat-id))
active-accounts (get-group-chat-accounts group-chat-id)]
(cond
(< 1 (count active-accounts))
(let [other-accounts (filter #(not= (:user-id %) chat-id) active-accounts)]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :select-account]
:param-vals {:accounts other-accounts
:txt select-payer-account-txt}}))
(empty? active-accounts)
(do
(log/error "No eligible accounts to select a debtor account from")
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason no-debtor-account-error}}))
:else
(let [debtor-acc (first active-accounts)]
(log/debug "Debtor account auto-selected:" debtor-acc)
(proceed-with-adding-new-expense! chat-id debtor-acc)))))
(defn- proceed-with-expense-details!
[chat-id group-chat-id first-name]
(let [group-chat-data (get-chat-data group-chat-id)
expense-items (get-group-chat-expense-items group-chat-data)
event (if (seq expense-items)
{:transition [:chat-type/private :select-expense-item]
:param-vals {:expense-items expense-items}}
{:transition [:chat-type/private :request-expense-desc]
:param-vals {:first-name first-name}})]
(proceed-with-chat-and-respond! {:chat-id chat-id} event)))
;; TODO: Abstract this away — "selecting 1 of N, with a special case for N=1".
(defn- proceed-with-group!
[chat-id first-name]
(let [is-eligible? (fn [group-chat-id]
(is-group-chat-eligible-for-selection? group-chat-id chat-id))
groups (->> (get-chat-data chat-id)
get-private-chat-groups
(filter is-eligible?))]
(cond
(< 1 (count groups))
(let [group-refs (->> groups
(map #(vector % (-> % get-chat-data get-chat-title)))
(map #(apply ->group-ref %)))]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :select-group]
:param-vals {:group-refs group-refs}}))
(empty? groups)
(do
(log/error "No eligible groups to record expenses to")
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason no-group-to-record-error}}))
:else
(let [group-chat-id (first groups)]
(log/debug "Group chat auto-selected:" group-chat-id)
(assoc-in-chat-data! chat-id [:group] group-chat-id)
(proceed-with-expense-details! chat-id group-chat-id first-name)))))
;; TODO: Abstract away the "selecting N of {M; optional ALL}, M>=N>0" scenario.
(defn- clean-up-interactive-input-data!
[chat-id]
(let [dropped-msgs (concat (drop-bot-msg! chat-id {:type :inline-calculator})
(drop-bot-msg! chat-id {:type :cancel-disclaimer}))]
(doseq [msg-id dropped-msgs]
(delete-response! {:chat-id chat-id :msg-id msg-id}))))
; group chats
; - chat & msgs state
(defn- proceed-with-bot-eviction!
[chat-id]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/group :mark-evicted]}))
(defn- proceed-with-restoring-group-chat-intro!
[chat-id user-id msg-id]
(release-message-lock! chat-id user-id msg-id)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :restore]}))
; - personal accounts
(defn- proceed-with-personal-accounts-name-request!
[chat-id existing-chat? ?new-chat-members]
(respond!* {:chat-id chat-id}
[:chat-type/group :personal-account-name-request-msg]
:param-vals {:existing-chat? existing-chat?
:chat-members ?new-chat-members}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :name-request})))
(defn- proceed-with-group-chat-finalization!
[chat-id show-settings?]
;; NB: Tries to create a new version of the "general account"
;; even if the group chat already existed before.
(create-general-account! chat-id (get-datetime-in-tg-format))
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/group :mark-managed]
:param-vals {:bot-username (get-bot-username)}})
(when show-settings?
(respond!* {:chat-id chat-id}
[:chat-type/group :settings-msg]
:param-vals {:first-time? true}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :settings
:state :initial}))))
(defn- check-personal-accounts-and-proceed!
([chat-id]
(let [existing-chat? (does-bot-manage-the-chat? {:chat-id chat-id})]
(check-personal-accounts-and-proceed! chat-id existing-chat?)))
([chat-id existing-chat?]
;; NB: We need to update the list of chat personal accounts with new ones
;; for those users:
;; - who were members of the previously non-existent group chat at the
;; time the bot was added there (or were added along with the bot),
;; - who have joined the existing group chat during the absence of the
;; previously evicted bot, if there are any. (Users with an existing
;; active personal account should be ignored in this case.)
(let [pers-accs-missing (get-number-of-missing-personal-accounts chat-id)]
(if (> pers-accs-missing 0)
(if (and (seq (find-bot-messages (get-chat-data chat-id) {:type :name-request}))
(not (is-bot-evicted-from-chat? chat-id))) ;; just in case, to not stuck
(respond!* {:chat-id chat-id}
[:chat-type/group :personal-accounts-left-msg]
:param-vals {:count pers-accs-missing})
(proceed-with-personal-accounts-name-request! chat-id existing-chat? nil))
(do
(drop-bot-msg! chat-id {:type :name-request})
(proceed-with-group-chat-finalization! chat-id (not existing-chat?)))))))
(defn- proceed-with-new-chat-members!
[chat-id new-chat-members]
(update-members-count! chat-id (partial + (count new-chat-members)))
(proceed-with-personal-accounts-name-request! chat-id true new-chat-members))
(defn- proceed-with-left-chat-member!
[chat-id left-chat-member]
(update-members-count! chat-id dec)
;; NB: It is necessary to trigger the personal accounts check, just in case we
;; are in the middle of the accounts creation process. If so, it will help
;; us to avoid stale ':name-request' message in chat data and, what's even
;; more important, will run the group chat finalization routine.
(check-personal-accounts-and-proceed! chat-id)
(encore/when-let [chat-data (get-chat-data chat-id)
user-id (:id left-chat-member)
pers-acc (get-personal-account chat-data {:user-id user-id})
datetime (get-datetime-in-tg-format)]
(change-account-activity-status! chat-id pers-acc
{:revoke? true :datetime datetime})
(drop-user-input-data! chat-id user-id)
(report-to-user! user-id
[:chat-type/private :removed-from-group-msg]
{:chat-title (get-chat-title chat-data)})))
; - accounts mgmt
(defn- proceed-with-accounts-mgmt!
[chat-id msg-id]
(let [accounts-by-type (get-group-chat-accounts-by-type chat-id)]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-accounts]
:param-vals {:accounts-by-type accounts-by-type}})))
(defn- proceed-with-account-type-selection!
[chat-id msg-id]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :select-acc-type]
:param-vals {:account-types [:acc-type/group :acc-type/personal]
:extra-buttons [back-button]}}))
(defn- proceed-with-account-naming!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-account-name-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-acc-name})))
(defn- proceed-with-the-account-name-is-already-taken!
[chat-id {user-id :id :as user} bot-msg-type]
(respond!* {:chat-id chat-id}
[:chat-type/group :the-account-name-is-already-taken-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type bot-msg-type})))
(defn- proceed-with-next-account-creation-steps!
[chat-id acc-type {user-id :id :as user}]
(let [input-data {:acc-type acc-type}]
(set-user-input-data! chat-id user-id :create-account input-data))
(case acc-type
:acc-type/personal
(proceed-with-account-naming! chat-id user)
:acc-type/group
(let [personal-accs (get-group-chat-accounts chat-id
{:acc-types [:acc-type/personal]})]
(respond!* {:chat-id chat-id}
[:chat-type/group :group-members-selection-msg]
:param-vals {:user user
:selected nil
:remaining personal-accs}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :group-members-selection})))))
(defn- proceed-with-account-member-selection!
[chat-id msg-id user already-selected-account-members]
(let [personal-accs (set (get-group-chat-accounts chat-id
{:acc-types [:acc-type/personal]}))
selected-accs (set already-selected-account-members)
remaining-accs (set/difference personal-accs selected-accs)
accounts-remain? (seq remaining-accs)]
(when accounts-remain?
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/group :group-members-selection-msg]
:param-vals {:user user
:selected selected-accs
:remaining remaining-accs}
:replace? true))
accounts-remain?))
(defn- proceed-with-end-of-account-members-selection!
[chat-id msg-id {user-id :id :as user} members]
(drop-bot-msg! chat-id {:to-user user-id
:type :group-members-selection})
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/group :new-group-members-msg]
:param-vals {:acc-names (map :name members)}
:replace? true)
(proceed-with-account-naming! chat-id user))
(defn- proceed-with-next-group-account-creation-steps!
[chat-id msg-id {user-id :id :as user}]
(let [members (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(get :members))
can-proceed? (proceed-with-account-member-selection! chat-id msg-id user members)]
(when-not can-proceed?
(proceed-with-end-of-account-members-selection! chat-id msg-id user members))))
(defn- proceed-with-account-selection!
([chat-id msg-id callback-query-id
state-transition-name]
(proceed-with-account-selection! chat-id msg-id callback-query-id
state-transition-name nil))
([chat-id msg-id callback-query-id
state-transition-name ?filter-pred]
(let [eligible-accs (get-group-chat-accounts chat-id
{:acc-types [:acc-type/group
:acc-type/personal]
:filter-pred ?filter-pred})]
(if (seq eligible-accs)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings state-transition-name]
:param-vals {:accounts eligible-accs
:txt select-account-txt
:extra-buttons [back-button]}})
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-eligible-accounts-notification])))))
(defn- proceed-with-account-renaming!
[chat-id {user-id :id :as user} acc-to-rename]
(let [input-data {:acc-type (:type acc-to-rename)
:acc-id (:id acc-to-rename)}]
(set-user-input-data! chat-id user-id :rename-account input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :account-rename-request-msg]
:param-vals {:user user
:acc-name (:name acc-to-rename)}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-acc-rename})))
(defn- proceed-with-personal-account-creation!
[chat-id chat-title
acc-name created-dt {user-id :id :as user} first-msg-id]
(let [create-acc-res (create-personal-account! chat-id acc-name created-dt
:user-id user-id :first-msg-id first-msg-id)]
(if (is-failure? create-acc-res)
(case create-acc-res
:failure/user-already-has-an-active-account
(respond!* {:chat-id chat-id} [:chat-type/group :canceled-changes-msg])
:failure/the-account-name-is-already-taken
(proceed-with-the-account-name-is-already-taken! chat-id user :name-request))
(report-to-user! user-id
[:chat-type/private :added-to-new-group-msg]
{:chat-title chat-title}))))
(defn- proceed-with-account-operation!
[chat-id {user-id :id :as user}
bot-msg-type input-name acc-op-fn]
(let [chat-data (get-chat-data chat-id)
input-data (get-user-input-data chat-data user-id input-name)
acc-op-res (acc-op-fn chat-id input-data)]
(if (is-failure? acc-op-res)
(case acc-op-res
:failure/the-account-name-is-already-taken
(proceed-with-the-account-name-is-already-taken! chat-id user bot-msg-type)
(throw (ex-info "Unexpected operation result" {:result acc-op-res})))
(do
(clean-up-chat-data! chat-id {:bot-messages [{:to-user user-id
:type bot-msg-type}]
:input [{:user user-id
:name input-name}]})
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg])))))
; - expense items mgmt
(defn- proceed-with-expense-items-mgmt!
[chat-id msg-id]
(let [chat-data (get-chat-data chat-id)
expense-items (get-group-chat-expense-items chat-data)]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-expense-items]
:param-vals {:expense-items expense-items}})))
(defn- proceed-with-expense-item-description!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-expense-item-desc-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-desc})))
(defn- proceed-with-expense-item-encoding!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-expense-item-code-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-code})))
(defn- proceed-with-the-expense-item-code-is-already-used!
[chat-id {user-id :id :as user} bot-msg-type]
(respond!* {:chat-id chat-id}
[:chat-type/group :the-expense-item-code-is-already-used-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type bot-msg-type})))
(defn- proceed-with-expense-item-creation-steps!
[chat-id user]
;; TODO: Re-implement as a "logical action flow": name + desc.
(proceed-with-expense-item-description! chat-id user))
(defn- proceed-with-expense-item-operation!
[chat-id {user-id :id :as user}
bot-msg-type input-name exp-it-op-fn]
(let [chat-data (get-chat-data chat-id)
input-data (get-user-input-data chat-data user-id input-name)
exp-it-op-res (exp-it-op-fn chat-id input-data)]
(if (is-failure? exp-it-op-res)
(case exp-it-op-res
:failure/the-expense-item-code-is-already-used
(proceed-with-the-expense-item-code-is-already-used! chat-id user bot-msg-type)
(throw (ex-info "Unexpected operation result" {:result exp-it-op-res})))
(do
(clean-up-chat-data! chat-id {:bot-messages [{:to-user user-id
:type bot-msg-type}]
:input [{:user user-id
:name input-name}]})
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg])))))
(defn- proceed-with-expense-item-selection!
([chat-id msg-id callback-query-id
state-transition-name]
(proceed-with-expense-item-selection! chat-id msg-id callback-query-id
state-transition-name nil))
([chat-id msg-id callback-query-id
state-transition-name ?filter-pred]
(let [chat-data (get-chat-data chat-id)
eligible-expense-items (cond->> (get-group-chat-expense-items chat-data)
(some? ?filter-pred) (filter ?filter-pred))]
(if (seq eligible-expense-items)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings state-transition-name]
:param-vals {:expense-items eligible-expense-items
:extra-buttons [back-button]}})
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-eligible-expense-items-notification])))))
(defn- proceed-with-expense-item-re-description!
[chat-id {user-id :id :as user} exp-it-to-redesc]
(let [input-data {:exp-it-code (first exp-it-to-redesc)}]
(set-user-input-data! chat-id user-id :redesc-expense-item input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :expense-item-redesc-request-msg]
:param-vals {:user user
:exp-it-desc (:desc (second exp-it-to-redesc))}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-redesc})))
(defn- proceed-with-expense-item-re-encoding!
[chat-id {user-id :id :as user} exp-it-to-recode]
(let [input-data {:exp-it-code (first exp-it-to-recode)}]
(set-user-input-data! chat-id user-id :recode-expense-item input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :expense-item-recode-request-msg]
:param-vals {:user user
:exp-it-desc (:desc (second exp-it-to-recode))}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-recode})))
(defn- proceed-with-expense-item-deletion!
[chat-id exp-it-to-delete]
(let [delete-exp-it-res (delete-group-chat-expense-item! chat-id exp-it-to-delete)]
(if (is-failure? delete-exp-it-res)
(case delete-exp-it-res
:failure/the-expense-item-cannot-be-deleted
(respond!* {:chat-id chat-id}
[:chat-type/group :the-expense-item-cannot-be-deleted-msg]
:param-vals {:exp-it-code (first exp-it-to-delete)
:exp-it-desc (:desc (second exp-it-to-delete))})
(throw (ex-info "Unexpected operation result" {:result delete-exp-it-res})))
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg]))))
;; TODO: Linearize calls to these macros with a wrapper macro & a map.
(defmacro do-when-chat-is-ready-or-send-notification!
[chat-state callback-query-id & body]
`(if (does-bot-manage-the-chat? {:chat-state ~chat-state})
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :waiting-for-user-input-notification])))
(defmacro do-with-expected-user-or-send-notification!
[chat-id user-id msg-id callback-query-id & body]
`(if (check-bot-msg (get-bot-msg (get-chat-data ~chat-id) ~msg-id)
{:to-user ~user-id})
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :waiting-for-other-user-notification])))
(defmacro try-with-message-lock-or-send-notification!
[chat-id user-id msg-id callback-query-id & body]
`(if (acquire-message-lock! ~chat-id ~user-id ~msg-id)
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :message-already-in-use-notification])))
;; - COMMANDS ACTIONS
; private chats
(defn- cmd-private-start!
[{chat-id :id :as chat}
{first-name :first_name :as _user}]
(log/debug "Conversation started in a private chat:" chat)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :request-amount]
:param-vals {:first-name first-name}}))
;; TODO: Implement proper '/help' message (w/ the list of commands, etc.).
(defn- cmd-private-help!
[{chat-id :id :as chat}]
(log/debug "Help requested in a private chat:" chat)
(respond! {:chat-id chat-id}
{:type :text
:text "Help is on the way!"}))
(defn- cmd-private-calc!
[{chat-id :id :as chat}]
(when (= :input (-> chat-id get-chat-data get-chat-state))
(log/debug "Calculator opened in a private chat:" chat)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :show-calculator]}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :inline-calculator}))
(respond!* {:chat-id chat-id}
[:chat-type/private :interactive-input-disclaimer-msg]
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :cancel-disclaimer}))))
(defn- cmd-private-cancel!
[{chat-id :id :as chat}]
(log/debug "The operation is canceled in a private chat:" chat)
;; clean-up the messages
(case (get-chat-state (get-chat-data chat-id))
:interactive-input
(clean-up-interactive-input-data! chat-id)
nil)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :cancel-input]}))
; group chats
;; TODO: Implement proper '/help' message (w/ the list of commands, etc.).
(defn- cmd-group-help!
[{chat-id :id :as chat}]
(log/debug "Help requested in a group chat:" chat)
(respond! {:chat-id chat-id}
{:type :text
:text "Help is on the way!"}))
(defn- cmd-group-settings!
[{chat-id :id :as chat}]
(log/debug "Settings requested in a group chat:" chat)
(respond!* {:chat-id chat-id}
[:chat-type/group :settings-msg]
:param-vals {:first-time? false}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :settings
:state :initial})))
;; API RESPONSES
;; IMPORTANT: The main idea of this API is to organize handlers of any type (message, command, any
;; query, etc.) into a chain (in the order of their declaration within the 'defhandler'
;; body) that will process updates in the following way:
;; - the first handler of the type have to log an incoming update (its payload object);
;; - any intermediate handler have to either:
;; - result in an "operation [result] code" ('succeed', 'failed') OR in an "immediate
;; response" (only for Webhook updates) — which will stop the further processing;
;; - result in 'nil' — which will pass the update for processing to the next handler;
;; - the last handler, in case the update wasn't processed, have to "ignore" it — which
;; is also interpreted as the whole operation had 'succeed'.
;; NB: Any non-nil will do.
(def op-succeed {:ok true})
(def op-failed {:ok false})
(defmacro ^:private ignore
[msg & args]
`(do
(log/debugf (str "Ignored: " ~msg) ~@args)
op-succeed))
(defn- cb-succeed
[callback-query-id]
(tg-api/build-immediate-response "answerCallbackQuery"
{:callback_query_id callback-query-id}))
(defn- cb-ignored
[callback-query-id]
;; TODO: For a long-polling version, respond as usual.
(tg-api/build-immediate-response "answerCallbackQuery"
(assoc ignored-callback-query-notification
:callback_query_id callback-query-id)))
;; TODO: This have to be combined with an Event-Driven model,
;; i.e. in case of long-term request processing the bot
;; should immediately respond with sending the 'typing'
;; chat action (use "sendChatAction" method and see the
;; /sendChatAction specs for the request parameters).
;; BOT API
;; TODO: The design should be similar to the Lupapiste web handlers with their 'in-/outjects'.
;; TODO: Add a rate limiter. Use the 'limiter' from Encore? Or some full-featured RPC library?
;; This is to overcome the recent error — HTTP 429 — "Too many requests, retry after X".
; The Bots FAQ on the official Telegram website lists the following limits on server requests:
; - No more than 1 message per second in a single chat,
; - No more than 20 messages per minute in one group,
; - No more than 30 messages per second in total.
(defmacro handle-with-care!
[bindings & handler-body-and-care-fn]
(let [body (butlast handler-body-and-care-fn)
care-fn (last handler-body-and-care-fn)]
`(fn [arg#]
(try
((fn ~bindings ~@body) arg#)
(catch Exception e#
(log/error e# "Failed to handle an incoming update:" arg#)
(when-some [ex-data# (ex-data e#)]
(log/error "The associated exception data:" ex-data#))
(~care-fn arg#)
op-failed)))))
(tg-client/defhandler
handler
;; NB: This function is applied to the arguments of all handlers that follow
;; and merges its result with the original value of the argument.
(fn [upd upd-type]
(let [chat (case upd-type
(:message :my_chat_member) (-> upd upd-type :chat)
(:callback_query) (-> upd upd-type :message :chat)
nil)
msg (case upd-type
:message (:message upd)
:callback_query (-> upd :callback_query :message)
nil)
chat-data (get-chat-data (or (:id chat)
(:id (:chat msg))))]
(cond-> nil
(some? chat)
(merge {:chat-type (cond
(tg-api/is-private? chat) :chat-type/private
(tg-api/is-group? chat) :chat-type/group)
:chat-state (get-chat-state chat-data)})
(some? msg)
(merge (when-some [bot-msg (get-bot-msg chat-data (:message_id msg))]
{:bot-msg bot-msg})))))
;; - BOT COMMANDS
; group chats
(tg-client/command-fn
"help"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/group (:chat-type message))
(cmd-group-help! chat)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"settings"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/group (:chat-type message))
(cmd-group-settings! chat)
op-succeed)
send-retry-command!))
; private chats
(tg-client/command-fn
"start"
(handle-with-care!
[{user :from chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-start! chat user)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"help"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-help! chat)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"calc"
(handle-with-care!
[{chat :chat :as message}]
(when (and (= :chat-type/private (:chat-type message))
(cmd-private-calc! chat))
op-succeed)
send-retry-command!))
(tg-client/command-fn
"cancel"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-cancel! chat)
op-succeed)
send-retry-command!))
;; - INLINE QUERIES
(m-hlr/inline-fn
(fn [inline-query]
(log/debug "Inline query:" inline-query)))
;; TODO: Try to implement an inline query answered w/ 'switch_pm_text' parameter?
(m-hlr/inline-fn
(fn [{inline-query-id :id _user :from query-str :query _offset :offset
:as _inline-query}]
(ignore "inline query id=%s, query=%s" inline-query-id query-str)))
;; - CALLBACK QUERIES
(m-hlr/callback-fn
(fn [callback-query]
(log/debug "Callback query:" callback-query)))
; group chats
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-accounts callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-accounts-mgmt! chat-id msg-id)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :accounts-mgmt (-> callback-query :bot-msg :state)))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(when-let [respond! (condp = callback-btn-data
cd-accounts-create #(proceed-with-account-type-selection!
chat-id msg-id)
cd-accounts-rename #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:rename-account
(can-rename-account? chat-id user-id))
cd-accounts-revoke #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:revoke-account
(can-revoke-account? chat-id user-id))
cd-accounts-reinstate #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:reinstate-account
(can-reinstate-account? chat-id user-id))
nil)]
(respond!)
(cb-succeed callback-query-id)))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-type-selection (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-type-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [acc-type-name (str/replace-first callback-btn-data
cd-account-type-prefix "")
acc-type (keyword "acc-type" acc-type-name)]
(proceed-with-next-account-creation-steps! chat-id acc-type user))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
picked-acc (data->account callback-btn-data chat-data)
input-data (-> chat-data
(get-user-input-data user-id :create-account)
(update :members #(u-coll/add-or-remove picked-acc %)))]
(set-user-input-data! chat-id user-id :create-account input-data))
(proceed-with-next-group-account-creation-steps! chat-id msg-id user)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(= cd-undo callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(drop-bot-msg! chat-id {:to-user user-id
:type :group-members-selection})
(set-user-input-data! chat-id user-id :create-account nil)
(delete-response! {:chat-id chat-id :msg-id msg-id})
(respond!* {:chat-id chat-id}
[:chat-type/group :canceled-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(= cd-done callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [members (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(get :members))]
(if (seq members)
(do
(proceed-with-end-of-account-members-selection! chat-id msg-id user members)
(cb-succeed callback-query-id))
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-group-members-selected-notification]))))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-renaming (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
account-to-rename (data->account callback-btn-data chat-data)]
(proceed-with-account-renaming! chat-id user account-to-rename))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-revocation (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
account-to-revoke (data->account callback-btn-data chat-data)
datetime (get-datetime-in-tg-format)]
;; NB: It makes sense to ask the user if the revoked account owner
;; should be excluded from the chat, but this is possible only
;; for bots with 'admin' rights.
(change-account-activity-status! chat-id account-to-revoke
{:revoke? true :datetime datetime}))
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(respond!* {:chat-id chat-id} [:chat-type/group :successful-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-reinstatement (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
account-to-reinstate (data->account callback-btn-data chat-data)
datetime (get-datetime-in-tg-format)]
(change-account-activity-status! chat-id account-to-reinstate
{:reinstate? true :datetime datetime}))
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(respond!* {:chat-id chat-id} [:chat-type/group :successful-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-expense-items callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-expense-items-mgmt! chat-id msg-id)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-items-mgmt (-> callback-query :bot-msg :state)))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(when-let [respond! (condp = callback-btn-data
cd-expense-items-create #(proceed-with-expense-item-creation-steps!
chat-id user)
cd-expense-items-redesc #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:redesc-expense-item)
cd-expense-items-recode #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:recode-expense-item)
cd-expense-items-delete #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:delete-expense-item
can-expense-item-be-deleted?)
nil)]
(respond!)
(cb-succeed callback-query-id)))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-description (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-re-description! chat-id user expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-encoding (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-re-encoding! chat-id user expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-deletion (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-deletion! chat-id expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-shares callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-shares]})))
(cb-succeed callback-query-id))
send-retry-callback-query!))
;; TODO: Implement handlers for ':shares-mgmt'.
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= cd-back callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(case (-> callback-query :bot-msg :state)
(:initial ;; for when something went wrong
:accounts-mgmt :expense-items-mgmt :shares-mgmt)
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(:account-type-selection :account-renaming :account-revocation :account-reinstatement)
(proceed-with-accounts-mgmt! chat-id msg-id)
(:expense-item-description :expense-item-encoding :expense-item-deletion)
(proceed-with-expense-items-mgmt! chat-id msg-id))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
; private chats
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{first-name :first_name} :from
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :group-selection (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-group-chat-prefix))
(let [group-chat-id-str (str/replace-first callback-btn-data cd-group-chat-prefix "")
group-chat-id (u-nums/parse-int group-chat-id-str)]
(assoc-in-chat-data! chat-id [:group] group-chat-id)
(proceed-with-expense-details! chat-id group-chat-id first-name))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :expense-detailing (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(let [expense-item (str/replace-first callback-btn-data cd-expense-item-prefix "")]
(assoc-in-chat-data! chat-id [:expense-item] expense-item)
(proceed-with-account! chat-id))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :account-selection (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-account-prefix))
(let [group-chat-id (:group (get-chat-data chat-id))
group-chat-data (get-chat-data group-chat-id)
debtor-acc (data->account callback-btn-data group-chat-data)]
(proceed-with-adding-new-expense! chat-id debtor-acc))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :interactive-input (:chat-state callback-query)))
(when-let [non-terminal-operation (condp apply [callback-btn-data]
cd-digits-set {:type :append-digit
:data callback-btn-data}
cd-ar-ops-set {:type :append-ar-op
:data callback-btn-data}
(partial = cd-clear) {:type :cancel}
(partial = cd-cancel) {:type :clear}
nil)]
(let [old-user-input (get-user-input (get-chat-data chat-id))
new-user-input (update-user-input! chat-id non-terminal-operation)]
(when (not= old-user-input new-user-input)
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/private :inline-calculator-msg]
:param-vals {:new-user-input new-user-input}
:replace? true)))
(cb-succeed callback-query-id)))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{first-name :first_name} :from
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :interactive-input (:chat-state callback-query))
(= cd-enter callback-btn-data))
(let [user-input (get-user-input (get-chat-data chat-id))
parsed-val (u-nums/parse-arithmetic-expression user-input)]
(if (and (number? parsed-val) (pos? parsed-val))
(do
(log/debug "User input:" parsed-val)
(assoc-in-chat-data! chat-id [:amount] parsed-val)
(clean-up-interactive-input-data! chat-id)
(respond!* {:chat-id chat-id}
[:chat-type/private :interactive-input-success-msg]
:param-vals {:parsed-val parsed-val})
(proceed-with-group! chat-id first-name))
(do
(log/debugf "Invalid user input: \"%s\"" parsed-val)
(respond!* {:callback-query-id callback-query-id}
[:chat-type/private :invalid-input-notification]))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(fn [{callback-query-id :id _user :from _msg :message _msg-id :inline_message_id
_chat-instance :chat_instance callback-btn-data :data
:as _callback-query}]
(ignore "callback query id=%s, data=%s" callback-query-id callback-btn-data)
(cb-ignored callback-query-id)))
;; - CHAT MEMBER STATUS UPDATES
(tg-client/bot-chat-member-status-fn
(handle-with-care!
[{{chat-id :id _type :type chat-title :title _username :username :as chat} :chat
{_user-id :id first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
date :date
{_old-user :user _old-status :status :as _old-chat-member} :old_chat_member
{_new-user :user _new-status :status :as _new-chat-member} :new_chat_member
:as my-chat-member-updated}]
(log/debug "Bot chat member status updated in:" chat)
(cond
(tg-api/has-joined? my-chat-member-updated)
(let [token (config/get-prop :bot-api-token)
chat-members-count (tg-client/get-chat-member-count token chat-id)
new-chat (setup-new-group-chat! chat-id chat-title chat-members-count)
existing-chat? (nil? new-chat)]
(if existing-chat?
(do
(log/debugf "The chat=%s already exists" chat-id)
(update-members-count! chat-id (constantly chat-members-count)))
(respond!* {:chat-id chat-id}
[:chat-type/group :introduction-msg]
:param-vals {:chat-members-count chat-members-count
:first-name first-name}))
(check-personal-accounts-and-proceed! chat-id existing-chat?)
op-succeed)
(tg-api/has-left? my-chat-member-updated)
(do
(update-members-count! chat-id dec)
(proceed-with-bot-eviction! chat-id)
op-succeed)
:else
(ignore "bot chat member status update dated %s in chat=%s" date chat-id))
notify-of-inconsistent-chat-state!))
(tg-client/chat-member-status-fn
(fn [{{chat-id :id _type :type _chat-title :title _username :username :as chat} :chat
{_user-id :id _first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
date :date
{_old-user :user _old-status :status :as _old-chat-member} :old_chat_member
{_new-user :user _new-status :status :as _new-chat-member} :new_chat_member
:as _chat-member-updated}]
(log/debug "Chat member status updated in:" chat)
;; NB: The bot must be an administrator in the chat to receive 'chat_member' updates
;; about other chat members. By default, only 'my_chat_member' updates about the
;; bot itself are received.
(ignore "chat member status update dated %s in chat=%s" date chat-id)))
;; - PLAIN MESSAGES
; group chats
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id :as chat} :chat
new-chat-members :new_chat_members
:as _message}]
(when (some? new-chat-members)
(log/debug "New chat members in chat:" chat)
(let [new-chat-members (filter #(not (:is_bot %)) new-chat-members)]
(when (seq new-chat-members)
(proceed-with-new-chat-members! chat-id new-chat-members)
op-succeed)))
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id :as chat} :chat
left-chat-member :left_chat_member
:as _message}]
(when (some? left-chat-member)
(log/debug "Chat member left chat:" chat)
(when-not (:is_bot left-chat-member)
(proceed-with-left-chat-member! chat-id left-chat-member)
op-succeed))
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(fn [{msg-id :message_id group-chat-created :group_chat_created :as _message}]
(when (some? group-chat-created)
(ignore "message id=%s" msg-id))))
(m-hlr/message-fn
(handle-with-care!
[{msg-id :message_id date :date text :text
{user-id :id :as user} :from
{chat-id :id chat-title :title} :chat
:as message}]
;; TODO: Figure out how to proceed if someone accidentally closes the reply.
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:type :name-request}))
;; NB: Here the 'user-id' exists for sure, since it is the User's response.
(when-some [_new-chat (setup-new-private-chat! user-id chat-id)]
(update-private-chat-groups! user-id chat-id))
(proceed-with-personal-account-creation! chat-id chat-title
text date user msg-id)
(check-personal-accounts-and-proceed! chat-id)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{date :date text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-acc-name}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(assoc :acc-name text)
(assoc :created-dt date)
(assoc :created-by user-id))]
(set-user-input-data! chat-id user-id :create-account input-data))
(proceed-with-account-operation! chat-id user
:request-acc-name
:create-account
create-group-chat-account!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-acc-rename}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :rename-account)
(assoc :new-acc-name text))]
(set-user-input-data! chat-id user-id :rename-account input-data))
(proceed-with-account-operation! chat-id user
:request-acc-rename
:rename-account
change-group-chat-account-name!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-desc}))
(let [input-data {:exp-it-data {:desc text}}]
(set-user-input-data! chat-id user-id :create-expense-item input-data))
(proceed-with-expense-item-encoding! chat-id user)
(drop-bot-msg! chat-id {:to-user user-id
:type :request-exp-it-desc})
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{emoji :emoji} :sticker
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-code}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-expense-item)
(assoc :exp-it-code (or text emoji)))]
(set-user-input-data! chat-id user-id :create-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-code
:create-expense-item
create-group-chat-expense-item!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-redesc}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :redesc-expense-item)
(assoc-in [:exp-it-data :desc] text))]
(set-user-input-data! chat-id user-id :redesc-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-redesc
:redesc-expense-item
update-group-chat-expense-item!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{emoji :emoji} :sticker
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-recode}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :recode-expense-item)
(assoc :new-exp-it-code (or text emoji)))]
(set-user-input-data! chat-id user-id :recode-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-recode
:recode-expense-item
change-group-chat-expense-item-code!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id} :chat
new-chat-title :new_chat_title
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(some? new-chat-title))
(log/debugf "Chat %s title was changed to '%s'" chat-id new-chat-title)
(set-chat-title! chat-id new-chat-title)
op-succeed)
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id} :chat
migrate-to-chat-id :migrate_to_chat_id
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(some? migrate-to-chat-id))
(log/debugf "Group %s has been migrated to a supergroup %s" chat-id migrate-to-chat-id)
(migrate-group-chat-to-supergroup! chat-id migrate-to-chat-id)
op-succeed)
notify-of-inconsistent-chat-state!))
; private chats
(m-hlr/message-fn
(handle-with-care!
[{text :text
{first-name :first_name} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/private (:chat-type message))
(= :input (:chat-state message)))
(let [input (u-nums/parse-number text)]
(if (number? input)
(do
(log/debug "User input:" input)
(assoc-in-chat-data! chat-id [:amount] input)
(proceed-with-group! chat-id first-name)
op-succeed)
(respond!* {:chat-id chat-id}
[:chat-type/private :invalid-input-msg]))))
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text {chat-id :id} :chat
:as message}]
(when (and (= :chat-type/private (:chat-type message))
(= :expense-detailing (:chat-state message)))
(log/debugf "Expense description: \"%s\"" text)
(assoc-in-chat-data! chat-id [:expense-desc] text)
(proceed-with-account! chat-id)
op-succeed)
send-retry-message!))
;; NB: A "match-all catch-through" case. Excessive list of parameters is for clarity.
(m-hlr/message-fn
(fn [{msg-id :message_id _date :date _text :text
{_user-id :id _first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
{_chat-id :id _type :type _chat-title :title _username :username :as chat} :chat
_sender-chat :sender_chat
_forward-from :forward_from
_forward-from-chat :forward_from_chat
_forward-from-message-id :forward_from_message_id
_forward-signature :forward_signature
_forward-sender-name :forward_sender_name
_forward-date :forward_date
_original-msg :reply_to_message ;; for replies
_via-bot :via_bot
_edit-date :edit_date
_author-signature :author_signature
_entities :entities
_new-chat-members :new_chat_members
_left-chat-member :left_chat_member
_new-chat-title :new_chat_title
_new-chat-photo :new_chat_photo
_delete-chat-photo :delete_chat_photo
_group-chat-created :group_chat_created
_supergroup-chat-created :supergroup_chat_created
_channel-chat-created :channel_chat_created
_message-auto-delete-timer-changed :message_auto_delete_timer_changed
_migrate-to-chat-id :migrate_to_chat_id
_migrate-from-chat-id :migrate_from_chat_id
_pinned-message :pinned_message
_reply-markup :reply_markup
:as _message}]
(log/debug "Unprocessed message in chat:" chat)
(ignore "message id=%s" msg-id))))
(defn bot-api
[update]
(log/debug "Received update:" update)
(handler update))
|
118861
|
(ns general-expenses-accountant.core
"Bot API and business logic (core functionality)"
(:require [clojure.set :as set]
[clojure.string :as str]
[clojure.core.async :refer [go chan timeout >! <! close!]]
[morse
[api :as m-api]
[handlers :as m-hlr]]
[mount.core :refer [defstate]]
[slingshot.slingshot :as slingshot]
[taoensso
[encore :as encore]
[timbre :as log]]
[general-expenses-accountant.config :as config]
[general-expenses-accountant.domain.chat :as chats]
[general-expenses-accountant.domain.tlog :as tlogs]
[general-expenses-accountant.md-v2 :as md-v2]
[general-expenses-accountant.tg-bot-api :as tg-api]
[general-expenses-accountant.tg-client :as tg-client]
[general-expenses-accountant.utils.coll :as u-coll]
[general-expenses-accountant.utils.nums :as u-nums])
(:import [java.util Locale]))
;; STATE
(defstate ^:private bot-user
:start (encore/if-let [token (config/get-prop :bot-api-token)
bot-user (tg-client/get-me token)]
(do
(log/debug "Identified myself:" bot-user)
bot-user)
(do
(log/fatal "Unable to identify myself")
(System/exit 3))))
(defn get-bot-username
[]
(get bot-user :username))
;; TODO: Send the list of supported commands w/ 'setMyCommands'.
;; TODO: Normally, this should be transformed into a 'cloffeine' cache
;; which periodically auto-evicts the cast-off chats data. Then,
;; the initial data should be truncated, e.g. by an 'updated_at'
;; timestamps, and the data for chats from the incoming requests
;; should be (re)loaded from the DB on demand.
(defstate ^:private *bot-data
:start (let [chats (chats/select-all)
ids (map :id chats)]
(log/debug "Total chats uploaded from the DB:" (count chats))
(atom (zipmap ids chats))))
(defn- get-bot-data
[]
@*bot-data)
(defn- update-bot-data!
([upd-fn]
(swap! *bot-data upd-fn))
([upd-fn & upd-fn-args]
(apply swap! *bot-data upd-fn upd-fn-args)))
(defn- conditionally-update-bot-data!
([pred upd-fn]
(with-local-vars [succeed true]
(let [updated-bot-data
(update-bot-data!
(fn [bot-data]
(if (pred bot-data)
(upd-fn bot-data)
(do
(var-set succeed false)
bot-data))))]
(when @succeed
updated-bot-data))))
([pred upd-fn & upd-fn-args]
(conditionally-update-bot-data! pred #(apply upd-fn % upd-fn-args))))
;; TODO: Get rid of this atom after debugging is complete. This is not needed for the app.
(defonce ^:private *transactions (atom {}))
(defn- add-transaction!
[new-transaction]
{:pre [(contains? new-transaction :chat-id)]}
(swap! *transactions update (:chat-id new-transaction) conj new-transaction))
;; ACCOUNTING TYPES
;; From the business logic perspective there are 2 main use cases for the bot:
;; 1. personal accounting — when a user creates a group chat for himself
;; and the bot;
;; 2. group accounting — when multiple users create a group chat and add
;; the bot there to track their general expenses.
;; The only difference between the two is that an account of a ':general' type
;; is automatically created for a group accounting and what format is used for
;; new expense notification messages.
(def ^:private min-chat-members-for-group-accounting
"The number of users in a group chat (including the bot itself)
required for it to be used for the general expenses accounting."
3)
;; NB: The approach to the design of the "virtual members" (those who aren't
;; backed with a user but nevertheless occupy a personal account) in the
;; personal accounting case.
;; - Do they count when determining the use case for a chat?
;; At the moment, they DO NOT count. Only real chat members do.
;; - Are they merely different accounts for personal budgeting?
;; This bot was not intended for a full-featured accounting.
(defn- is-chat-for-group-accounting?
"Determines the use case for a chat by the number of its members."
[chat-members-count]
(and (some? chat-members-count) ;; a private chat with the bot
(>= chat-members-count min-chat-members-for-group-accounting)))
;; MESSAGE TEMPLATES & CALLBACK DATA
(def ^:private cd-back "<back>")
(def ^:private cd-undo "<undo>")
(def ^:private cd-done "<done>")
(def ^:private cd-accounts "<accounts>")
(def ^:private cd-accounts-create "<accounts/create>")
(def ^:private cd-accounts-rename "<accounts/rename>")
(def ^:private cd-accounts-revoke "<accounts/revoke>")
(def ^:private cd-accounts-reinstate "<accounts/reinstate>")
(def ^:private cd-expense-items "<expense_items>")
(def ^:private cd-expense-items-create "<expense_items/create>")
(def ^:private cd-expense-items-redesc "<expense_items/redesc>")
(def ^:private cd-expense-items-recode "<expense_items/recode>")
(def ^:private cd-expense-items-delete "<expense_items/delete>")
(def ^:private cd-shares "<shares>")
;; TODO: What about <language_and_currency>?
(def ^:private id-separator "::")
(def ^:private cd-group-chat-prefix (str "gc" id-separator))
(def ^:private cd-expense-item-prefix (str "ei" id-separator))
(def ^:private cd-account-prefix (str "ac" id-separator))
(def ^:private cd-account-type-prefix (str "at" id-separator))
(def ^:private cd-digits-set #{"1" "2" "3" "4" "5" "6" "7" "8" "9" "0" ","})
(def ^:private cd-ar-ops-set #{"+" "–"})
(def ^:private cd-cancel "C")
(def ^:private cd-clear "<-")
(def ^:private cd-enter "OK")
;; TODO: Proper localization (with fn).
(def ^:private back-button-text "<< назад")
(def ^:private undo-button-text "Отмена")
(def ^:private done-button-text "Готово")
(def ^:private unknown-failure-text "Что-то пошло не так.")
(def ^:private default-general-acc-name "общие расходы")
(def ^:private account-types-names {:acc-type/personal {:single "Личный" :plural "Личные"}
:acc-type/group {:single "Групповой" :plural "Групповые"}
:acc-type/general {:single "Общий"}})
(def ^:private select-account-txt "Выберите счёт:")
(def ^:private select-payer-account-txt "Выберите тех, кто понёс расход:")
;; "Error while saving data. Please, try again later." (en)
(def ^:private data-persistence-error "Ошибка при сохранении данных. Пожалуйста, повторите попытку позже.")
(def ^:private no-debtor-account-error "Нет возможности выбрать счёт для данного расхода.")
(def ^:private no-group-to-record-error "Нет возможности выбрать группу для записи расходов.")
(defn- join-into-text
([strings-or-colls]
(join-into-text strings-or-colls "\n\n"))
([strings-or-colls sep]
(str/join sep (flatten strings-or-colls))))
(defn- format-list
([items-coll]
(format-list items-coll nil))
([items-coll {:keys [bullet item-sep text-map-fn escape-md?]
:or {bullet "•"
item-sep "\n"
text-map-fn identity}
:as _?opts}]
(let [list-str (->> items-coll
(map #(str (when (some? bullet)
(str bullet " "))
(text-map-fn %)))
(str/join item-sep))]
(if escape-md? (md-v2/escape list-str) list-str))))
(defn- format-currency
[amount lang]
(String/format (Locale/forLanguageTag lang)
"%.2f" ;; receives BigDecimal
(to-array [(bigdec amount)])))
;; TODO: Use the newly introduced 'placeholder' option.
(def ^:private force-reply-options
(tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup :force-reply {:selective true})
:parse-mode "MarkdownV2"}))
(defn- build-items-selection-markup
[items-buttons ?extra-buttons]
(let [extra-buttons (when (some? ?extra-buttons)
(for [extra-btn ?extra-buttons]
[extra-btn]))
;; NB: A 'vec' is used to keep extra buttons below the regular ones.
all-kbd-btns (into (vec items-buttons) extra-buttons)]
{:reply-markup (tg-api/build-reply-markup :inline-keyboard all-kbd-btns)}))
(defn- get-select-one-item-markup
([items name-extr-fn key-extr-fn val-extr-fn]
(get-select-one-item-markup items name-extr-fn key-extr-fn val-extr-fn nil))
([items name-extr-fn key-extr-fn val-extr-fn ?extra-buttons]
(let [items-btns (for [item items]
[(tg-api/build-inline-kbd-btn (name-extr-fn item)
(key-extr-fn item)
(val-extr-fn item))])]
(build-items-selection-markup items-btns ?extra-buttons))))
(defn- get-select-multiple-items-markup
([selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn]
(get-select-multiple-items-markup selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn nil))
([selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn
?extra-buttons]
(let [sel-items-btns (for [item selected-items]
[(tg-api/build-inline-kbd-btn (str "✔ " (name-extr-fn item))
(key-extr-fn item)
(val-extr-fn item))])
rem-items-btns (for [item remaining-items]
[(tg-api/build-inline-kbd-btn (name-extr-fn item)
(key-extr-fn item)
(val-extr-fn item))])
all-items-btns (concat sel-items-btns rem-items-btns)]
(build-items-selection-markup all-items-btns ?extra-buttons))))
(defn- get-group-ref-option-id
[group-ref]
(str cd-group-chat-prefix (:id group-ref)))
(defn- group-refs->options
[group-refs]
(get-select-one-item-markup group-refs
:title
(constantly :callback-data)
get-group-ref-option-id))
(defn- get-expense-item-display-value
[[code data]]
(str (str/upper-case code) " (" (:desc data) ")"))
(defn- get-expense-item-option-id
[[code _data]]
(str cd-expense-item-prefix code))
(defn- expense-items->options
[expense-items & extra-buttons]
(get-select-one-item-markup (seq expense-items)
get-expense-item-display-value
(constantly :callback-data)
get-expense-item-option-id
extra-buttons))
(defn- get-account-option-id
[acc]
(str cd-account-prefix (name (:type acc)) id-separator (:id acc)))
(defn- accounts->options
[accounts & extra-buttons]
(get-select-one-item-markup accounts
:name
(constantly :callback-data)
get-account-option-id
extra-buttons))
(defn- get-account-type-option-id
[acc-type]
(str cd-account-type-prefix (name acc-type)))
(defn- account-types->options
[account-types & extra-buttons]
(get-select-one-item-markup account-types
#(get-in account-types-names [% :single])
(constantly :callback-data)
get-account-type-option-id
extra-buttons))
(def ^:private back-button
(tg-api/build-inline-kbd-btn back-button-text :callback-data cd-back))
(defn- get-retry-commands-msg
[commands]
{:type :text
:text (format
(str unknown-failure-text " Пожалуйста, повторите %s %s %s.")
(if (next commands) "команды" "команду")
(->> commands
(map (partial str "/"))
(str/join ", "))
(if (next commands) "по-отдельности" "через какое-то время"))})
(def ^:private retry-resend-message-msg
{:type :text
:text (str unknown-failure-text " Пожалуйста, отправьте сообщение снова.")})
(def ^:private retry-callback-query-notification
{:type :callback
:options {:text (str unknown-failure-text " Пожалуйста, повторите действие.")}})
; group chats
; - basic messages
;; TODO: Make messages texts localizable:
;; - take the ':language_code' of the chat initiator (no personal settings)
;; - externalize texts, keep only their keys (to get them via 'l10n')
(defn- get-introduction-msg
[chat-members-count first-name]
{:type :text
:text (apply format "Привет, %s! Я — бот-бухгалтер. И я призван помочь %s с учётом %s общих расходов.\n
Для того, чтобы начать работу, просто %s на следующее сообщение."
(if (= chat-members-count 2)
[first-name "<NAME>" "<NAME>" "<NAME>"]
["народ" "вам" "ваших" "ответьте каждый"]))})
(defn- get-personal-account-name-request-msg
[existing-chat? ?chat-members]
{:type :text
:text (let [request-txt (md-v2/escape "как будет называться ваш личный счёт?")
part-one (if (some? ?chat-members)
(let [mentions (for [user ?chat-members]
(tg-api/get-user-mention-text user))]
(str (str/join " " mentions) ", " request-txt))
(str/capitalize request-txt))
part-two (md-v2/escape
(if (and existing-chat? (empty? ?chat-members))
"Пожалуйста, проигнорийруте это сообщение, если у вас уже есть личный счёт в данной группе."
"Пожалуйста, ответьте на данное сообщение."))]
(join-into-text [part-one part-two]))
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:force-reply {:selective (some? ?chat-members)})
:parse-mode "MarkdownV2"})})
(defn- get-personal-accounts-left-msg
[count]
{:type :text
:text (format "Ожидаем остальных... Осталось %s." count)})
(defn- get-bot-readiness-msg
[bot-username]
{:type :text
:text "Я готов к ведению учёта. Давайте же начнём!"
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Перейти в чат для ввода расходов"
:url (str "https://t.me/" bot-username))]])})})
; - settings
(defn- get-settings-msg
[first-time?]
{:type :text
;; TODO: Shorten this text and spread its content between the mgmt views?
:text (format "%s можно настроить, чтобы учитывались:
- счета — не только личные, но и групповые;
- статьи расходов — подходящие по смыслу и удобные вам;
- доли — для статей расходов и ситуаций, когда 50/50 вам не подходит." ;; "По умолчанию равны для любых счетов и статей расходов."
(if (true? first-time?) "Также меня" "Меня"))
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Счета" :callback-data cd-accounts)
(tg-api/build-inline-kbd-btn "Статьи" :callback-data cd-expense-items)
(tg-api/build-inline-kbd-btn "Доли" :callback-data cd-shares)]])})})
(def ^:private successful-changes-msg
{:type :text
:text "Изменения внесены успешно."})
(def ^:private canceled-changes-msg
{:type :text
:text "Внесение изменений отменено."})
; - accounts mgmt
(defn- get-accounts-mgmt-options-msg
[accounts-by-type]
{:type :text
:text (join-into-text
["Список счетов данной группы:"
(map (fn [[acc-type accounts]]
(case acc-type
(:acc-type/personal :acc-type/group)
(str (md-v2/format-bold (get-in account-types-names [acc-type :plural])) "\n"
(format-list accounts {:text-map-fn :name
:escape-md? true}))
:acc-type/general
(md-v2/format-bold "Счёт для общих расходов")))
accounts-by-type)
"Выберите, что вы хотите сделать:"])
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Создать новый" :callback-data cd-accounts-create)]
[(tg-api/build-inline-kbd-btn "Переименовать" :callback-data cd-accounts-rename)]
[(tg-api/build-inline-kbd-btn "Упразднить" :callback-data cd-accounts-revoke)]
[(tg-api/build-inline-kbd-btn "Восстановить" :callback-data cd-accounts-reinstate)]
[back-button]])
:parse-mode "MarkdownV2"})})
(defn- get-account-selection-msg
([accounts txt]
(get-account-selection-msg accounts txt nil))
([accounts txt ?extra-buttons]
{:pre [(seq accounts)]}
{:type :text
:text txt
:options (tg-api/build-message-options
(apply accounts->options accounts ?extra-buttons))}))
(defn- get-account-type-selection-msg
[account-types extra-buttons]
{:pre [(seq account-types)]}
{:type :text
;; Group account is used to share the expenses between the group members.
;; Personal account is needed in case the person is not present in Telegram.
:text (join-into-text
["Какие счета для чего нужны?"
(str (md-v2/format-bold (get-in account-types-names [:acc-type/group :single])) " — "
(md-v2/escape "используется для распределения расходов между членами группы."))
(str (md-v2/format-bold (get-in account-types-names [:acc-type/personal :single])) " — "
(md-v2/escape "используется в случае, если человека нет в Telegram, но учитывать его при расчётах нужно."))
"Выберите тип счёта:"])
:options (tg-api/build-message-options
(merge (apply account-types->options account-types extra-buttons)
{:parse-mode "MarkdownV2"}))})
(defn- get-new-account-name-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", как бы вы хотели назвать новый счёт?"))
:options force-reply-options})
(defn- get-the-account-name-is-already-taken-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", данное имя счёта уже занято. Выберите другое имя."))
:options force-reply-options})
(defn- get-group-members-selection-msg
[user selected remaining]
(let [extra-buttons [(tg-api/build-inline-kbd-btn undo-button-text :callback-data cd-undo)
(tg-api/build-inline-kbd-btn done-button-text :callback-data cd-done)]]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", выберите члена(ов) группы:"))
:options (tg-api/build-message-options
(merge (get-select-multiple-items-markup selected remaining
:name
(constantly :callback-data)
get-account-option-id
extra-buttons)
{:parse-mode "MarkdownV2"}))}))
(defn- get-new-group-members-msg
[acc-names]
{:pre [(seq acc-names)]}
{:type :text
:text (str "Члены новой группы:\n"
(format-list acc-names))})
(def ^:private no-group-members-selected-notification
{:type :callback
:options {:text "Не выбрано ни одного участника группы"}})
(defn- get-account-rename-request-msg
[user acc-name]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", как бы вы хотели переименовать счёт \"" acc-name "\"?")))
:options force-reply-options})
(def ^:private no-eligible-accounts-notification
{:type :callback
:options {:text "Подходящих счетов не найдено"}})
; - expense items mgmt
(defn- get-expense-items-mgmt-options-msg
[expense-items]
(let [expense-items-seq (seq expense-items)]
{:type :text
:text (if expense-items-seq
(join-into-text
["Список статей расходов:"
(format-list expense-items-seq {:text-map-fn get-expense-item-display-value
:escape-md? true})
"Выберите, что вы хотите сделать:"])
(md-v2/escape "Статьи расходов не заданы."))
:options (let [action-btns (cond-> [[(tg-api/build-inline-kbd-btn "Добавить новую" :callback-data cd-expense-items-create)]]
(some? expense-items-seq)
(conj [(tg-api/build-inline-kbd-btn "Изменить описание" :callback-data cd-expense-items-redesc)]
[(tg-api/build-inline-kbd-btn "Изменить код" :callback-data cd-expense-items-recode)]
[(tg-api/build-inline-kbd-btn "Удалить" :callback-data cd-expense-items-delete)]))]
(tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard (conj action-btns [back-button]))
:parse-mode "MarkdownV2"}))}))
(defn- get-new-expense-item-desc-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", как бы вы описали новую статью расходов? Что в неё входит?"))
:options force-reply-options})
(defn- get-new-expense-item-code-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", придумайте кодовое обозначение для данной статью расходов. Это может быть простой текст, например \"пр\" для продуктов, или эмодзи, например ☕️ для еды вне дома."))
:options force-reply-options})
(defn- get-the-expense-item-code-is-already-used-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", данный код уже используется для другой статьи расходов. Выберите другой код."))
:options force-reply-options})
(defn- get-the-expense-item-cannot-be-deleted-msg
[exp-it-code exp-it-desc]
{:type :text
:text (format "Статья расходов \"%s (%s)\" не может быть удалена, поскольку была использована ранее."
exp-it-code exp-it-desc)})
(def ^:private no-eligible-expense-items-notification
{:type :callback
:options {:text "Подходящих статей расходов не найдено"}})
(defn- get-expense-item-redesc-request-msg
[user exp-it-desc]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", как бы вы по-другому описали статью расходов \"" exp-it-desc "\"?")))
:options force-reply-options})
(defn- get-expense-item-recode-request-msg
[user exp-it-desc]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", задайте новый код для статьи расходов \"" exp-it-desc "\".")))
:options force-reply-options})
;; TODO: Add messages for 'shares' here.
; - expenses
(defn- get-new-expense-msg
[expense-amount expense-details payer-acc-name debtor-acc-name]
(let [formatted-amount (format-currency expense-amount "ru")
title-txt (when (some? payer-acc-name)
(str (md-v2/format-bold (md-v2/escape payer-acc-name)) "\n"))
details-txt (->> [(str formatted-amount "₽")
debtor-acc-name
expense-details]
(filter some?)
(str/join " / ")
md-v2/escape)]
{:type :text
:text (str title-txt details-txt)
:options (tg-api/build-message-options
{:parse-mode "MarkdownV2"})}))
; - warnings
(def ^:private waiting-for-user-input-notification
{:type :callback
:options {:text "Ожидание ответа пользователя в чате"}})
(def ^:private waiting-for-other-user-notification
{:type :callback
:options {:text "Ответ ожидается от другого пользователя"}})
(def ^:private message-already-in-use-notification
{:type :callback
:options {:text "С этим сообщением уже взаимодействуют"}})
(def ^:private ignored-callback-query-notification
{:type :callback
:options {:text "Запрос не может быть обработан"}})
; private chats
(defn- get-private-introduction-msg
[first-name]
{:type :text
:text (str "Привет, " first-name "! Чтобы добавить новый расход просто напиши мне сумму.")})
(def ^:private invalid-input-msg
{:type :text
:text "Пожалуйста, введите число. Например, \"145,99\"."})
(def ^:private inline-calculator-markup
(tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "7" :callback-data "7")
(tg-api/build-inline-kbd-btn "8" :callback-data "8")
(tg-api/build-inline-kbd-btn "9" :callback-data "9")
(tg-api/build-inline-kbd-btn "C" :callback-data cd-cancel)]
[(tg-api/build-inline-kbd-btn "4" :callback-data "4")
(tg-api/build-inline-kbd-btn "5" :callback-data "5")
(tg-api/build-inline-kbd-btn "6" :callback-data "6")
(tg-api/build-inline-kbd-btn "+" :callback-data "+")]
[(tg-api/build-inline-kbd-btn "1" :callback-data "1")
(tg-api/build-inline-kbd-btn "2" :callback-data "2")
(tg-api/build-inline-kbd-btn "3" :callback-data "3")
(tg-api/build-inline-kbd-btn "–" :callback-data "–")]
[(tg-api/build-inline-kbd-btn "0" :callback-data "0")
(tg-api/build-inline-kbd-btn "," :callback-data ",")
(tg-api/build-inline-kbd-btn "←" :callback-data cd-clear)
(tg-api/build-inline-kbd-btn "OK" :callback-data cd-enter)]]))
(defn- get-interactive-input-msg
([text]
(get-interactive-input-msg text nil))
([text ?extra-opts]
{:type :text
:text (str (md-v2/escape "Новый расход:\n= ") text)
:options (tg-api/build-message-options
(merge {:parse-mode "MarkdownV2"} ?extra-opts))}))
(defn- get-inline-calculator-msg
[user-input]
(get-interactive-input-msg
(md-v2/escape (str user-input "_"))
{:reply-markup inline-calculator-markup}))
(defn- get-interactive-input-success-msg
[amount]
(get-interactive-input-msg
(md-v2/escape (format-currency amount "ru"))))
(def ^:private interactive-input-disclaimer-msg
{:type :text
:text "Введите /cancel, чтобы выйти из режима калькуляции и ввести данные вручную."})
(def ^:private invalid-input-notification
{:type :callback
:options {:text "Ошибка в выражении! Вычисление невозможно."}})
(defn- get-added-to-new-group-msg
[chat-title]
{:type :text
:text (str "Вас добавили в группу \"" chat-title "\".")})
(defn- get-removed-from-group-msg
[chat-title]
{:type :text
:text (str "Вы покинули группу \"" chat-title "\".")})
(defn- get-group-selection-msg
[group-refs]
{:pre [(seq group-refs)]}
{:type :text
:text "Выберите, к какой группе отнести расход:"
:options (tg-api/build-message-options
(group-refs->options group-refs))})
(defn- get-expense-item-selection-msg
([expense-items]
(get-expense-item-selection-msg expense-items nil))
([expense-items ?extra-buttons]
{:pre [(seq expense-items)]}
{:type :text
:text "Выберите статью расходов:"
:options (tg-api/build-message-options
(apply expense-items->options expense-items ?extra-buttons))}))
(defn- get-expense-manual-description-msg
[user-name]
{:type :text
:text (str user-name ", опишите расход в двух словах:")
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup :force-reply)})})
(def ^:private expense-added-successfully-msg
{:type :text
:text "Запись успешно внесена в ваш гроссбух."})
(defn- get-failed-to-add-new-expense-msg
[reason]
{:type :text
:text (str/join " " ["Не удалось добавить новый расход." reason])})
;; AUXILIARY FUNCTIONS
(defn get-datetime-in-tg-format
[]
(quot (System/currentTimeMillis) 1000))
(defn- is-failure?
"Checks if something resulted in a failure."
[res]
(and (keyword? res)
(= "failure" (namespace res))))
;; - CHATS
(defn- does-chat-exist?
[chat-id]
(contains? (get-bot-data) chat-id))
(def ^:private default-chat-state :initial)
(defn- setup-new-chat!
[chat-id new-chat]
(when-not (does-chat-exist? chat-id) ;; petty RC
(let [new-chat (chats/create! (assoc new-chat :id chat-id))]
(update-bot-data! assoc chat-id new-chat)
new-chat)))
;; TODO: Add a logical ID attr, e.g. UID, to track all group versions.
(defn- setup-new-group-chat!
[chat-id chat-title chat-members-count]
(setup-new-chat! chat-id {:type :chat-type/group
:data {:state default-chat-state
:title chat-title
:members-count chat-members-count
:accounts {:last-id -1}}}))
(defn- setup-new-supergroup-chat!
[chat-id migrate-from-id]
(setup-new-chat! chat-id {:type :chat-type/supergroup
:data migrate-from-id}))
(defn- setup-new-private-chat!
[chat-id group-chat-id]
(setup-new-chat! chat-id {:type :chat-type/private,
:data {:state default-chat-state
:groups #{group-chat-id}}}))
(defn- get-real-chat-id
"Returns the chat 'id' with built-in insurance for the 'supergroup' chats."
([chat-id]
(get-real-chat-id (get-bot-data) chat-id))
([bot-data chat-id]
(let [chat (get bot-data chat-id)]
(if (= :chat-type/supergroup (:type chat))
(:data chat) ;; target group chat-id
chat-id))))
(defn- get-chat-data
"Returns the JSON data associated with a chat with the specified 'chat-id'."
([chat-id]
(get-chat-data (get-bot-data) chat-id))
([bot-data chat-id]
(when-let [real-chat-id (get-real-chat-id bot-data chat-id)]
(get-in bot-data [real-chat-id :data]))))
(defn- -update-chat!
[chat-to-upd]
(if (chats/update! chat-to-upd)
(:data chat-to-upd)
(throw (ex-info "Failed to persist an updated chat" {:chat chat-to-upd}))))
(defn- update-chat-data!
[chat-id upd-fn & upd-fn-args]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
bot-data (apply update-bot-data!
update-in [real-chat-id :data] upd-fn upd-fn-args)
upd-chat (get bot-data real-chat-id)]
(-update-chat! upd-chat)))
(defn- conditionally-update-chat-data!
[chat-id pred upd-fn & upd-fn-args]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
bot-data (apply conditionally-update-bot-data!
#(pred (get-in % [real-chat-id :data]))
update-in [real-chat-id :data] upd-fn upd-fn-args)
upd-chat (get bot-data real-chat-id)]
(when (some? upd-chat)
(-update-chat! upd-chat))))
(defn- assoc-in-chat-data!
[chat-id [key & ks] ?value]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
full-path (concat [real-chat-id :data key] ks)
bot-data (if (nil? ?value)
(update-bot-data! update-in (butlast full-path)
dissoc (last full-path))
(update-bot-data! assoc-in full-path ?value))
upd-chat (get bot-data real-chat-id)]
(-update-chat! upd-chat)))
(defn- get-chat-state
"Determines the state of the given chat. Returns 'nil' in case the group chat
or user is unknown (the input is 'nil') and a valid default in case there is
no preset state.
NB: Be aware that calling this function, e.g. during a state change,
may cause a race condition (RC) and result in an obsolete value."
[chat-data]
(get chat-data :state
(when (some? chat-data) default-chat-state)))
(defn- change-chat-state!
[chat-id chat-type-states new-state]
{:pre [(does-chat-exist? chat-id)]}
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [curr-state (get-chat-state chat-data)
possible-new-states (or (-> chat-type-states curr-state :to)
(-> chat-type-states curr-state))]
(if (contains? possible-new-states new-state)
(let [state-init-fn (-> chat-type-states new-state :init-fn)]
(cond-> chat-data
(some? state-init-fn) (state-init-fn)
:and-most-importantly (assoc :state new-state)))
(do
(log/errorf "Failed to change state to '%s' for chat=%s with current state '%s'"
new-state chat-id curr-state)
chat-data)))))]
(get-chat-state updated-chat-data)))
;; - BOT STATUS
(defn- does-bot-manage-the-chat?
[{?chat-id :chat-id ?chat-state :chat-state}]
{:pre [(or (some? ?chat-id) (some? ?chat-state))]}
(let [chat-state (or ?chat-state
(and (does-chat-exist? ?chat-id)
(get-chat-state (get-chat-data ?chat-id))))]
(= :managed chat-state)))
(defn- is-bot-evicted-from-chat?
[chat-id]
(and (does-chat-exist? chat-id)
(= :evicted (get-chat-state (get-chat-data chat-id)))))
;; - ACCOUNTS
(defn- ->general-account
[id name created members]
{:id id
:type :acc-type/general
:name name
:created created
:members (set members)})
(defn- ->personal-account
[id name created ?user-id ?msg-id]
(cond-> {:id id
:type :acc-type/personal
:name name
:created created}
(some? ?user-id) (assoc :user-id ?user-id)
(some? ?msg-id) (assoc :msg-id ?msg-id)))
(defn- ->group-account
[id name created created-by members]
{:id id
:type :acc-type/group
:name name
:created created
:created-by created-by
:members (set members)})
(defn- is-account-revoked?
[acc]
(contains? acc :revoked))
(defn- is-account-active?
[acc]
(not (is-account-revoked? acc)))
;; - CHATS > ACCOUNTS
(defn- get-members-count
[chat-data]
(:members-count chat-data))
(defn- update-members-count!
[chat-id update-fn]
(update-chat-data! chat-id
update :members-count update-fn))
(defn- get-accounts-of-type
([chat-data acc-type]
(map val (get-in chat-data [:accounts acc-type])))
([chat-data acc-type ?filter-pred]
(cond->> (get-accounts-of-type chat-data acc-type)
(some? ?filter-pred) (filter ?filter-pred))))
(defn- get-account-by-id
[chat-data acc-type acc-id]
(get-in chat-data [:accounts acc-type acc-id]))
(defn- get-accounts-next-id
[chat-data]
(-> chat-data :accounts :last-id inc))
(defn- find-account-by-name
[chat-data acc-type acc-name]
;; NB: Personal and group account names must be unique.
(first (get-accounts-of-type chat-data acc-type
#(= (:name %) acc-name))))
(defn- create-named-account!
"Attempts to create a named type account with a name uniqueness check."
[chat-id acc-type acc-name constructor-fn]
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-account-by-name % acc-type acc-name))
(fn [chat-data]
(let [next-id (get-accounts-next-id chat-data)
upd-accounts-next-id #(assoc-in % [:accounts :last-id] next-id)]
(constructor-fn (upd-accounts-next-id chat-data) next-id))))]
(if (some? updated-chat-data)
(find-account-by-name updated-chat-data acc-type acc-name)
:failure/the-account-name-is-already-taken)))
;; - CHATS > ACCOUNTS > GENERAL
(defn- get-current-general-account
"Retrieves the current (the one that will be used) account of 'general' type
from the provided chat data.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact '?filter-pred'.
In the latter case, the most recent general account will be returned."
([chat-data]
(get-current-general-account chat-data is-account-active?))
([chat-data ?filter-pred]
(let [gen-accs (get-accounts-of-type chat-data
:acc-type/general
?filter-pred)]
(if (< 1 (count gen-accs))
(do
(log/warnf "There is more than 1 suitable general account in chat=%s"
(:id chat-data)) ;; it might be ok for custom 'filter-pred'
(apply max-key :id gen-accs))
(first gen-accs)))))
(defn- create-general-account!
[chat-id created-dt & {:keys [remove-member add-member] :as _opts}]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [old-gen-acc (get-current-general-account chat-data)
old-members (->> (get-accounts-of-type chat-data
:acc-type/personal
is-account-active?)
(map :id)
set)
new-members (cond-> old-members
(some? add-member) (conj add-member)
(some? remove-member) (disj remove-member))
upd-old-general-acc-fn
(fn [cd]
(if (some? old-gen-acc)
(assoc-in cd
[:accounts :acc-type/general (:id old-gen-acc) :revoked]
created-dt)
cd))
add-new-general-acc-fn
(fn [cd]
;; IMPLEMENTATION NOTE:
;; Here the chat 'members-count' have to already be updated!
(if (is-chat-for-group-accounting? (get-members-count cd))
(let [next-id (get-accounts-next-id cd)
acc-name (:name old-gen-acc default-general-acc-name)
new-general-acc (->general-account
next-id acc-name created-dt new-members)]
(-> cd
(assoc-in [:accounts :last-id] next-id)
(assoc-in [:accounts :acc-type/general next-id] new-general-acc)))
cd))]
(-> chat-data
upd-old-general-acc-fn
add-new-general-acc-fn))))]
(get-current-general-account updated-chat-data)))
;; - CHATS > ACCOUNTS > PERSONAL
(defn- get-personal-account-id
"A convenient way to get both user and virtual accounts ID."
[chat-data {?user-id :user-id ?acc-name :name :as _ids}]
{:pre [(or (some? ?user-id) (some? ?acc-name))]}
(if (some? ?user-id)
(get-in chat-data [:user-account-mapping ?user-id])
(:id (find-account-by-name chat-data :acc-type/personal ?acc-name))))
(defn- set-personal-account-id
[chat-data user-id pers-acc-id]
{:pre [(some? user-id)]}
(assoc-in chat-data [:user-account-mapping user-id] pers-acc-id))
(defn- get-personal-account
[chat-data {?user-id :user-id ?acc-name :name ?acc-id :id :as ids}]
{:pre [(or (some? ?user-id) (some? ?acc-name) (some? ?acc-id))]}
(cond
(some? ?acc-id)
(get-account-by-id chat-data :acc-type/personal ?acc-id)
(some? ?acc-name)
(find-account-by-name chat-data :acc-type/personal ?acc-name)
(some? ?user-id)
(let [pers-acc-id (get-personal-account-id chat-data ids)]
(get-account-by-id chat-data :acc-type/personal pers-acc-id))))
(defn- create-personal-account!
[chat-id acc-name created-dt & {?user-id :user-id ?first-msg-id :first-msg-id :as _opts}]
(if (or (nil? ?user-id)
(let [pers-acc (get-personal-account (get-chat-data chat-id) {:user-id ?user-id})] ;; petty RC
(or (nil? pers-acc) (is-account-revoked? pers-acc))))
(create-named-account!
chat-id :acc-type/personal acc-name
(fn [chat-data acc-id]
(let [pers-acc (->personal-account acc-id acc-name created-dt
?user-id ?first-msg-id)]
(cond-> (assoc-in chat-data [:accounts :acc-type/personal acc-id] pers-acc)
(some? ?user-id) (set-personal-account-id ?user-id acc-id)))))
:failure/user-already-has-an-active-account))
;; - CHATS > ACCOUNTS > GROUP
(defn- get-group-account
[chat-data {?acc-name :name ?acc-id :id :as _ids}]
{:pre [(or (some? ?acc-name) (some? ?acc-id))]}
(cond
(some? ?acc-id)
(get-account-by-id chat-data :acc-type/group ?acc-id)
(some? ?acc-name)
(find-account-by-name chat-data :acc-type/group ?acc-name)))
(defn- create-group-account!
[chat-id acc-name created-dt created-by members-ids]
(create-named-account!
chat-id :acc-type/group acc-name
(fn [chat-data acc-id]
(let [group-acc (->group-account acc-id acc-name created-dt created-by members-ids)]
(assoc-in chat-data [:accounts :acc-type/group acc-id] group-acc)))))
;; - CHATS > BOT MESSAGES
(defn- get-bot-msg
[chat-data msg-id]
(get-in chat-data [:bot-messages msg-id]))
(defn- set-bot-msg!
[chat-id msg-id {:keys [type] :as ?props}]
{:pre [(or (nil? ?props) (some? type))]}
(assoc-in-chat-data! chat-id [:bot-messages msg-id] ?props))
(defn- find-bot-messages
[chat-data {:keys [type to-user] :as _props}]
(cond->> (:bot-messages chat-data)
(some? type) (filter #(= type (-> % val :type)))
(some? to-user) (filter #(= to-user (-> % val :to-user)))))
(defn- drop-bot-msg!
[chat-id {:keys [type to-user] :as props}]
{:pre [(or (some? type) (some? to-user))]}
(let [to-drop (map key (find-bot-messages (get-chat-data chat-id) props))]
(update-chat-data! chat-id
update-in [:bot-messages] #(apply dissoc % to-drop))
to-drop))
(defn- get-original-bot-msg
[chat-id reply-msg]
;; NB: There's always only one original msg.
(->> (:bot-messages (get-chat-data chat-id))
(filter #(tg-api/is-reply-to? (key %) reply-msg))
(map (fn [[k v]] (assoc v :msg-id k)))
first))
(defn- check-bot-msg
[bot-msg {:keys [type to-user] :as props}]
{:pre [(or (some? type) (some? to-user))]}
(when (some? bot-msg)
(every? #(= (val %) (-> % key bot-msg)) props)))
(defn- change-bot-msg-state!
[chat-id msg-id msg-type-states new-state]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [bot-msg (get-bot-msg chat-data msg-id)
curr-state (:state bot-msg)]
(if (or (nil? curr-state) ;; to set an initial state
(contains? (get msg-type-states curr-state) new-state))
(assoc-in chat-data [:bot-messages msg-id :state] new-state)
(do
(log/errorf "Failed to change state from '%s' to '%s' for message=%s in chat=%s"
curr-state new-state msg-id chat-id)
chat-data)))))]
(:state (get-bot-msg updated-chat-data msg-id))))
;; - CHATS > GROUP CHAT
(defn- get-chat-title
[chat-data]
(:title chat-data))
(defn- set-chat-title!
[chat-id chat-title]
(assoc-in-chat-data! chat-id [:title] chat-title))
;; - CHATS > GROUP CHAT > EXPENSE ITEMS
;; TODO: Optionally sort them according popularity.
(defn- get-group-chat-expense-items
[chat-data]
(:expense-items chat-data))
(defn- find-expense-item
[chat-data exp-it-code]
(get (get-group-chat-expense-items chat-data) exp-it-code))
(defn- create-group-chat-expense-item!
[chat-id {:keys [exp-it-code exp-it-data]}]
{:pre [(some? exp-it-code) (some? exp-it-data)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-expense-item % exp-it-code))
#(assoc-in % [:expense-items exp-it-code] exp-it-data))]
(if (some? updated-chat-data)
(find-expense-item updated-chat-data exp-it-code)
:failure/the-expense-item-code-is-already-used)))
(defn- update-group-chat-expense-item!
[chat-id {:keys [exp-it-code exp-it-data]}]
{:pre [(some? exp-it-code) (some? exp-it-data)]}
(let [updated-chat-data
(update-chat-data!
chat-id
update-in [:expense-items exp-it-code] merge exp-it-data)]
(find-expense-item updated-chat-data exp-it-code)))
(defn- change-group-chat-expense-item-code!
[chat-id {:keys [exp-it-code new-exp-it-code]}]
{:pre [(some? exp-it-code) (some? new-exp-it-code)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-expense-item % new-exp-it-code))
(fn [chat-data]
(-> chat-data
(update :expense-items dissoc exp-it-code)
(assoc-in [:expense-items new-exp-it-code]
(get-in chat-data [:expense-items exp-it-code])))))]
(if (some? updated-chat-data)
(find-expense-item updated-chat-data new-exp-it-code)
:failure/the-expense-item-code-is-already-used)))
(defn- can-expense-item-be-deleted?
[[_code data]]
(not (and (contains? data :pops)
(< 0 (:pops data)))))
(defn- delete-group-chat-expense-item!
[chat-id exp-it-to-delete]
{:pre [(some? exp-it-to-delete)]}
(let [exp-it-code (first exp-it-to-delete)
updated-chat-data
(conditionally-update-chat-data!
chat-id
#(let [exp-it (find-expense-item % exp-it-code)]
(can-expense-item-be-deleted? [exp-it-code exp-it]))
#(update % :expense-items dissoc exp-it-code))]
(if (some? updated-chat-data)
true
:failure/the-expense-item-cannot-be-deleted)))
(defn- data->expense-item
"Retrieves a group chat's expense item by parsing the callback button data."
[callback-btn-data chat-data]
(let [exp-it-code (str/replace-first callback-btn-data cd-expense-item-prefix "")]
[exp-it-code (find-expense-item chat-data exp-it-code)]))
;; - CHATS > GROUP CHAT > ACCOUNTS
(def ^:private all-account-types
[:acc-type/personal :acc-type/group :acc-type/general])
(defn- get-group-chat-accounts
"Retrieves accounts of all or specific types (if the 'acc-types' is present)
for a group chat with the specified 'chat-id'.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact 'filter-pred'."
;; TODO: Sort them according popularity.
([chat-id]
(get-group-chat-accounts chat-id
{:acc-types all-account-types}))
([chat-id {:keys [acc-types filter-pred sort-by-popularity]
:or {acc-types all-account-types
filter-pred is-account-active?}}]
(if (< 1 (count acc-types))
;; multiple types
(->> acc-types
(mapcat #(get-group-chat-accounts chat-id
{:acc-types [%]
:filter-pred filter-pred})))
;; single type
(when-let [chat-data (get-chat-data chat-id)]
(get-accounts-of-type chat-data (first acc-types) filter-pred)))))
(defn- get-group-chat-accounts-by-type
"Retrieves accounts, grouped in a map by account type, for a group chat with
the specified 'chat-id'.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact '?filter-pred'."
([chat-id]
(get-group-chat-accounts-by-type chat-id is-account-active?))
([chat-id ?filter-pred]
(group-by :type
(get-group-chat-accounts chat-id
{:acc-types all-account-types
:filter-pred ?filter-pred}))))
(defn- is-not-virtual-member?
[acc]
(and (is-account-active? acc)
(some? (:user-id acc))))
(defn- get-number-of-missing-personal-accounts
"Returns the number of missing personal accounts in a group chat,
which have to be created before the group chat is ready for the
expenses accounting."
[chat-id]
(let [chat-members-count (get-members-count (get-chat-data chat-id))
existing-pers-accs (->> {:acc-types [:acc-type/personal]
:filter-pred is-not-virtual-member?}
(get-group-chat-accounts chat-id)
count)]
(- chat-members-count existing-pers-accs 1)))
(defn- is-group-acc-member?
[chat-id group-acc user-id]
(let [chat-data (get-chat-data chat-id)
pers-acc-id (get-personal-account-id chat-data {:user-id user-id})
group-acc-members (:members group-acc)]
(contains? group-acc-members pers-acc-id)))
(defn- all-group-acc-members-are-inactive?
[chat-id group-acc]
(let [group-acc-members (:members group-acc)]
(->> {:acc-types [:acc-type/personal]
:filter-pred #(and (is-account-active? %)
(contains? group-acc-members (:id %)))}
(get-group-chat-accounts chat-id)
empty?)))
(defn- can-rename-account?
[chat-id user-id]
(fn [acc]
(and (is-account-active? acc)
(or (and (= :acc-type/personal (:type acc))
(contains? #{user-id nil} (:user-id acc)))
(and (= :acc-type/group (:type acc))
(or (= (:created-by acc) user-id)
(is-group-acc-member? chat-id acc user-id)
(all-group-acc-members-are-inactive? chat-id acc)))))))
(defn- can-revoke-account?
[chat-id user-id]
(fn [acc]
(and (is-account-active? acc)
(or (and (= :acc-type/personal (:type acc))
(not= (:user-id acc) user-id))
(and (= :acc-type/group (:type acc))
(or (= (:created-by acc) user-id)
(is-group-acc-member? chat-id acc user-id)
(all-group-acc-members-are-inactive? chat-id acc)))))))
(defn- can-reinstate-account?
[_chat-id _user-id]
(fn [acc]
(is-account-revoked? acc)))
(defn- get-group-chat-account
[chat-data {acc-type :type :as props}]
(case acc-type
:acc-type/personal
(get-personal-account chat-data props)
:acc-type/group
(get-group-account chat-data props)
:acc-type/general
(get-current-general-account chat-data)))
(defn- is-group-chat-eligible-for-selection?
"Checks the ability of a specified user to select a given group chat."
[chat-id user-id]
(let [chat-data (get-chat-data chat-id)
pers-acc (get-group-chat-account chat-data {:type :acc-type/personal
:user-id user-id})]
(is-account-active? pers-acc)))
(defn- data->account
"Retrieves a group chat's account by parsing the callback button data."
[callback-btn-data chat-data]
(let [account (str/replace-first callback-btn-data cd-account-prefix "")
account-path (str/split account (re-pattern id-separator))]
(get-group-chat-account chat-data
{:type (keyword "acc-type" (nth account-path 0))
:id (u-nums/parse-int (nth account-path 1))})))
(defn- create-group-chat-account!
[chat-id {:keys [acc-type acc-name created-dt created-by members]}]
{:pre [(some? acc-type) (some? acc-name) (some? created-dt)]}
(case acc-type
:acc-type/personal (when-some [pers-acc (create-personal-account! chat-id acc-name created-dt)]
(create-general-account! chat-id created-dt)
pers-acc)
:acc-type/group (let [members-ids (map :id members)]
(create-group-account! chat-id acc-name created-dt created-by members-ids))))
(defn- change-group-chat-account-name!
[chat-id {:keys [acc-type acc-id new-acc-name]}]
{:pre [(some? acc-type) (some? acc-id) (some? new-acc-name)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-account-by-name % acc-type new-acc-name))
assoc-in [:accounts acc-type acc-id :name] new-acc-name)]
(if (some? updated-chat-data)
(get-group-chat-account updated-chat-data {:type acc-type
:id acc-id})
:failure/the-account-name-is-already-taken)))
(defn- change-account-activity-status!
"Changes the activity status of a personal or group account (just marks it as
'revoked' or removes this mark) and, for personal accounts only, updates the
general account (revokes an existing and creates a new version, if needed)."
[chat-id acc {:keys [revoke? reinstate? datetime] :as _activity_status_upd}]
{:pre [(or (some? revoke?) (some? reinstate?))
(not (and (some? revoke?) (some? reinstate?)))
(contains? #{:acc-type/personal :acc-type/group} (:type acc))]}
(let [acc-id (:id acc)
acc-type (:type acc)
updated-chat-data
(conditionally-update-chat-data!
chat-id
#(some? (get-account-by-id % acc-type acc-id))
(fn [chat-data]
(cond-> chat-data
(true? revoke?)
(assoc-in [:accounts acc-type acc-id :revoked] datetime)
(true? reinstate?)
(update-in [:accounts acc-type acc-id] dissoc :revoked))))]
(when (= :acc-type/personal (:type acc))
(let [member-action (cond
(true? revoke?) :remove-member
(true? reinstate?) :add-member)]
(create-general-account! chat-id datetime member-action acc-id)))
(get-account-by-id updated-chat-data acc-type acc-id)))
;; - CHATS > GROUP CHAT > USER INPUT
(defn- get-user-input-data
[chat-data user-id input-name]
(get-in chat-data [:input user-id input-name]))
(defn- set-user-input-data!
[chat-id user-id input-name ?input-data]
(if (nil? ?input-data)
(update-chat-data! chat-id
update-in [:input user-id] dissoc input-name)
(update-chat-data! chat-id
assoc-in [:input user-id input-name] ?input-data)))
(defn- drop-user-input-data!
[chat-id user-id]
(update-chat-data! chat-id
update-in [:input] dissoc user-id))
(defn- clean-up-chat-data!
[chat-id {:keys [bot-messages input]}]
(doseq [bot-msg bot-messages]
(drop-bot-msg! chat-id bot-msg))
(doseq [user-input input]
(if (contains? user-input :name)
(set-user-input-data! chat-id (:user user-input) (:name user-input) nil)
(drop-user-input-data! chat-id (:user user-input)))))
(defn- release-message-lock!
"Releases the \"input lock\" acquired by the user for the message in chat."
[chat-id user-id msg-id]
(update-chat-data!
chat-id
(fn [chat-data]
(let [user-locked (get-user-input-data chat-data user-id :locked-messages)]
(if (contains? user-locked msg-id)
(update-in chat-data [:input user-id :locked-messages] set/difference #{msg-id})
chat-data))))
nil)
(defn- acquire-message-lock!
"Acquires an \"input lock\" for a specific message in chat and the specified
user, but only if the message has not yet been locked by another user.
IMPLEMENTATION NOTE:
The chat data stores IDs of all locked message for each member in ':input',
so that none of the users can intercept the input of another and interfere
with it. These locks are time-limited — to protect against forgetful users'
inactivity.
Moreover, since the user-specific input data is auto-erased when the user
leaves/is removed from the chat, these message locks will also be released
automatically, and immediately."
[chat-id user-id msg-id]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [all-locked (->> (vals (:input chat-data))
(map :locked-messages)
(reduce #(set/union %1 %2) #{}))
user-locked (get-user-input-data chat-data user-id :locked-messages)]
(if (or (not (contains? all-locked msg-id))
(contains? user-locked msg-id))
(update-in chat-data [:input user-id :locked-messages] set/union #{msg-id})
chat-data))))
user-locked (get-user-input-data updated-chat-data user-id :locked-messages)
has-message-lock? (contains? user-locked msg-id)]
(when has-message-lock?
(go
(<! (timeout (* 5 60 1000))) ;; after 5 minutes
(release-message-lock! chat-id user-id msg-id)))
has-message-lock?))
;; - CHATS > PRIVATE CHAT
(defn- can-write-to-user?
[user-id]
(let [chat-state (-> user-id get-chat-data get-chat-state)]
(and (some? chat-state)
(not= default-chat-state chat-state))))
(defn- get-private-chat-groups
[chat-data]
(get chat-data :groups))
;; NB: This is a design decision to only accumulate groups and not delete them.
(defn- update-private-chat-groups!
([chat-id new-group-chat-id]
(let [updated-chat-data
(update-chat-data! chat-id
update :groups conj new-group-chat-id)]
(get-private-chat-groups updated-chat-data)))
([chat-id old-group-chat-id new-group-chat-id]
(let [swap-ids-fn
(comp set (partial replace {old-group-chat-id new-group-chat-id}))
updated-chat-data (update-chat-data! chat-id
update :groups swap-ids-fn)]
(get-private-chat-groups updated-chat-data))))
(defn- ->group-ref
[group-chat-id group-chat-title]
{:id group-chat-id
:title group-chat-title})
;; - CHATS > PRIVATE CHAT > USER INPUT
(defn- get-user-input
[chat-data]
(get chat-data :user-input))
(defn- update-user-input!
[chat-id {:keys [type data] :as _operation}]
(let [append-digit
(fn [old-val]
(if (or (nil? old-val)
(empty? old-val))
(when (not= "0" data) data)
(str (or old-val "") data)))
append-ar-op
(fn [old-val]
(if (or (nil? old-val)
(empty? old-val))
old-val ;; do not allow
(let [last-char (-> old-val
str/trim
last
str)]
(if (contains? cd-ar-ops-set
last-char)
old-val ;; do not allow
(str (or old-val "")
" " data " ")))))
cancel
(fn [old-val]
(let [trimmed (str/trim old-val)]
(if (< 0 (count trimmed))
(-> trimmed
(subs 0 (dec (count trimmed)))
str/trim)
trimmed)))
clear
(constantly nil)
updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [old-val (get chat-data :user-input)
new-val ((case type
:append-digit append-digit
:append-ar-op append-ar-op
:cancel cancel
:clear clear) old-val)]
(assoc chat-data :user-input new-val))))]
(get-user-input updated-chat-data)))
;; - CHATS > SUPERGROUP CHAT
(defn- migrate-group-chat-to-supergroup!
[chat-id migrate-to-chat-id]
(let [new-chat (setup-new-supergroup-chat! migrate-to-chat-id chat-id)
chat-data (if (some? new-chat)
(:data new-chat)
(get-chat-data chat-id))
group-users (-> chat-data
(get :user-account-mapping)
keys)]
;; NB: Here we iterate only real users, and this is exactly what we need.
(doseq [user-id group-users]
(update-private-chat-groups! user-id chat-id migrate-to-chat-id))))
;; RESPONSES
(def ^:private responses
{:chat-type/group
{:introduction-msg
{:response-fn get-introduction-msg
:response-params [:chat-members-count :first-name]}
:personal-account-name-request-msg
{:response-fn get-personal-account-name-request-msg
:response-params [:existing-chat? :chat-members]}
:personal-accounts-left-msg
{:response-fn get-personal-accounts-left-msg
:response-params [:count]}
:bot-readiness-msg
{:response-fn get-bot-readiness-msg
:response-params [:bot-username]}
:settings-msg
{:response-fn get-settings-msg
:response-params [:first-time?]}
:new-account-name-request-msg
{:response-fn get-new-account-name-request-msg
:response-params [:user]}
:the-account-name-is-already-taken-msg
{:response-fn get-the-account-name-is-already-taken-msg
:response-params [:user]}
:group-members-selection-msg
{:response-fn get-group-members-selection-msg
:response-params [:user :selected :remaining]}
:new-group-members-msg
{:response-fn get-new-group-members-msg
:response-params [:acc-names]}
:account-rename-request-msg
{:response-fn get-account-rename-request-msg
:response-params [:user :acc-name]}
:new-expense-item-desc-request-msg
{:response-fn get-new-expense-item-desc-request-msg
:response-params [:user]}
:new-expense-item-code-request-msg
{:response-fn get-new-expense-item-code-request-msg
:response-params [:user]}
:the-expense-item-code-is-already-used-msg
{:response-fn get-the-expense-item-code-is-already-used-msg
:response-params [:user]}
:the-expense-item-cannot-be-deleted-msg
{:response-fn get-the-expense-item-cannot-be-deleted-msg
:response-params [:exp-it-code :exp-it-desc]}
:expense-item-redesc-request-msg
{:response-fn get-expense-item-redesc-request-msg
:response-params [:user :exp-it-desc]}
:expense-item-recode-request-msg
{:response-fn get-expense-item-recode-request-msg
:response-params [:user :exp-it-desc]}
:successful-changes-msg
{:response-fn (constantly successful-changes-msg)}
:canceled-changes-msg
{:response-fn (constantly canceled-changes-msg)}
:waiting-for-user-input-notification
{:response-fn (constantly waiting-for-user-input-notification)}
:waiting-for-other-user-notification
{:response-fn (constantly waiting-for-other-user-notification)}
:message-already-in-use-notification
{:response-fn (constantly message-already-in-use-notification)}
:no-eligible-accounts-notification
{:response-fn (constantly no-eligible-accounts-notification)}
:no-group-members-selected-notification
{:response-fn (constantly no-group-members-selected-notification)}
:no-eligible-expense-items-notification
{:response-fn (constantly no-eligible-expense-items-notification)}
; message-specific
:settings
{:accounts-mgmt-options-msg
{:response-fn get-accounts-mgmt-options-msg
:response-params [:accounts-by-type]}
:account-type-selection-msg
{:response-fn get-account-type-selection-msg
:response-params [:account-types :extra-buttons]}
:account-selection-msg
{:response-fn get-account-selection-msg
:response-params [:accounts :txt :extra-buttons]}
:expense-items-mgmt-options-msg
{:response-fn get-expense-items-mgmt-options-msg
:response-params [:expense-items]}
:expense-item-selection-msg
{:response-fn get-expense-item-selection-msg
:response-params [:expense-items :extra-buttons]}
:restored-settings-msg
{:response-fn (partial get-settings-msg false)}}}
:chat-type/private
{:private-introduction-msg
{:response-fn get-private-introduction-msg
:response-params [:first-name]}
:inline-calculator-msg
{:response-fn get-inline-calculator-msg
:response-params [:new-user-input]}
:interactive-input-success-msg
{:response-fn get-interactive-input-success-msg
:response-params [:parsed-val]}
:interactive-input-disclaimer-msg
{:response-fn (constantly interactive-input-disclaimer-msg)}
:invalid-input-msg
{:response-fn (constantly invalid-input-msg)}
:group-selection-msg
{:response-fn get-group-selection-msg
:response-params [:group-refs]}
:expense-item-selection-msg
{:response-fn get-expense-item-selection-msg
:response-params [:expense-items]}
:expense-manual-description-msg
{:response-fn get-expense-manual-description-msg
:response-params [:first-name]}
:account-selection-msg
{:response-fn get-account-selection-msg
:response-params [:accounts :txt]}
:new-expense-msg
{:response-fn get-new-expense-msg
:response-params [:expense-amount :expense-details
:payer-acc-name :debtor-acc-name]}
:added-to-new-group-msg
{:response-fn get-added-to-new-group-msg
:response-params [:chat-title]}
:removed-from-group-msg
{:response-fn get-removed-from-group-msg
:response-params [:chat-title]}
:invalid-input-notification
{:response-fn (constantly invalid-input-notification)}
:expense-added-successfully-msg
{:response-fn (constantly expense-added-successfully-msg)}
:failed-to-add-new-expense-msg
{:response-fn get-failed-to-add-new-expense-msg
:response-params [:reason]}}})
;; STATES & STATE TRANSITIONS
;; TODO: Re-write with an existing state machine (FSM) library.
(defn- to-response
[{:keys [response-fn response-params]} ?param-vals]
(when (some? response-fn)
(apply response-fn (map (or ?param-vals {}) response-params))))
(defn- handle-state-transition!
[event state-transitions change-state-fn]
(let [transition-keys (:transition event)
transition (get-in state-transitions transition-keys)
chat-type (first transition-keys)
response-keys (u-coll/collect [chat-type] (:response transition))
response-data (get-in responses response-keys)]
(change-state-fn (:to-state transition))
(to-response response-data (:param-vals event))))
; chat states
;; TODO: There is a serious issue of a chat transition happening right before the exception happens.
;; Both private chats state and group chats' message state are vulnerable to this.
;; Solution: surround all update handlers with transaction boundaries.
(def ^:private group-chat-states
{:initial #{:managed
:evicted}
:managed #{:managed
:evicted}
:evicted #{:managed}})
(def ^:private private-chat-states
{:initial #{:input}
:input {:to #{:group-selection
:expense-detailing
:interactive-input
:input}
:init-fn (fn [chat-data]
(select-keys chat-data [:groups]))}
:interactive-input #{:group-selection
:expense-detailing
:input}
:group-selection #{:expense-detailing
:input}
:expense-detailing #{:account-selection
:input}
:account-selection #{:input}})
(def ^:private chat-state-transitions
{:chat-type/group
{:mark-managed
{:to-state :managed
:response :bot-readiness-msg}
:mark-evicted
{:to-state :evicted}}
:chat-type/private
{:request-amount
{:to-state :input
:response :private-introduction-msg}
:show-calculator
{:to-state :interactive-input
:response :inline-calculator-msg}
:select-group
{:to-state :group-selection
:response :group-selection-msg}
:select-expense-item
{:to-state :expense-detailing
:response :expense-item-selection-msg}
:request-expense-desc
{:to-state :expense-detailing
:response :expense-manual-description-msg}
:select-account
{:to-state :account-selection
:response :account-selection-msg}
:cancel-input
{:to-state :input}
:notify-input-success
{:to-state :input
:response :expense-added-successfully-msg}
:notify-input-failure
{:to-state :input
:response :failed-to-add-new-expense-msg}}})
(defn- handle-chat-state-transition!
[chat-id event]
(let [chat-type (first (:transition event))
chat-type-states (case chat-type
:chat-type/group group-chat-states
:chat-type/private private-chat-states)
change-state-fn (partial change-chat-state! chat-id chat-type-states)]
(handle-state-transition! event chat-state-transitions change-state-fn)))
; message states
(def ^:private group-msg-states
{:settings
{:initial #{:accounts-mgmt
:expense-items-mgmt
:shares-mgmt}
:accounts-mgmt #{:account-type-selection
:account-renaming
:account-revocation
:account-reinstatement
:initial}
:account-type-selection #{:accounts-mgmt
:initial}
:account-renaming #{:accounts-mgmt
:initial}
:account-revocation #{:accounts-mgmt
:initial}
:account-reinstatement #{:accounts-mgmt
:initial}
:expense-items-mgmt #{:expense-item-description
:expense-item-encoding
:expense-item-deletion
:initial}
:expense-item-description #{:expense-items-mgmt
:initial}
:expense-item-encoding #{:expense-items-mgmt
:initial}
:expense-item-deletion #{:expense-items-mgmt
:initial}
:shares-mgmt #{:initial}}})
(def ^:private msg-state-transitions
{:chat-type/group
{:settings
{:manage-accounts
{:to-state :accounts-mgmt
:response [:settings :accounts-mgmt-options-msg]}
:select-acc-type
{:to-state :account-type-selection
:response [:settings :account-type-selection-msg]}
:rename-account
{:to-state :account-renaming
:response [:settings :account-selection-msg]}
:revoke-account
{:to-state :account-revocation
:response [:settings :account-selection-msg]}
:reinstate-account
{:to-state :account-reinstatement
:response [:settings :account-selection-msg]}
:manage-expense-items
{:to-state :expense-items-mgmt
:response [:settings :expense-items-mgmt-options-msg]}
:redesc-expense-item
{:to-state :expense-item-description
:response [:settings :expense-item-selection-msg]}
:recode-expense-item
{:to-state :expense-item-encoding
:response [:settings :expense-item-selection-msg]}
:delete-expense-item
{:to-state :expense-item-deletion
:response [:settings :expense-item-selection-msg]}
:manage-shares
{:to-state :shares-mgmt}
:restore
{:to-state :initial
:response [:settings :restored-settings-msg]}}}})
(defn- handle-msg-state-transition!
[chat-id msg-id msg-event]
(let [chat-type (first (:transition msg-event))
all-msg-types-states (case chat-type
:chat-type/group group-msg-states)
msg-type (second (:transition msg-event))
msg-type-states (get all-msg-types-states msg-type)
change-state-fn (partial change-bot-msg-state! chat-id msg-id msg-type-states)]
(handle-state-transition! msg-event msg-state-transitions change-state-fn)))
;; RECIPROCAL ACTIONS
;; TODO: Switch to Event-Driven model. Is simpler?
;; HTTP requests should be transformed into events
;; that are handled by appropriate listeners (fns)
;; that, in turn, may result in emitting events.
;; - ABSTRACT ACTIONS
(defmulti ^:private send!
(fn [_token _ids response _opts] (:type response)))
(defmethod send! :text
[token {:keys [chat-<KEY> msg-id] :as _ids}
{:keys [text options] :as _response} {:keys [replace?] :as _opts}]
(if (is-bot-evicted-from-chat? chat-id)
(log/debug "Dropped sending a message to an evicted chat=" chat-id)
;; NB: Looks for the 'replace?' among the passed options to replace
;; the existing response message rather than sending a new one.
(if-not (true? replace?)
(m-api/send-text token chat-id options text)
(m-api/edit-text token chat-id msg-id options text))))
(defmethod send! :inline
[token {:keys [inline-query-id] :as _ids}
{:keys [results options] :as _response} _opts]
(m-api/answer-inline token inline-query-id options results))
(defmethod send! :callback
[token {:keys [callback-query-id] :as _ids}
{:keys [options] :as _response} _opts]
(tg-client/answer-callback-query token callback-query-id options))
(defn- make-tg-bot-api-request!
"Makes a request to the Telegram Bot API. By default, this function awaits the feedback
(a Telegram's response) synchronously and returns a pre-defined code ':finished-sync'.
Options are key-value pairs and may be one of:
:async?
An indicator to make the whole process asynchronous (causes the fn
to return immediately with the ':launched-async' code)
:on-failure
A fn used to handle an exception in case of the request failure
:on-success
A fn used to handle the Telegram's response in case of the successful request
NB: Properly wrapped in try-catch and logged to highlight the exact HTTP client error."
[request-fn {:keys [async? on-failure on-success] :as _?options}]
(let [token (config/get-prop :bot-api-token)
handle-tg-bot-api-req (fn []
(try
(request-fn token)
(catch Throwable t
(if (some? on-failure)
(on-failure t)
(log/error t "Failed making a Telegram Bot API request"))
:req-failed)))
handle-tg-response-fn (fn [tg-response]
(log/debug "Telegram returned:" tg-response)
(try
;; TODO: There are 2 possible outcomes. Do we need to differentiate them somehow?
;; - successful request ('ok' equals true)
;; - unsuccessful request ('ok' equals false, error is in the 'description')
(when (and (some? on-success)
(true? (:ok tg-response)))
(on-success (:result tg-response)))
(catch Exception e
(log/error e "Failed to handle the response from Telegram"))))
handle-when-succeeded (fn [res]
(when-not (= :req-failed res)
(handle-tg-response-fn res)))]
(if (true? async?)
(letfn [(with-one-off-channel [req-fn handle-fn]
(let [resp-chan (chan)]
(go (handle-fn (<! resp-chan))
(close! resp-chan))
(go (>! resp-chan (req-fn)))))]
(with-one-off-channel handle-tg-bot-api-req handle-when-succeeded)
:launched-async)
(do
(handle-when-succeeded (handle-tg-bot-api-req))
:finished-sync))))
(defn- respond!
"Uniformly responds to the user action, whether it a message, inline or callback query,
or some event (e.g. service message or chat member status update).
This fn takes an optional parameter, which is an options map of a specific API method."
([ids response]
(respond! ids response nil))
([ids response ?options]
(make-tg-bot-api-request!
(fn [token]
(send! token ids response ?options))
(assoc ?options
;; TODO: Add the 'response' to the 'failed-responses' queue for the bot Admin
;; to be able to manually handle it later, if this feature is necessary.
:on-failure #(log/errorf % "Failed to respond to %s with %s" ids response)))))
(defn- respond!*
"A variant of the 'respond!' function that is used with the 'keys' of one of
the predefined responses, rather than with an arbitrary response value."
[ids response-keys & {:keys [param-vals] :as ?options}]
{:pre [(vector? response-keys)]}
(encore/when-let [response-data (get-in responses response-keys)
response (to-response response-data param-vals)]
(respond! ids response
(dissoc ?options :param-vals))))
;; TODO: GET RID OF MOST OF THESE !-FNS MAKING THEM PURE AND PASSING THEM DATA!
(defn- proceed-with-chat-and-respond!
"Continues the course of transitions between the states of the chat and sends
a message (answers an inline/callback query) in response to a user/an event."
[{:keys [chat-id] :as ids} event & {:as ?options}]
{:pre [(some? chat-id)]}
(when-let [response (handle-chat-state-transition! chat-id event)]
(respond! ids response ?options)))
(defn- proceed-with-msg-and-respond!
"Continues the course of transitions between the states of the extant message
in some chat and replaces its content in response to a user/an event."
[{:keys [chat-id msg-id] :as ids} msg-event & {:as ?options}]
{:pre [(some? chat-id) (some? msg-id)]}
(when-let [response (handle-msg-state-transition! chat-id msg-id msg-event)]
(respond! ids response
(assoc ?options :replace? true))))
(defn- delete-text!
[token {:keys [<KEY> msg-id] :as _ids}]
(if (is-bot-evicted-from-chat? chat-id)
(log/debug "Dropped deleting the bot's response from an evicted chat=" chat-id)
(m-api/delete-text token chat-id msg-id)))
(defn- delete-response!
"Deletes one of the bot's previous response messages.
NB: - A message can only be deleted if it was sent less than 48 hours ago.
- Bots can delete outgoing messages in private chats, groups, and supergroups.
This fn takes an optional parameter, which is an options map of a specific API method."
([ids]
(delete-response! ids nil))
([ids ?options]
(make-tg-bot-api-request!
(fn [token]
(delete-text! token ids))
(assoc ?options
:on-failure #(log/errorf % "Failed to delete the response message %s" ids)))))
;; - SPECIFIC ACTIONS
(defn- send-retry-command!
[{{chat-id :id} :chat :as message}]
(let [commands-to-retry (tg-client/get-commands {:message message})]
(respond! {:chat-id chat-id}
(get-retry-commands-msg commands-to-retry))))
(defn- send-retry-message!
[{{chat-id :id} :chat :as _message}]
(respond! {:chat-id chat-id}
retry-resend-message-msg))
(defn- send-retry-callback-query!
[{callback-query-id :id :as _callback-query}]
(respond! {:callback-query-id callback-query-id}
retry-callback-query-notification))
(defn- notify-of-inconsistent-chat-state!
[{{chat-id :id} :chat :as _chat-member-updated-or-message}]
(log/errorf "Chat=%s has entered an inconsistent state" chat-id)
'(notify-bot-admin)) ;; TODO: Implement Admin notifications feature.
; private chats
(defn- report-to-user!
[user-id response-keys param-vals]
(when (can-write-to-user? user-id)
(respond!* {:chat-id user-id} response-keys :param-vals param-vals)))
(defn- proceed-with-adding-new-expense!
[chat-id debtor-acc]
(let [chat-data (get-chat-data chat-id)
group-chat-id (:group chat-data)
group-chat-data (get-chat-data group-chat-id)
payer-acc-id (get-personal-account-id
group-chat-data {:user-id chat-id})
debtor-acc-id (:id debtor-acc)
expense-amount (:amount chat-data)
expense-details (or (:expense-item chat-data)
(:expense-desc chat-data))
new-transaction {:chat-id group-chat-id
:payer-acc-id payer-acc-id
:debtor-acc-id debtor-acc-id
:expense-amount expense-amount
:expense-details expense-details}]
(slingshot/try+
(add-transaction! (tlogs/create! new-transaction))
(catch Exception e
;; TODO: Retry to log the failed transaction?
(log/error e "Failed to log transaction:" new-transaction)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason data-persistence-error}}))
(else
(let [pers-accs-count (->> {:acc-types [:acc-type/personal]}
(get-group-chat-accounts chat-id)
count)
payer-acc-name (when-not (or (= pers-accs-count 1)
(= payer-acc-id debtor-acc-id))
(:name (get-group-chat-account
group-chat-data {:type :acc-type/personal
:id payer-acc-id})))
debtor-acc-name (when-not (= pers-accs-count 1)
(:name debtor-acc))]
(respond!* {:chat-id group-chat-id}
[:chat-type/private :new-expense-msg]
:param-vals {:expense-amount expense-amount
:expense-details expense-details
:payer-acc-name payer-acc-name
:debtor-acc-name debtor-acc-name}))
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-success]})))))
;; TODO: Abstract this away — "selecting 1 of N, with a special case for N=1".
(defn- proceed-with-account!
[chat-id]
(let [group-chat-id (:group (get-chat-data chat-id))
active-accounts (get-group-chat-accounts group-chat-id)]
(cond
(< 1 (count active-accounts))
(let [other-accounts (filter #(not= (:user-id %) chat-id) active-accounts)]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :select-account]
:param-vals {:accounts other-accounts
:txt select-payer-account-txt}}))
(empty? active-accounts)
(do
(log/error "No eligible accounts to select a debtor account from")
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason no-debtor-account-error}}))
:else
(let [debtor-acc (first active-accounts)]
(log/debug "Debtor account auto-selected:" debtor-acc)
(proceed-with-adding-new-expense! chat-id debtor-acc)))))
(defn- proceed-with-expense-details!
[chat-id group-chat-id first-name]
(let [group-chat-data (get-chat-data group-chat-id)
expense-items (get-group-chat-expense-items group-chat-data)
event (if (seq expense-items)
{:transition [:chat-type/private :select-expense-item]
:param-vals {:expense-items expense-items}}
{:transition [:chat-type/private :request-expense-desc]
:param-vals {:first-name first-name}})]
(proceed-with-chat-and-respond! {:chat-id chat-id} event)))
;; TODO: Abstract this away — "selecting 1 of N, with a special case for N=1".
(defn- proceed-with-group!
[chat-id first-name]
(let [is-eligible? (fn [group-chat-id]
(is-group-chat-eligible-for-selection? group-chat-id chat-id))
groups (->> (get-chat-data chat-id)
get-private-chat-groups
(filter is-eligible?))]
(cond
(< 1 (count groups))
(let [group-refs (->> groups
(map #(vector % (-> % get-chat-data get-chat-title)))
(map #(apply ->group-ref %)))]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :select-group]
:param-vals {:group-refs group-refs}}))
(empty? groups)
(do
(log/error "No eligible groups to record expenses to")
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason no-group-to-record-error}}))
:else
(let [group-chat-id (first groups)]
(log/debug "Group chat auto-selected:" group-chat-id)
(assoc-in-chat-data! chat-id [:group] group-chat-id)
(proceed-with-expense-details! chat-id group-chat-id first-name)))))
;; TODO: Abstract away the "selecting N of {M; optional ALL}, M>=N>0" scenario.
(defn- clean-up-interactive-input-data!
[chat-id]
(let [dropped-msgs (concat (drop-bot-msg! chat-id {:type :inline-calculator})
(drop-bot-msg! chat-id {:type :cancel-disclaimer}))]
(doseq [msg-id dropped-msgs]
(delete-response! {:chat-id chat-id :msg-id msg-id}))))
; group chats
; - chat & msgs state
(defn- proceed-with-bot-eviction!
[chat-id]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/group :mark-evicted]}))
(defn- proceed-with-restoring-group-chat-intro!
[chat-id user-id msg-id]
(release-message-lock! chat-id user-id msg-id)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :restore]}))
; - personal accounts
(defn- proceed-with-personal-accounts-name-request!
[chat-id existing-chat? ?new-chat-members]
(respond!* {:chat-id chat-id}
[:chat-type/group :personal-account-name-request-msg]
:param-vals {:existing-chat? existing-chat?
:chat-members ?new-chat-members}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :name-request})))
(defn- proceed-with-group-chat-finalization!
[chat-id show-settings?]
;; NB: Tries to create a new version of the "general account"
;; even if the group chat already existed before.
(create-general-account! chat-id (get-datetime-in-tg-format))
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/group :mark-managed]
:param-vals {:bot-username (get-bot-username)}})
(when show-settings?
(respond!* {:chat-id chat-id}
[:chat-type/group :settings-msg]
:param-vals {:first-time? true}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :settings
:state :initial}))))
(defn- check-personal-accounts-and-proceed!
([chat-id]
(let [existing-chat? (does-bot-manage-the-chat? {:chat-id chat-id})]
(check-personal-accounts-and-proceed! chat-id existing-chat?)))
([chat-id existing-chat?]
;; NB: We need to update the list of chat personal accounts with new ones
;; for those users:
;; - who were members of the previously non-existent group chat at the
;; time the bot was added there (or were added along with the bot),
;; - who have joined the existing group chat during the absence of the
;; previously evicted bot, if there are any. (Users with an existing
;; active personal account should be ignored in this case.)
(let [pers-accs-missing (get-number-of-missing-personal-accounts chat-id)]
(if (> pers-accs-missing 0)
(if (and (seq (find-bot-messages (get-chat-data chat-id) {:type :name-request}))
(not (is-bot-evicted-from-chat? chat-id))) ;; just in case, to not stuck
(respond!* {:chat-id chat-id}
[:chat-type/group :personal-accounts-left-msg]
:param-vals {:count pers-accs-missing})
(proceed-with-personal-accounts-name-request! chat-id existing-chat? nil))
(do
(drop-bot-msg! chat-id {:type :name-request})
(proceed-with-group-chat-finalization! chat-id (not existing-chat?)))))))
(defn- proceed-with-new-chat-members!
[chat-id new-chat-members]
(update-members-count! chat-id (partial + (count new-chat-members)))
(proceed-with-personal-accounts-name-request! chat-id true new-chat-members))
(defn- proceed-with-left-chat-member!
[chat-id left-chat-member]
(update-members-count! chat-id dec)
;; NB: It is necessary to trigger the personal accounts check, just in case we
;; are in the middle of the accounts creation process. If so, it will help
;; us to avoid stale ':name-request' message in chat data and, what's even
;; more important, will run the group chat finalization routine.
(check-personal-accounts-and-proceed! chat-id)
(encore/when-let [chat-data (get-chat-data chat-id)
user-id (:id left-chat-member)
pers-acc (get-personal-account chat-data {:user-id user-id})
datetime (get-datetime-in-tg-format)]
(change-account-activity-status! chat-id pers-acc
{:revoke? true :datetime datetime})
(drop-user-input-data! chat-id user-id)
(report-to-user! user-id
[:chat-type/private :removed-from-group-msg]
{:chat-title (get-chat-title chat-data)})))
; - accounts mgmt
(defn- proceed-with-accounts-mgmt!
[chat-id msg-id]
(let [accounts-by-type (get-group-chat-accounts-by-type chat-id)]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-accounts]
:param-vals {:accounts-by-type accounts-by-type}})))
(defn- proceed-with-account-type-selection!
[chat-id msg-id]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :select-acc-type]
:param-vals {:account-types [:acc-type/group :acc-type/personal]
:extra-buttons [back-button]}}))
(defn- proceed-with-account-naming!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-account-name-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-acc-name})))
(defn- proceed-with-the-account-name-is-already-taken!
[chat-id {user-id :id :as user} bot-msg-type]
(respond!* {:chat-id chat-id}
[:chat-type/group :the-account-name-is-already-taken-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type bot-msg-type})))
(defn- proceed-with-next-account-creation-steps!
[chat-id acc-type {user-id :id :as user}]
(let [input-data {:acc-type acc-type}]
(set-user-input-data! chat-id user-id :create-account input-data))
(case acc-type
:acc-type/personal
(proceed-with-account-naming! chat-id user)
:acc-type/group
(let [personal-accs (get-group-chat-accounts chat-id
{:acc-types [:acc-type/personal]})]
(respond!* {:chat-id chat-id}
[:chat-type/group :group-members-selection-msg]
:param-vals {:user user
:selected nil
:remaining personal-accs}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :group-members-selection})))))
(defn- proceed-with-account-member-selection!
[chat-id msg-id user already-selected-account-members]
(let [personal-accs (set (get-group-chat-accounts chat-id
{:acc-types [:acc-type/personal]}))
selected-accs (set already-selected-account-members)
remaining-accs (set/difference personal-accs selected-accs)
accounts-remain? (seq remaining-accs)]
(when accounts-remain?
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/group :group-members-selection-msg]
:param-vals {:user user
:selected selected-accs
:remaining remaining-accs}
:replace? true))
accounts-remain?))
(defn- proceed-with-end-of-account-members-selection!
[chat-id msg-id {user-id :id :as user} members]
(drop-bot-msg! chat-id {:to-user user-id
:type :group-members-selection})
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/group :new-group-members-msg]
:param-vals {:acc-names (map :name members)}
:replace? true)
(proceed-with-account-naming! chat-id user))
(defn- proceed-with-next-group-account-creation-steps!
[chat-id msg-id {user-id :id :as user}]
(let [members (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(get :members))
can-proceed? (proceed-with-account-member-selection! chat-id msg-id user members)]
(when-not can-proceed?
(proceed-with-end-of-account-members-selection! chat-id msg-id user members))))
(defn- proceed-with-account-selection!
([chat-id msg-id callback-query-id
state-transition-name]
(proceed-with-account-selection! chat-id msg-id callback-query-id
state-transition-name nil))
([chat-id msg-id callback-query-id
state-transition-name ?filter-pred]
(let [eligible-accs (get-group-chat-accounts chat-id
{:acc-types [:acc-type/group
:acc-type/personal]
:filter-pred ?filter-pred})]
(if (seq eligible-accs)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings state-transition-name]
:param-vals {:accounts eligible-accs
:txt select-account-txt
:extra-buttons [back-button]}})
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-eligible-accounts-notification])))))
(defn- proceed-with-account-renaming!
[chat-id {user-id :id :as user} acc-to-rename]
(let [input-data {:acc-type (:type acc-to-rename)
:acc-id (:id acc-to-rename)}]
(set-user-input-data! chat-id user-id :rename-account input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :account-rename-request-msg]
:param-vals {:user user
:acc-name (:name acc-to-rename)}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-acc-rename})))
(defn- proceed-with-personal-account-creation!
[chat-id chat-title
acc-name created-dt {user-id :id :as user} first-msg-id]
(let [create-acc-res (create-personal-account! chat-id acc-name created-dt
:user-id user-id :first-msg-id first-msg-id)]
(if (is-failure? create-acc-res)
(case create-acc-res
:failure/user-already-has-an-active-account
(respond!* {:chat-id chat-id} [:chat-type/group :canceled-changes-msg])
:failure/the-account-name-is-already-taken
(proceed-with-the-account-name-is-already-taken! chat-id user :name-request))
(report-to-user! user-id
[:chat-type/private :added-to-new-group-msg]
{:chat-title chat-title}))))
(defn- proceed-with-account-operation!
[chat-id {user-id :id :as user}
bot-msg-type input-name acc-op-fn]
(let [chat-data (get-chat-data chat-id)
input-data (get-user-input-data chat-data user-id input-name)
acc-op-res (acc-op-fn chat-id input-data)]
(if (is-failure? acc-op-res)
(case acc-op-res
:failure/the-account-name-is-already-taken
(proceed-with-the-account-name-is-already-taken! chat-id user bot-msg-type)
(throw (ex-info "Unexpected operation result" {:result acc-op-res})))
(do
(clean-up-chat-data! chat-id {:bot-messages [{:to-user user-id
:type bot-msg-type}]
:input [{:user user-id
:name input-name}]})
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg])))))
; - expense items mgmt
(defn- proceed-with-expense-items-mgmt!
[chat-id msg-id]
(let [chat-data (get-chat-data chat-id)
expense-items (get-group-chat-expense-items chat-data)]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-expense-items]
:param-vals {:expense-items expense-items}})))
(defn- proceed-with-expense-item-description!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-expense-item-desc-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-desc})))
(defn- proceed-with-expense-item-encoding!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-expense-item-code-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-code})))
(defn- proceed-with-the-expense-item-code-is-already-used!
[chat-id {user-id :id :as user} bot-msg-type]
(respond!* {:chat-id chat-id}
[:chat-type/group :the-expense-item-code-is-already-used-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type bot-msg-type})))
(defn- proceed-with-expense-item-creation-steps!
[chat-id user]
;; TODO: Re-implement as a "logical action flow": name + desc.
(proceed-with-expense-item-description! chat-id user))
(defn- proceed-with-expense-item-operation!
[chat-id {user-id :id :as user}
bot-msg-type input-name exp-it-op-fn]
(let [chat-data (get-chat-data chat-id)
input-data (get-user-input-data chat-data user-id input-name)
exp-it-op-res (exp-it-op-fn chat-id input-data)]
(if (is-failure? exp-it-op-res)
(case exp-it-op-res
:failure/the-expense-item-code-is-already-used
(proceed-with-the-expense-item-code-is-already-used! chat-id user bot-msg-type)
(throw (ex-info "Unexpected operation result" {:result exp-it-op-res})))
(do
(clean-up-chat-data! chat-id {:bot-messages [{:to-user user-id
:type bot-msg-type}]
:input [{:user user-id
:name input-name}]})
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg])))))
(defn- proceed-with-expense-item-selection!
([chat-id msg-id callback-query-id
state-transition-name]
(proceed-with-expense-item-selection! chat-id msg-id callback-query-id
state-transition-name nil))
([chat-id msg-id callback-query-id
state-transition-name ?filter-pred]
(let [chat-data (get-chat-data chat-id)
eligible-expense-items (cond->> (get-group-chat-expense-items chat-data)
(some? ?filter-pred) (filter ?filter-pred))]
(if (seq eligible-expense-items)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings state-transition-name]
:param-vals {:expense-items eligible-expense-items
:extra-buttons [back-button]}})
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-eligible-expense-items-notification])))))
(defn- proceed-with-expense-item-re-description!
[chat-id {user-id :id :as user} exp-it-to-redesc]
(let [input-data {:exp-it-code (first exp-it-to-redesc)}]
(set-user-input-data! chat-id user-id :redesc-expense-item input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :expense-item-redesc-request-msg]
:param-vals {:user user
:exp-it-desc (:desc (second exp-it-to-redesc))}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-redesc})))
(defn- proceed-with-expense-item-re-encoding!
[chat-id {user-id :id :as user} exp-it-to-recode]
(let [input-data {:exp-it-code (first exp-it-to-recode)}]
(set-user-input-data! chat-id user-id :recode-expense-item input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :expense-item-recode-request-msg]
:param-vals {:user user
:exp-it-desc (:desc (second exp-it-to-recode))}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-recode})))
(defn- proceed-with-expense-item-deletion!
[chat-id exp-it-to-delete]
(let [delete-exp-it-res (delete-group-chat-expense-item! chat-id exp-it-to-delete)]
(if (is-failure? delete-exp-it-res)
(case delete-exp-it-res
:failure/the-expense-item-cannot-be-deleted
(respond!* {:chat-id chat-id}
[:chat-type/group :the-expense-item-cannot-be-deleted-msg]
:param-vals {:exp-it-code (first exp-it-to-delete)
:exp-it-desc (:desc (second exp-it-to-delete))})
(throw (ex-info "Unexpected operation result" {:result delete-exp-it-res})))
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg]))))
;; TODO: Linearize calls to these macros with a wrapper macro & a map.
(defmacro do-when-chat-is-ready-or-send-notification!
[chat-state callback-query-id & body]
`(if (does-bot-manage-the-chat? {:chat-state ~chat-state})
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :waiting-for-user-input-notification])))
(defmacro do-with-expected-user-or-send-notification!
[chat-id user-id msg-id callback-query-id & body]
`(if (check-bot-msg (get-bot-msg (get-chat-data ~chat-id) ~msg-id)
{:to-user ~user-id})
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :waiting-for-other-user-notification])))
(defmacro try-with-message-lock-or-send-notification!
[chat-id user-id msg-id callback-query-id & body]
`(if (acquire-message-lock! ~chat-id ~user-id ~msg-id)
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :message-already-in-use-notification])))
;; - COMMANDS ACTIONS
; private chats
(defn- cmd-private-start!
[{chat-id :id :as chat}
{first-name :first_name :as _user}]
(log/debug "Conversation started in a private chat:" chat)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :request-amount]
:param-vals {:first-name first-name}}))
;; TODO: Implement proper '/help' message (w/ the list of commands, etc.).
(defn- cmd-private-help!
[{chat-id :id :as chat}]
(log/debug "Help requested in a private chat:" chat)
(respond! {:chat-id chat-id}
{:type :text
:text "Help is on the way!"}))
(defn- cmd-private-calc!
[{chat-id :id :as chat}]
(when (= :input (-> chat-id get-chat-data get-chat-state))
(log/debug "Calculator opened in a private chat:" chat)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :show-calculator]}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :inline-calculator}))
(respond!* {:chat-id chat-id}
[:chat-type/private :interactive-input-disclaimer-msg]
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :cancel-disclaimer}))))
(defn- cmd-private-cancel!
[{chat-id :id :as chat}]
(log/debug "The operation is canceled in a private chat:" chat)
;; clean-up the messages
(case (get-chat-state (get-chat-data chat-id))
:interactive-input
(clean-up-interactive-input-data! chat-id)
nil)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :cancel-input]}))
; group chats
;; TODO: Implement proper '/help' message (w/ the list of commands, etc.).
(defn- cmd-group-help!
[{chat-id :id :as chat}]
(log/debug "Help requested in a group chat:" chat)
(respond! {:chat-id chat-id}
{:type :text
:text "Help is on the way!"}))
(defn- cmd-group-settings!
[{chat-id :id :as chat}]
(log/debug "Settings requested in a group chat:" chat)
(respond!* {:chat-id chat-id}
[:chat-type/group :settings-msg]
:param-vals {:first-time? false}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :settings
:state :initial})))
;; API RESPONSES
;; IMPORTANT: The main idea of this API is to organize handlers of any type (message, command, any
;; query, etc.) into a chain (in the order of their declaration within the 'defhandler'
;; body) that will process updates in the following way:
;; - the first handler of the type have to log an incoming update (its payload object);
;; - any intermediate handler have to either:
;; - result in an "operation [result] code" ('succeed', 'failed') OR in an "immediate
;; response" (only for Webhook updates) — which will stop the further processing;
;; - result in 'nil' — which will pass the update for processing to the next handler;
;; - the last handler, in case the update wasn't processed, have to "ignore" it — which
;; is also interpreted as the whole operation had 'succeed'.
;; NB: Any non-nil will do.
(def op-succeed {:ok true})
(def op-failed {:ok false})
(defmacro ^:private ignore
[msg & args]
`(do
(log/debugf (str "Ignored: " ~msg) ~@args)
op-succeed))
(defn- cb-succeed
[callback-query-id]
(tg-api/build-immediate-response "answerCallbackQuery"
{:callback_query_id callback-query-id}))
(defn- cb-ignored
[callback-query-id]
;; TODO: For a long-polling version, respond as usual.
(tg-api/build-immediate-response "answerCallbackQuery"
(assoc ignored-callback-query-notification
:callback_query_id callback-query-id)))
;; TODO: This have to be combined with an Event-Driven model,
;; i.e. in case of long-term request processing the bot
;; should immediately respond with sending the 'typing'
;; chat action (use "sendChatAction" method and see the
;; /sendChatAction specs for the request parameters).
;; BOT API
;; TODO: The design should be similar to the Lupapiste web handlers with their 'in-/outjects'.
;; TODO: Add a rate limiter. Use the 'limiter' from Encore? Or some full-featured RPC library?
;; This is to overcome the recent error — HTTP 429 — "Too many requests, retry after X".
; The Bots FAQ on the official Telegram website lists the following limits on server requests:
; - No more than 1 message per second in a single chat,
; - No more than 20 messages per minute in one group,
; - No more than 30 messages per second in total.
(defmacro handle-with-care!
[bindings & handler-body-and-care-fn]
(let [body (butlast handler-body-and-care-fn)
care-fn (last handler-body-and-care-fn)]
`(fn [arg#]
(try
((fn ~bindings ~@body) arg#)
(catch Exception e#
(log/error e# "Failed to handle an incoming update:" arg#)
(when-some [ex-data# (ex-data e#)]
(log/error "The associated exception data:" ex-data#))
(~care-fn arg#)
op-failed)))))
(tg-client/defhandler
handler
;; NB: This function is applied to the arguments of all handlers that follow
;; and merges its result with the original value of the argument.
(fn [upd upd-type]
(let [chat (case upd-type
(:message :my_chat_member) (-> upd upd-type :chat)
(:callback_query) (-> upd upd-type :message :chat)
nil)
msg (case upd-type
:message (:message upd)
:callback_query (-> upd :callback_query :message)
nil)
chat-data (get-chat-data (or (:id chat)
(:id (:chat msg))))]
(cond-> nil
(some? chat)
(merge {:chat-type (cond
(tg-api/is-private? chat) :chat-type/private
(tg-api/is-group? chat) :chat-type/group)
:chat-state (get-chat-state chat-data)})
(some? msg)
(merge (when-some [bot-msg (get-bot-msg chat-data (:message_id msg))]
{:bot-msg bot-msg})))))
;; - BOT COMMANDS
; group chats
(tg-client/command-fn
"help"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/group (:chat-type message))
(cmd-group-help! chat)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"settings"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/group (:chat-type message))
(cmd-group-settings! chat)
op-succeed)
send-retry-command!))
; private chats
(tg-client/command-fn
"start"
(handle-with-care!
[{user :from chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-start! chat user)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"help"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-help! chat)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"calc"
(handle-with-care!
[{chat :chat :as message}]
(when (and (= :chat-type/private (:chat-type message))
(cmd-private-calc! chat))
op-succeed)
send-retry-command!))
(tg-client/command-fn
"cancel"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-cancel! chat)
op-succeed)
send-retry-command!))
;; - INLINE QUERIES
(m-hlr/inline-fn
(fn [inline-query]
(log/debug "Inline query:" inline-query)))
;; TODO: Try to implement an inline query answered w/ 'switch_pm_text' parameter?
(m-hlr/inline-fn
(fn [{inline-query-id :id _user :from query-str :query _offset :offset
:as _inline-query}]
(ignore "inline query id=%s, query=%s" inline-query-id query-str)))
;; - CALLBACK QUERIES
(m-hlr/callback-fn
(fn [callback-query]
(log/debug "Callback query:" callback-query)))
; group chats
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-accounts callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-accounts-mgmt! chat-id msg-id)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :accounts-mgmt (-> callback-query :bot-msg :state)))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(when-let [respond! (condp = callback-btn-data
cd-accounts-create #(proceed-with-account-type-selection!
chat-id msg-id)
cd-accounts-rename #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:rename-account
(can-rename-account? chat-id user-id))
cd-accounts-revoke #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:revoke-account
(can-revoke-account? chat-id user-id))
cd-accounts-reinstate #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:reinstate-account
(can-reinstate-account? chat-id user-id))
nil)]
(respond!)
(cb-succeed callback-query-id)))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-type-selection (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-type-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [acc-type-name (str/replace-first callback-btn-data
cd-account-type-prefix "")
acc-type (keyword "acc-type" acc-type-name)]
(proceed-with-next-account-creation-steps! chat-id acc-type user))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
picked-acc (data->account callback-btn-data chat-data)
input-data (-> chat-data
(get-user-input-data user-id :create-account)
(update :members #(u-coll/add-or-remove picked-acc %)))]
(set-user-input-data! chat-id user-id :create-account input-data))
(proceed-with-next-group-account-creation-steps! chat-id msg-id user)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(= cd-undo callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(drop-bot-msg! chat-id {:to-user user-id
:type :group-members-selection})
(set-user-input-data! chat-id user-id :create-account nil)
(delete-response! {:chat-id chat-id :msg-id msg-id})
(respond!* {:chat-id chat-id}
[:chat-type/group :canceled-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(= cd-done callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [members (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(get :members))]
(if (seq members)
(do
(proceed-with-end-of-account-members-selection! chat-id msg-id user members)
(cb-succeed callback-query-id))
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-group-members-selected-notification]))))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-renaming (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
account-to-rename (data->account callback-btn-data chat-data)]
(proceed-with-account-renaming! chat-id user account-to-rename))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-revocation (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
account-to-revoke (data->account callback-btn-data chat-data)
datetime (get-datetime-in-tg-format)]
;; NB: It makes sense to ask the user if the revoked account owner
;; should be excluded from the chat, but this is possible only
;; for bots with 'admin' rights.
(change-account-activity-status! chat-id account-to-revoke
{:revoke? true :datetime datetime}))
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(respond!* {:chat-id chat-id} [:chat-type/group :successful-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-reinstatement (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
account-to-reinstate (data->account callback-btn-data chat-data)
datetime (get-datetime-in-tg-format)]
(change-account-activity-status! chat-id account-to-reinstate
{:reinstate? true :datetime datetime}))
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(respond!* {:chat-id chat-id} [:chat-type/group :successful-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-expense-items callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-expense-items-mgmt! chat-id msg-id)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-items-mgmt (-> callback-query :bot-msg :state)))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(when-let [respond! (condp = callback-btn-data
cd-expense-items-create #(proceed-with-expense-item-creation-steps!
chat-id user)
cd-expense-items-redesc #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:redesc-expense-item)
cd-expense-items-recode #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:recode-expense-item)
cd-expense-items-delete #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:delete-expense-item
can-expense-item-be-deleted?)
nil)]
(respond!)
(cb-succeed callback-query-id)))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-description (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-re-description! chat-id user expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-encoding (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-re-encoding! chat-id user expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-deletion (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-deletion! chat-id expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-shares callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-shares]})))
(cb-succeed callback-query-id))
send-retry-callback-query!))
;; TODO: Implement handlers for ':shares-mgmt'.
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= cd-back callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(case (-> callback-query :bot-msg :state)
(:initial ;; for when something went wrong
:accounts-mgmt :expense-items-mgmt :shares-mgmt)
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(:account-type-selection :account-renaming :account-revocation :account-reinstatement)
(proceed-with-accounts-mgmt! chat-id msg-id)
(:expense-item-description :expense-item-encoding :expense-item-deletion)
(proceed-with-expense-items-mgmt! chat-id msg-id))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
; private chats
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{first-name :first_name} :from
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :group-selection (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-group-chat-prefix))
(let [group-chat-id-str (str/replace-first callback-btn-data cd-group-chat-prefix "")
group-chat-id (u-nums/parse-int group-chat-id-str)]
(assoc-in-chat-data! chat-id [:group] group-chat-id)
(proceed-with-expense-details! chat-id group-chat-id first-name))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :expense-detailing (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(let [expense-item (str/replace-first callback-btn-data cd-expense-item-prefix "")]
(assoc-in-chat-data! chat-id [:expense-item] expense-item)
(proceed-with-account! chat-id))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :account-selection (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-account-prefix))
(let [group-chat-id (:group (get-chat-data chat-id))
group-chat-data (get-chat-data group-chat-id)
debtor-acc (data->account callback-btn-data group-chat-data)]
(proceed-with-adding-new-expense! chat-id debtor-acc))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :interactive-input (:chat-state callback-query)))
(when-let [non-terminal-operation (condp apply [callback-btn-data]
cd-digits-set {:type :append-digit
:data callback-btn-data}
cd-ar-ops-set {:type :append-ar-op
:data callback-btn-data}
(partial = cd-clear) {:type :cancel}
(partial = cd-cancel) {:type :clear}
nil)]
(let [old-user-input (get-user-input (get-chat-data chat-id))
new-user-input (update-user-input! chat-id non-terminal-operation)]
(when (not= old-user-input new-user-input)
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/private :inline-calculator-msg]
:param-vals {:new-user-input new-user-input}
:replace? true)))
(cb-succeed callback-query-id)))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{first-name :first_name} :from
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :interactive-input (:chat-state callback-query))
(= cd-enter callback-btn-data))
(let [user-input (get-user-input (get-chat-data chat-id))
parsed-val (u-nums/parse-arithmetic-expression user-input)]
(if (and (number? parsed-val) (pos? parsed-val))
(do
(log/debug "User input:" parsed-val)
(assoc-in-chat-data! chat-id [:amount] parsed-val)
(clean-up-interactive-input-data! chat-id)
(respond!* {:chat-id chat-id}
[:chat-type/private :interactive-input-success-msg]
:param-vals {:parsed-val parsed-val})
(proceed-with-group! chat-id first-name))
(do
(log/debugf "Invalid user input: \"%s\"" parsed-val)
(respond!* {:callback-query-id callback-query-id}
[:chat-type/private :invalid-input-notification]))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(fn [{callback-query-id :id _user :from _msg :message _msg-id :inline_message_id
_chat-instance :chat_instance callback-btn-data :data
:as _callback-query}]
(ignore "callback query id=%s, data=%s" callback-query-id callback-btn-data)
(cb-ignored callback-query-id)))
;; - CHAT MEMBER STATUS UPDATES
(tg-client/bot-chat-member-status-fn
(handle-with-care!
[{{chat-id :id _type :type chat-title :title _username :username :as chat} :chat
{_user-id :id first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
date :date
{_old-user :user _old-status :status :as _old-chat-member} :old_chat_member
{_new-user :user _new-status :status :as _new-chat-member} :new_chat_member
:as my-chat-member-updated}]
(log/debug "Bot chat member status updated in:" chat)
(cond
(tg-api/has-joined? my-chat-member-updated)
(let [token (config/get-prop :bot-api-token)
chat-members-count (tg-client/get-chat-member-count token chat-id)
new-chat (setup-new-group-chat! chat-id chat-title chat-members-count)
existing-chat? (nil? new-chat)]
(if existing-chat?
(do
(log/debugf "The chat=%s already exists" chat-id)
(update-members-count! chat-id (constantly chat-members-count)))
(respond!* {:chat-id chat-id}
[:chat-type/group :introduction-msg]
:param-vals {:chat-members-count chat-members-count
:first-name first-name}))
(check-personal-accounts-and-proceed! chat-id existing-chat?)
op-succeed)
(tg-api/has-left? my-chat-member-updated)
(do
(update-members-count! chat-id dec)
(proceed-with-bot-eviction! chat-id)
op-succeed)
:else
(ignore "bot chat member status update dated %s in chat=%s" date chat-id))
notify-of-inconsistent-chat-state!))
(tg-client/chat-member-status-fn
(fn [{{chat-id :id _type :type _chat-title :title _username :username :as chat} :chat
{_user-id :id _first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
date :date
{_old-user :user _old-status :status :as _old-chat-member} :old_chat_member
{_new-user :user _new-status :status :as _new-chat-member} :new_chat_member
:as _chat-member-updated}]
(log/debug "Chat member status updated in:" chat)
;; NB: The bot must be an administrator in the chat to receive 'chat_member' updates
;; about other chat members. By default, only 'my_chat_member' updates about the
;; bot itself are received.
(ignore "chat member status update dated %s in chat=%s" date chat-id)))
;; - PLAIN MESSAGES
; group chats
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id :as chat} :chat
new-chat-members :new_chat_members
:as _message}]
(when (some? new-chat-members)
(log/debug "New chat members in chat:" chat)
(let [new-chat-members (filter #(not (:is_bot %)) new-chat-members)]
(when (seq new-chat-members)
(proceed-with-new-chat-members! chat-id new-chat-members)
op-succeed)))
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id :as chat} :chat
left-chat-member :left_chat_member
:as _message}]
(when (some? left-chat-member)
(log/debug "Chat member left chat:" chat)
(when-not (:is_bot left-chat-member)
(proceed-with-left-chat-member! chat-id left-chat-member)
op-succeed))
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(fn [{msg-id :message_id group-chat-created :group_chat_created :as _message}]
(when (some? group-chat-created)
(ignore "message id=%s" msg-id))))
(m-hlr/message-fn
(handle-with-care!
[{msg-id :message_id date :date text :text
{user-id :id :as user} :from
{chat-id :id chat-title :title} :chat
:as message}]
;; TODO: Figure out how to proceed if someone accidentally closes the reply.
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:type :name-request}))
;; NB: Here the 'user-id' exists for sure, since it is the User's response.
(when-some [_new-chat (setup-new-private-chat! user-id chat-id)]
(update-private-chat-groups! user-id chat-id))
(proceed-with-personal-account-creation! chat-id chat-title
text date user msg-id)
(check-personal-accounts-and-proceed! chat-id)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{date :date text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-acc-name}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(assoc :acc-name text)
(assoc :created-dt date)
(assoc :created-by user-id))]
(set-user-input-data! chat-id user-id :create-account input-data))
(proceed-with-account-operation! chat-id user
:request-acc-name
:create-account
create-group-chat-account!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-acc-rename}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :rename-account)
(assoc :new-acc-name text))]
(set-user-input-data! chat-id user-id :rename-account input-data))
(proceed-with-account-operation! chat-id user
:request-acc-rename
:rename-account
change-group-chat-account-name!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-desc}))
(let [input-data {:exp-it-data {:desc text}}]
(set-user-input-data! chat-id user-id :create-expense-item input-data))
(proceed-with-expense-item-encoding! chat-id user)
(drop-bot-msg! chat-id {:to-user user-id
:type :request-exp-it-desc})
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{emoji :emoji} :sticker
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-code}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-expense-item)
(assoc :exp-it-code (or text emoji)))]
(set-user-input-data! chat-id user-id :create-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-code
:create-expense-item
create-group-chat-expense-item!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-redesc}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :redesc-expense-item)
(assoc-in [:exp-it-data :desc] text))]
(set-user-input-data! chat-id user-id :redesc-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-redesc
:redesc-expense-item
update-group-chat-expense-item!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{emoji :emoji} :sticker
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-recode}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :recode-expense-item)
(assoc :new-exp-it-code (or text emoji)))]
(set-user-input-data! chat-id user-id :recode-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-recode
:recode-expense-item
change-group-chat-expense-item-code!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id} :chat
new-chat-title :new_chat_title
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(some? new-chat-title))
(log/debugf "Chat %s title was changed to '%s'" chat-id new-chat-title)
(set-chat-title! chat-id new-chat-title)
op-succeed)
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id} :chat
migrate-to-chat-id :migrate_to_chat_id
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(some? migrate-to-chat-id))
(log/debugf "Group %s has been migrated to a supergroup %s" chat-id migrate-to-chat-id)
(migrate-group-chat-to-supergroup! chat-id migrate-to-chat-id)
op-succeed)
notify-of-inconsistent-chat-state!))
; private chats
(m-hlr/message-fn
(handle-with-care!
[{text :text
{<NAME> :<NAME>} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/private (:chat-type message))
(= :input (:chat-state message)))
(let [input (u-nums/parse-number text)]
(if (number? input)
(do
(log/debug "User input:" input)
(assoc-in-chat-data! chat-id [:amount] input)
(proceed-with-group! chat-id first-name)
op-succeed)
(respond!* {:chat-id chat-id}
[:chat-type/private :invalid-input-msg]))))
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text {chat-id :id} :chat
:as message}]
(when (and (= :chat-type/private (:chat-type message))
(= :expense-detailing (:chat-state message)))
(log/debugf "Expense description: \"%s\"" text)
(assoc-in-chat-data! chat-id [:expense-desc] text)
(proceed-with-account! chat-id)
op-succeed)
send-retry-message!))
;; NB: A "match-all catch-through" case. Excessive list of parameters is for clarity.
(m-hlr/message-fn
(fn [{msg-id :message_id _date :date _text :text
{_user-id :id _first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
{_chat-id :id _type :type _chat-title :title _username :username :as chat} :chat
_sender-chat :sender_chat
_forward-from :forward_from
_forward-from-chat :forward_from_chat
_forward-from-message-id :forward_from_message_id
_forward-signature :forward_signature
_forward-sender-name :forward_sender_name
_forward-date :forward_date
_original-msg :reply_to_message ;; for replies
_via-bot :via_bot
_edit-date :edit_date
_author-signature :author_signature
_entities :entities
_new-chat-members :new_chat_members
_left-chat-member :left_chat_member
_new-chat-title :new_chat_title
_new-chat-photo :new_chat_photo
_delete-chat-photo :delete_chat_photo
_group-chat-created :group_chat_created
_supergroup-chat-created :supergroup_chat_created
_channel-chat-created :channel_chat_created
_message-auto-delete-timer-changed :message_auto_delete_timer_changed
_migrate-to-chat-id :migrate_to_chat_id
_migrate-from-chat-id :migrate_from_chat_id
_pinned-message :pinned_message
_reply-markup :reply_markup
:as _message}]
(log/debug "Unprocessed message in chat:" chat)
(ignore "message id=%s" msg-id))))
(defn bot-api
[update]
(log/debug "Received update:" update)
(handler update))
| true |
(ns general-expenses-accountant.core
"Bot API and business logic (core functionality)"
(:require [clojure.set :as set]
[clojure.string :as str]
[clojure.core.async :refer [go chan timeout >! <! close!]]
[morse
[api :as m-api]
[handlers :as m-hlr]]
[mount.core :refer [defstate]]
[slingshot.slingshot :as slingshot]
[taoensso
[encore :as encore]
[timbre :as log]]
[general-expenses-accountant.config :as config]
[general-expenses-accountant.domain.chat :as chats]
[general-expenses-accountant.domain.tlog :as tlogs]
[general-expenses-accountant.md-v2 :as md-v2]
[general-expenses-accountant.tg-bot-api :as tg-api]
[general-expenses-accountant.tg-client :as tg-client]
[general-expenses-accountant.utils.coll :as u-coll]
[general-expenses-accountant.utils.nums :as u-nums])
(:import [java.util Locale]))
;; STATE
(defstate ^:private bot-user
:start (encore/if-let [token (config/get-prop :bot-api-token)
bot-user (tg-client/get-me token)]
(do
(log/debug "Identified myself:" bot-user)
bot-user)
(do
(log/fatal "Unable to identify myself")
(System/exit 3))))
(defn get-bot-username
[]
(get bot-user :username))
;; TODO: Send the list of supported commands w/ 'setMyCommands'.
;; TODO: Normally, this should be transformed into a 'cloffeine' cache
;; which periodically auto-evicts the cast-off chats data. Then,
;; the initial data should be truncated, e.g. by an 'updated_at'
;; timestamps, and the data for chats from the incoming requests
;; should be (re)loaded from the DB on demand.
(defstate ^:private *bot-data
:start (let [chats (chats/select-all)
ids (map :id chats)]
(log/debug "Total chats uploaded from the DB:" (count chats))
(atom (zipmap ids chats))))
(defn- get-bot-data
[]
@*bot-data)
(defn- update-bot-data!
([upd-fn]
(swap! *bot-data upd-fn))
([upd-fn & upd-fn-args]
(apply swap! *bot-data upd-fn upd-fn-args)))
(defn- conditionally-update-bot-data!
([pred upd-fn]
(with-local-vars [succeed true]
(let [updated-bot-data
(update-bot-data!
(fn [bot-data]
(if (pred bot-data)
(upd-fn bot-data)
(do
(var-set succeed false)
bot-data))))]
(when @succeed
updated-bot-data))))
([pred upd-fn & upd-fn-args]
(conditionally-update-bot-data! pred #(apply upd-fn % upd-fn-args))))
;; TODO: Get rid of this atom after debugging is complete. This is not needed for the app.
(defonce ^:private *transactions (atom {}))
(defn- add-transaction!
[new-transaction]
{:pre [(contains? new-transaction :chat-id)]}
(swap! *transactions update (:chat-id new-transaction) conj new-transaction))
;; ACCOUNTING TYPES
;; From the business logic perspective there are 2 main use cases for the bot:
;; 1. personal accounting — when a user creates a group chat for himself
;; and the bot;
;; 2. group accounting — when multiple users create a group chat and add
;; the bot there to track their general expenses.
;; The only difference between the two is that an account of a ':general' type
;; is automatically created for a group accounting and what format is used for
;; new expense notification messages.
(def ^:private min-chat-members-for-group-accounting
"The number of users in a group chat (including the bot itself)
required for it to be used for the general expenses accounting."
3)
;; NB: The approach to the design of the "virtual members" (those who aren't
;; backed with a user but nevertheless occupy a personal account) in the
;; personal accounting case.
;; - Do they count when determining the use case for a chat?
;; At the moment, they DO NOT count. Only real chat members do.
;; - Are they merely different accounts for personal budgeting?
;; This bot was not intended for a full-featured accounting.
(defn- is-chat-for-group-accounting?
"Determines the use case for a chat by the number of its members."
[chat-members-count]
(and (some? chat-members-count) ;; a private chat with the bot
(>= chat-members-count min-chat-members-for-group-accounting)))
;; MESSAGE TEMPLATES & CALLBACK DATA
(def ^:private cd-back "<back>")
(def ^:private cd-undo "<undo>")
(def ^:private cd-done "<done>")
(def ^:private cd-accounts "<accounts>")
(def ^:private cd-accounts-create "<accounts/create>")
(def ^:private cd-accounts-rename "<accounts/rename>")
(def ^:private cd-accounts-revoke "<accounts/revoke>")
(def ^:private cd-accounts-reinstate "<accounts/reinstate>")
(def ^:private cd-expense-items "<expense_items>")
(def ^:private cd-expense-items-create "<expense_items/create>")
(def ^:private cd-expense-items-redesc "<expense_items/redesc>")
(def ^:private cd-expense-items-recode "<expense_items/recode>")
(def ^:private cd-expense-items-delete "<expense_items/delete>")
(def ^:private cd-shares "<shares>")
;; TODO: What about <language_and_currency>?
(def ^:private id-separator "::")
(def ^:private cd-group-chat-prefix (str "gc" id-separator))
(def ^:private cd-expense-item-prefix (str "ei" id-separator))
(def ^:private cd-account-prefix (str "ac" id-separator))
(def ^:private cd-account-type-prefix (str "at" id-separator))
(def ^:private cd-digits-set #{"1" "2" "3" "4" "5" "6" "7" "8" "9" "0" ","})
(def ^:private cd-ar-ops-set #{"+" "–"})
(def ^:private cd-cancel "C")
(def ^:private cd-clear "<-")
(def ^:private cd-enter "OK")
;; TODO: Proper localization (with fn).
(def ^:private back-button-text "<< назад")
(def ^:private undo-button-text "Отмена")
(def ^:private done-button-text "Готово")
(def ^:private unknown-failure-text "Что-то пошло не так.")
(def ^:private default-general-acc-name "общие расходы")
(def ^:private account-types-names {:acc-type/personal {:single "Личный" :plural "Личные"}
:acc-type/group {:single "Групповой" :plural "Групповые"}
:acc-type/general {:single "Общий"}})
(def ^:private select-account-txt "Выберите счёт:")
(def ^:private select-payer-account-txt "Выберите тех, кто понёс расход:")
;; "Error while saving data. Please, try again later." (en)
(def ^:private data-persistence-error "Ошибка при сохранении данных. Пожалуйста, повторите попытку позже.")
(def ^:private no-debtor-account-error "Нет возможности выбрать счёт для данного расхода.")
(def ^:private no-group-to-record-error "Нет возможности выбрать группу для записи расходов.")
(defn- join-into-text
([strings-or-colls]
(join-into-text strings-or-colls "\n\n"))
([strings-or-colls sep]
(str/join sep (flatten strings-or-colls))))
(defn- format-list
([items-coll]
(format-list items-coll nil))
([items-coll {:keys [bullet item-sep text-map-fn escape-md?]
:or {bullet "•"
item-sep "\n"
text-map-fn identity}
:as _?opts}]
(let [list-str (->> items-coll
(map #(str (when (some? bullet)
(str bullet " "))
(text-map-fn %)))
(str/join item-sep))]
(if escape-md? (md-v2/escape list-str) list-str))))
(defn- format-currency
[amount lang]
(String/format (Locale/forLanguageTag lang)
"%.2f" ;; receives BigDecimal
(to-array [(bigdec amount)])))
;; TODO: Use the newly introduced 'placeholder' option.
(def ^:private force-reply-options
(tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup :force-reply {:selective true})
:parse-mode "MarkdownV2"}))
(defn- build-items-selection-markup
[items-buttons ?extra-buttons]
(let [extra-buttons (when (some? ?extra-buttons)
(for [extra-btn ?extra-buttons]
[extra-btn]))
;; NB: A 'vec' is used to keep extra buttons below the regular ones.
all-kbd-btns (into (vec items-buttons) extra-buttons)]
{:reply-markup (tg-api/build-reply-markup :inline-keyboard all-kbd-btns)}))
(defn- get-select-one-item-markup
([items name-extr-fn key-extr-fn val-extr-fn]
(get-select-one-item-markup items name-extr-fn key-extr-fn val-extr-fn nil))
([items name-extr-fn key-extr-fn val-extr-fn ?extra-buttons]
(let [items-btns (for [item items]
[(tg-api/build-inline-kbd-btn (name-extr-fn item)
(key-extr-fn item)
(val-extr-fn item))])]
(build-items-selection-markup items-btns ?extra-buttons))))
(defn- get-select-multiple-items-markup
([selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn]
(get-select-multiple-items-markup selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn nil))
([selected-items remaining-items
name-extr-fn key-extr-fn val-extr-fn
?extra-buttons]
(let [sel-items-btns (for [item selected-items]
[(tg-api/build-inline-kbd-btn (str "✔ " (name-extr-fn item))
(key-extr-fn item)
(val-extr-fn item))])
rem-items-btns (for [item remaining-items]
[(tg-api/build-inline-kbd-btn (name-extr-fn item)
(key-extr-fn item)
(val-extr-fn item))])
all-items-btns (concat sel-items-btns rem-items-btns)]
(build-items-selection-markup all-items-btns ?extra-buttons))))
(defn- get-group-ref-option-id
[group-ref]
(str cd-group-chat-prefix (:id group-ref)))
(defn- group-refs->options
[group-refs]
(get-select-one-item-markup group-refs
:title
(constantly :callback-data)
get-group-ref-option-id))
(defn- get-expense-item-display-value
[[code data]]
(str (str/upper-case code) " (" (:desc data) ")"))
(defn- get-expense-item-option-id
[[code _data]]
(str cd-expense-item-prefix code))
(defn- expense-items->options
[expense-items & extra-buttons]
(get-select-one-item-markup (seq expense-items)
get-expense-item-display-value
(constantly :callback-data)
get-expense-item-option-id
extra-buttons))
(defn- get-account-option-id
[acc]
(str cd-account-prefix (name (:type acc)) id-separator (:id acc)))
(defn- accounts->options
[accounts & extra-buttons]
(get-select-one-item-markup accounts
:name
(constantly :callback-data)
get-account-option-id
extra-buttons))
(defn- get-account-type-option-id
[acc-type]
(str cd-account-type-prefix (name acc-type)))
(defn- account-types->options
[account-types & extra-buttons]
(get-select-one-item-markup account-types
#(get-in account-types-names [% :single])
(constantly :callback-data)
get-account-type-option-id
extra-buttons))
(def ^:private back-button
(tg-api/build-inline-kbd-btn back-button-text :callback-data cd-back))
(defn- get-retry-commands-msg
[commands]
{:type :text
:text (format
(str unknown-failure-text " Пожалуйста, повторите %s %s %s.")
(if (next commands) "команды" "команду")
(->> commands
(map (partial str "/"))
(str/join ", "))
(if (next commands) "по-отдельности" "через какое-то время"))})
(def ^:private retry-resend-message-msg
{:type :text
:text (str unknown-failure-text " Пожалуйста, отправьте сообщение снова.")})
(def ^:private retry-callback-query-notification
{:type :callback
:options {:text (str unknown-failure-text " Пожалуйста, повторите действие.")}})
; group chats
; - basic messages
;; TODO: Make messages texts localizable:
;; - take the ':language_code' of the chat initiator (no personal settings)
;; - externalize texts, keep only their keys (to get them via 'l10n')
(defn- get-introduction-msg
[chat-members-count first-name]
{:type :text
:text (apply format "Привет, %s! Я — бот-бухгалтер. И я призван помочь %s с учётом %s общих расходов.\n
Для того, чтобы начать работу, просто %s на следующее сообщение."
(if (= chat-members-count 2)
[first-name "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]
["народ" "вам" "ваших" "ответьте каждый"]))})
(defn- get-personal-account-name-request-msg
[existing-chat? ?chat-members]
{:type :text
:text (let [request-txt (md-v2/escape "как будет называться ваш личный счёт?")
part-one (if (some? ?chat-members)
(let [mentions (for [user ?chat-members]
(tg-api/get-user-mention-text user))]
(str (str/join " " mentions) ", " request-txt))
(str/capitalize request-txt))
part-two (md-v2/escape
(if (and existing-chat? (empty? ?chat-members))
"Пожалуйста, проигнорийруте это сообщение, если у вас уже есть личный счёт в данной группе."
"Пожалуйста, ответьте на данное сообщение."))]
(join-into-text [part-one part-two]))
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:force-reply {:selective (some? ?chat-members)})
:parse-mode "MarkdownV2"})})
(defn- get-personal-accounts-left-msg
[count]
{:type :text
:text (format "Ожидаем остальных... Осталось %s." count)})
(defn- get-bot-readiness-msg
[bot-username]
{:type :text
:text "Я готов к ведению учёта. Давайте же начнём!"
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Перейти в чат для ввода расходов"
:url (str "https://t.me/" bot-username))]])})})
; - settings
(defn- get-settings-msg
[first-time?]
{:type :text
;; TODO: Shorten this text and spread its content between the mgmt views?
:text (format "%s можно настроить, чтобы учитывались:
- счета — не только личные, но и групповые;
- статьи расходов — подходящие по смыслу и удобные вам;
- доли — для статей расходов и ситуаций, когда 50/50 вам не подходит." ;; "По умолчанию равны для любых счетов и статей расходов."
(if (true? first-time?) "Также меня" "Меня"))
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Счета" :callback-data cd-accounts)
(tg-api/build-inline-kbd-btn "Статьи" :callback-data cd-expense-items)
(tg-api/build-inline-kbd-btn "Доли" :callback-data cd-shares)]])})})
(def ^:private successful-changes-msg
{:type :text
:text "Изменения внесены успешно."})
(def ^:private canceled-changes-msg
{:type :text
:text "Внесение изменений отменено."})
; - accounts mgmt
(defn- get-accounts-mgmt-options-msg
[accounts-by-type]
{:type :text
:text (join-into-text
["Список счетов данной группы:"
(map (fn [[acc-type accounts]]
(case acc-type
(:acc-type/personal :acc-type/group)
(str (md-v2/format-bold (get-in account-types-names [acc-type :plural])) "\n"
(format-list accounts {:text-map-fn :name
:escape-md? true}))
:acc-type/general
(md-v2/format-bold "Счёт для общих расходов")))
accounts-by-type)
"Выберите, что вы хотите сделать:"])
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "Создать новый" :callback-data cd-accounts-create)]
[(tg-api/build-inline-kbd-btn "Переименовать" :callback-data cd-accounts-rename)]
[(tg-api/build-inline-kbd-btn "Упразднить" :callback-data cd-accounts-revoke)]
[(tg-api/build-inline-kbd-btn "Восстановить" :callback-data cd-accounts-reinstate)]
[back-button]])
:parse-mode "MarkdownV2"})})
(defn- get-account-selection-msg
([accounts txt]
(get-account-selection-msg accounts txt nil))
([accounts txt ?extra-buttons]
{:pre [(seq accounts)]}
{:type :text
:text txt
:options (tg-api/build-message-options
(apply accounts->options accounts ?extra-buttons))}))
(defn- get-account-type-selection-msg
[account-types extra-buttons]
{:pre [(seq account-types)]}
{:type :text
;; Group account is used to share the expenses between the group members.
;; Personal account is needed in case the person is not present in Telegram.
:text (join-into-text
["Какие счета для чего нужны?"
(str (md-v2/format-bold (get-in account-types-names [:acc-type/group :single])) " — "
(md-v2/escape "используется для распределения расходов между членами группы."))
(str (md-v2/format-bold (get-in account-types-names [:acc-type/personal :single])) " — "
(md-v2/escape "используется в случае, если человека нет в Telegram, но учитывать его при расчётах нужно."))
"Выберите тип счёта:"])
:options (tg-api/build-message-options
(merge (apply account-types->options account-types extra-buttons)
{:parse-mode "MarkdownV2"}))})
(defn- get-new-account-name-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", как бы вы хотели назвать новый счёт?"))
:options force-reply-options})
(defn- get-the-account-name-is-already-taken-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", данное имя счёта уже занято. Выберите другое имя."))
:options force-reply-options})
(defn- get-group-members-selection-msg
[user selected remaining]
(let [extra-buttons [(tg-api/build-inline-kbd-btn undo-button-text :callback-data cd-undo)
(tg-api/build-inline-kbd-btn done-button-text :callback-data cd-done)]]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", выберите члена(ов) группы:"))
:options (tg-api/build-message-options
(merge (get-select-multiple-items-markup selected remaining
:name
(constantly :callback-data)
get-account-option-id
extra-buttons)
{:parse-mode "MarkdownV2"}))}))
(defn- get-new-group-members-msg
[acc-names]
{:pre [(seq acc-names)]}
{:type :text
:text (str "Члены новой группы:\n"
(format-list acc-names))})
(def ^:private no-group-members-selected-notification
{:type :callback
:options {:text "Не выбрано ни одного участника группы"}})
(defn- get-account-rename-request-msg
[user acc-name]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", как бы вы хотели переименовать счёт \"" acc-name "\"?")))
:options force-reply-options})
(def ^:private no-eligible-accounts-notification
{:type :callback
:options {:text "Подходящих счетов не найдено"}})
; - expense items mgmt
(defn- get-expense-items-mgmt-options-msg
[expense-items]
(let [expense-items-seq (seq expense-items)]
{:type :text
:text (if expense-items-seq
(join-into-text
["Список статей расходов:"
(format-list expense-items-seq {:text-map-fn get-expense-item-display-value
:escape-md? true})
"Выберите, что вы хотите сделать:"])
(md-v2/escape "Статьи расходов не заданы."))
:options (let [action-btns (cond-> [[(tg-api/build-inline-kbd-btn "Добавить новую" :callback-data cd-expense-items-create)]]
(some? expense-items-seq)
(conj [(tg-api/build-inline-kbd-btn "Изменить описание" :callback-data cd-expense-items-redesc)]
[(tg-api/build-inline-kbd-btn "Изменить код" :callback-data cd-expense-items-recode)]
[(tg-api/build-inline-kbd-btn "Удалить" :callback-data cd-expense-items-delete)]))]
(tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup
:inline-keyboard (conj action-btns [back-button]))
:parse-mode "MarkdownV2"}))}))
(defn- get-new-expense-item-desc-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", как бы вы описали новую статью расходов? Что в неё входит?"))
:options force-reply-options})
(defn- get-new-expense-item-code-request-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", придумайте кодовое обозначение для данной статью расходов. Это может быть простой текст, например \"пр\" для продуктов, или эмодзи, например ☕️ для еды вне дома."))
:options force-reply-options})
(defn- get-the-expense-item-code-is-already-used-msg
[user]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape ", данный код уже используется для другой статьи расходов. Выберите другой код."))
:options force-reply-options})
(defn- get-the-expense-item-cannot-be-deleted-msg
[exp-it-code exp-it-desc]
{:type :text
:text (format "Статья расходов \"%s (%s)\" не может быть удалена, поскольку была использована ранее."
exp-it-code exp-it-desc)})
(def ^:private no-eligible-expense-items-notification
{:type :callback
:options {:text "Подходящих статей расходов не найдено"}})
(defn- get-expense-item-redesc-request-msg
[user exp-it-desc]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", как бы вы по-другому описали статью расходов \"" exp-it-desc "\"?")))
:options force-reply-options})
(defn- get-expense-item-recode-request-msg
[user exp-it-desc]
{:type :text
:text (str (tg-api/get-user-mention-text user)
(md-v2/escape (str ", задайте новый код для статьи расходов \"" exp-it-desc "\".")))
:options force-reply-options})
;; TODO: Add messages for 'shares' here.
; - expenses
(defn- get-new-expense-msg
[expense-amount expense-details payer-acc-name debtor-acc-name]
(let [formatted-amount (format-currency expense-amount "ru")
title-txt (when (some? payer-acc-name)
(str (md-v2/format-bold (md-v2/escape payer-acc-name)) "\n"))
details-txt (->> [(str formatted-amount "₽")
debtor-acc-name
expense-details]
(filter some?)
(str/join " / ")
md-v2/escape)]
{:type :text
:text (str title-txt details-txt)
:options (tg-api/build-message-options
{:parse-mode "MarkdownV2"})}))
; - warnings
(def ^:private waiting-for-user-input-notification
{:type :callback
:options {:text "Ожидание ответа пользователя в чате"}})
(def ^:private waiting-for-other-user-notification
{:type :callback
:options {:text "Ответ ожидается от другого пользователя"}})
(def ^:private message-already-in-use-notification
{:type :callback
:options {:text "С этим сообщением уже взаимодействуют"}})
(def ^:private ignored-callback-query-notification
{:type :callback
:options {:text "Запрос не может быть обработан"}})
; private chats
(defn- get-private-introduction-msg
[first-name]
{:type :text
:text (str "Привет, " first-name "! Чтобы добавить новый расход просто напиши мне сумму.")})
(def ^:private invalid-input-msg
{:type :text
:text "Пожалуйста, введите число. Например, \"145,99\"."})
(def ^:private inline-calculator-markup
(tg-api/build-reply-markup
:inline-keyboard
[[(tg-api/build-inline-kbd-btn "7" :callback-data "7")
(tg-api/build-inline-kbd-btn "8" :callback-data "8")
(tg-api/build-inline-kbd-btn "9" :callback-data "9")
(tg-api/build-inline-kbd-btn "C" :callback-data cd-cancel)]
[(tg-api/build-inline-kbd-btn "4" :callback-data "4")
(tg-api/build-inline-kbd-btn "5" :callback-data "5")
(tg-api/build-inline-kbd-btn "6" :callback-data "6")
(tg-api/build-inline-kbd-btn "+" :callback-data "+")]
[(tg-api/build-inline-kbd-btn "1" :callback-data "1")
(tg-api/build-inline-kbd-btn "2" :callback-data "2")
(tg-api/build-inline-kbd-btn "3" :callback-data "3")
(tg-api/build-inline-kbd-btn "–" :callback-data "–")]
[(tg-api/build-inline-kbd-btn "0" :callback-data "0")
(tg-api/build-inline-kbd-btn "," :callback-data ",")
(tg-api/build-inline-kbd-btn "←" :callback-data cd-clear)
(tg-api/build-inline-kbd-btn "OK" :callback-data cd-enter)]]))
(defn- get-interactive-input-msg
([text]
(get-interactive-input-msg text nil))
([text ?extra-opts]
{:type :text
:text (str (md-v2/escape "Новый расход:\n= ") text)
:options (tg-api/build-message-options
(merge {:parse-mode "MarkdownV2"} ?extra-opts))}))
(defn- get-inline-calculator-msg
[user-input]
(get-interactive-input-msg
(md-v2/escape (str user-input "_"))
{:reply-markup inline-calculator-markup}))
(defn- get-interactive-input-success-msg
[amount]
(get-interactive-input-msg
(md-v2/escape (format-currency amount "ru"))))
(def ^:private interactive-input-disclaimer-msg
{:type :text
:text "Введите /cancel, чтобы выйти из режима калькуляции и ввести данные вручную."})
(def ^:private invalid-input-notification
{:type :callback
:options {:text "Ошибка в выражении! Вычисление невозможно."}})
(defn- get-added-to-new-group-msg
[chat-title]
{:type :text
:text (str "Вас добавили в группу \"" chat-title "\".")})
(defn- get-removed-from-group-msg
[chat-title]
{:type :text
:text (str "Вы покинули группу \"" chat-title "\".")})
(defn- get-group-selection-msg
[group-refs]
{:pre [(seq group-refs)]}
{:type :text
:text "Выберите, к какой группе отнести расход:"
:options (tg-api/build-message-options
(group-refs->options group-refs))})
(defn- get-expense-item-selection-msg
([expense-items]
(get-expense-item-selection-msg expense-items nil))
([expense-items ?extra-buttons]
{:pre [(seq expense-items)]}
{:type :text
:text "Выберите статью расходов:"
:options (tg-api/build-message-options
(apply expense-items->options expense-items ?extra-buttons))}))
(defn- get-expense-manual-description-msg
[user-name]
{:type :text
:text (str user-name ", опишите расход в двух словах:")
:options (tg-api/build-message-options
{:reply-markup (tg-api/build-reply-markup :force-reply)})})
(def ^:private expense-added-successfully-msg
{:type :text
:text "Запись успешно внесена в ваш гроссбух."})
(defn- get-failed-to-add-new-expense-msg
[reason]
{:type :text
:text (str/join " " ["Не удалось добавить новый расход." reason])})
;; AUXILIARY FUNCTIONS
(defn get-datetime-in-tg-format
[]
(quot (System/currentTimeMillis) 1000))
(defn- is-failure?
"Checks if something resulted in a failure."
[res]
(and (keyword? res)
(= "failure" (namespace res))))
;; - CHATS
(defn- does-chat-exist?
[chat-id]
(contains? (get-bot-data) chat-id))
(def ^:private default-chat-state :initial)
(defn- setup-new-chat!
[chat-id new-chat]
(when-not (does-chat-exist? chat-id) ;; petty RC
(let [new-chat (chats/create! (assoc new-chat :id chat-id))]
(update-bot-data! assoc chat-id new-chat)
new-chat)))
;; TODO: Add a logical ID attr, e.g. UID, to track all group versions.
(defn- setup-new-group-chat!
[chat-id chat-title chat-members-count]
(setup-new-chat! chat-id {:type :chat-type/group
:data {:state default-chat-state
:title chat-title
:members-count chat-members-count
:accounts {:last-id -1}}}))
(defn- setup-new-supergroup-chat!
[chat-id migrate-from-id]
(setup-new-chat! chat-id {:type :chat-type/supergroup
:data migrate-from-id}))
(defn- setup-new-private-chat!
[chat-id group-chat-id]
(setup-new-chat! chat-id {:type :chat-type/private,
:data {:state default-chat-state
:groups #{group-chat-id}}}))
(defn- get-real-chat-id
"Returns the chat 'id' with built-in insurance for the 'supergroup' chats."
([chat-id]
(get-real-chat-id (get-bot-data) chat-id))
([bot-data chat-id]
(let [chat (get bot-data chat-id)]
(if (= :chat-type/supergroup (:type chat))
(:data chat) ;; target group chat-id
chat-id))))
(defn- get-chat-data
"Returns the JSON data associated with a chat with the specified 'chat-id'."
([chat-id]
(get-chat-data (get-bot-data) chat-id))
([bot-data chat-id]
(when-let [real-chat-id (get-real-chat-id bot-data chat-id)]
(get-in bot-data [real-chat-id :data]))))
(defn- -update-chat!
[chat-to-upd]
(if (chats/update! chat-to-upd)
(:data chat-to-upd)
(throw (ex-info "Failed to persist an updated chat" {:chat chat-to-upd}))))
(defn- update-chat-data!
[chat-id upd-fn & upd-fn-args]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
bot-data (apply update-bot-data!
update-in [real-chat-id :data] upd-fn upd-fn-args)
upd-chat (get bot-data real-chat-id)]
(-update-chat! upd-chat)))
(defn- conditionally-update-chat-data!
[chat-id pred upd-fn & upd-fn-args]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
bot-data (apply conditionally-update-bot-data!
#(pred (get-in % [real-chat-id :data]))
update-in [real-chat-id :data] upd-fn upd-fn-args)
upd-chat (get bot-data real-chat-id)]
(when (some? upd-chat)
(-update-chat! upd-chat))))
(defn- assoc-in-chat-data!
[chat-id [key & ks] ?value]
{:pre [(does-chat-exist? chat-id)]}
(let [real-chat-id (get-real-chat-id chat-id)
full-path (concat [real-chat-id :data key] ks)
bot-data (if (nil? ?value)
(update-bot-data! update-in (butlast full-path)
dissoc (last full-path))
(update-bot-data! assoc-in full-path ?value))
upd-chat (get bot-data real-chat-id)]
(-update-chat! upd-chat)))
(defn- get-chat-state
"Determines the state of the given chat. Returns 'nil' in case the group chat
or user is unknown (the input is 'nil') and a valid default in case there is
no preset state.
NB: Be aware that calling this function, e.g. during a state change,
may cause a race condition (RC) and result in an obsolete value."
[chat-data]
(get chat-data :state
(when (some? chat-data) default-chat-state)))
(defn- change-chat-state!
[chat-id chat-type-states new-state]
{:pre [(does-chat-exist? chat-id)]}
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [curr-state (get-chat-state chat-data)
possible-new-states (or (-> chat-type-states curr-state :to)
(-> chat-type-states curr-state))]
(if (contains? possible-new-states new-state)
(let [state-init-fn (-> chat-type-states new-state :init-fn)]
(cond-> chat-data
(some? state-init-fn) (state-init-fn)
:and-most-importantly (assoc :state new-state)))
(do
(log/errorf "Failed to change state to '%s' for chat=%s with current state '%s'"
new-state chat-id curr-state)
chat-data)))))]
(get-chat-state updated-chat-data)))
;; - BOT STATUS
(defn- does-bot-manage-the-chat?
[{?chat-id :chat-id ?chat-state :chat-state}]
{:pre [(or (some? ?chat-id) (some? ?chat-state))]}
(let [chat-state (or ?chat-state
(and (does-chat-exist? ?chat-id)
(get-chat-state (get-chat-data ?chat-id))))]
(= :managed chat-state)))
(defn- is-bot-evicted-from-chat?
[chat-id]
(and (does-chat-exist? chat-id)
(= :evicted (get-chat-state (get-chat-data chat-id)))))
;; - ACCOUNTS
(defn- ->general-account
[id name created members]
{:id id
:type :acc-type/general
:name name
:created created
:members (set members)})
(defn- ->personal-account
[id name created ?user-id ?msg-id]
(cond-> {:id id
:type :acc-type/personal
:name name
:created created}
(some? ?user-id) (assoc :user-id ?user-id)
(some? ?msg-id) (assoc :msg-id ?msg-id)))
(defn- ->group-account
[id name created created-by members]
{:id id
:type :acc-type/group
:name name
:created created
:created-by created-by
:members (set members)})
(defn- is-account-revoked?
[acc]
(contains? acc :revoked))
(defn- is-account-active?
[acc]
(not (is-account-revoked? acc)))
;; - CHATS > ACCOUNTS
(defn- get-members-count
[chat-data]
(:members-count chat-data))
(defn- update-members-count!
[chat-id update-fn]
(update-chat-data! chat-id
update :members-count update-fn))
(defn- get-accounts-of-type
([chat-data acc-type]
(map val (get-in chat-data [:accounts acc-type])))
([chat-data acc-type ?filter-pred]
(cond->> (get-accounts-of-type chat-data acc-type)
(some? ?filter-pred) (filter ?filter-pred))))
(defn- get-account-by-id
[chat-data acc-type acc-id]
(get-in chat-data [:accounts acc-type acc-id]))
(defn- get-accounts-next-id
[chat-data]
(-> chat-data :accounts :last-id inc))
(defn- find-account-by-name
[chat-data acc-type acc-name]
;; NB: Personal and group account names must be unique.
(first (get-accounts-of-type chat-data acc-type
#(= (:name %) acc-name))))
(defn- create-named-account!
"Attempts to create a named type account with a name uniqueness check."
[chat-id acc-type acc-name constructor-fn]
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-account-by-name % acc-type acc-name))
(fn [chat-data]
(let [next-id (get-accounts-next-id chat-data)
upd-accounts-next-id #(assoc-in % [:accounts :last-id] next-id)]
(constructor-fn (upd-accounts-next-id chat-data) next-id))))]
(if (some? updated-chat-data)
(find-account-by-name updated-chat-data acc-type acc-name)
:failure/the-account-name-is-already-taken)))
;; - CHATS > ACCOUNTS > GENERAL
(defn- get-current-general-account
"Retrieves the current (the one that will be used) account of 'general' type
from the provided chat data.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact '?filter-pred'.
In the latter case, the most recent general account will be returned."
([chat-data]
(get-current-general-account chat-data is-account-active?))
([chat-data ?filter-pred]
(let [gen-accs (get-accounts-of-type chat-data
:acc-type/general
?filter-pred)]
(if (< 1 (count gen-accs))
(do
(log/warnf "There is more than 1 suitable general account in chat=%s"
(:id chat-data)) ;; it might be ok for custom 'filter-pred'
(apply max-key :id gen-accs))
(first gen-accs)))))
(defn- create-general-account!
[chat-id created-dt & {:keys [remove-member add-member] :as _opts}]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [old-gen-acc (get-current-general-account chat-data)
old-members (->> (get-accounts-of-type chat-data
:acc-type/personal
is-account-active?)
(map :id)
set)
new-members (cond-> old-members
(some? add-member) (conj add-member)
(some? remove-member) (disj remove-member))
upd-old-general-acc-fn
(fn [cd]
(if (some? old-gen-acc)
(assoc-in cd
[:accounts :acc-type/general (:id old-gen-acc) :revoked]
created-dt)
cd))
add-new-general-acc-fn
(fn [cd]
;; IMPLEMENTATION NOTE:
;; Here the chat 'members-count' have to already be updated!
(if (is-chat-for-group-accounting? (get-members-count cd))
(let [next-id (get-accounts-next-id cd)
acc-name (:name old-gen-acc default-general-acc-name)
new-general-acc (->general-account
next-id acc-name created-dt new-members)]
(-> cd
(assoc-in [:accounts :last-id] next-id)
(assoc-in [:accounts :acc-type/general next-id] new-general-acc)))
cd))]
(-> chat-data
upd-old-general-acc-fn
add-new-general-acc-fn))))]
(get-current-general-account updated-chat-data)))
;; - CHATS > ACCOUNTS > PERSONAL
(defn- get-personal-account-id
"A convenient way to get both user and virtual accounts ID."
[chat-data {?user-id :user-id ?acc-name :name :as _ids}]
{:pre [(or (some? ?user-id) (some? ?acc-name))]}
(if (some? ?user-id)
(get-in chat-data [:user-account-mapping ?user-id])
(:id (find-account-by-name chat-data :acc-type/personal ?acc-name))))
(defn- set-personal-account-id
[chat-data user-id pers-acc-id]
{:pre [(some? user-id)]}
(assoc-in chat-data [:user-account-mapping user-id] pers-acc-id))
(defn- get-personal-account
[chat-data {?user-id :user-id ?acc-name :name ?acc-id :id :as ids}]
{:pre [(or (some? ?user-id) (some? ?acc-name) (some? ?acc-id))]}
(cond
(some? ?acc-id)
(get-account-by-id chat-data :acc-type/personal ?acc-id)
(some? ?acc-name)
(find-account-by-name chat-data :acc-type/personal ?acc-name)
(some? ?user-id)
(let [pers-acc-id (get-personal-account-id chat-data ids)]
(get-account-by-id chat-data :acc-type/personal pers-acc-id))))
(defn- create-personal-account!
[chat-id acc-name created-dt & {?user-id :user-id ?first-msg-id :first-msg-id :as _opts}]
(if (or (nil? ?user-id)
(let [pers-acc (get-personal-account (get-chat-data chat-id) {:user-id ?user-id})] ;; petty RC
(or (nil? pers-acc) (is-account-revoked? pers-acc))))
(create-named-account!
chat-id :acc-type/personal acc-name
(fn [chat-data acc-id]
(let [pers-acc (->personal-account acc-id acc-name created-dt
?user-id ?first-msg-id)]
(cond-> (assoc-in chat-data [:accounts :acc-type/personal acc-id] pers-acc)
(some? ?user-id) (set-personal-account-id ?user-id acc-id)))))
:failure/user-already-has-an-active-account))
;; - CHATS > ACCOUNTS > GROUP
(defn- get-group-account
[chat-data {?acc-name :name ?acc-id :id :as _ids}]
{:pre [(or (some? ?acc-name) (some? ?acc-id))]}
(cond
(some? ?acc-id)
(get-account-by-id chat-data :acc-type/group ?acc-id)
(some? ?acc-name)
(find-account-by-name chat-data :acc-type/group ?acc-name)))
(defn- create-group-account!
[chat-id acc-name created-dt created-by members-ids]
(create-named-account!
chat-id :acc-type/group acc-name
(fn [chat-data acc-id]
(let [group-acc (->group-account acc-id acc-name created-dt created-by members-ids)]
(assoc-in chat-data [:accounts :acc-type/group acc-id] group-acc)))))
;; - CHATS > BOT MESSAGES
(defn- get-bot-msg
[chat-data msg-id]
(get-in chat-data [:bot-messages msg-id]))
(defn- set-bot-msg!
[chat-id msg-id {:keys [type] :as ?props}]
{:pre [(or (nil? ?props) (some? type))]}
(assoc-in-chat-data! chat-id [:bot-messages msg-id] ?props))
(defn- find-bot-messages
[chat-data {:keys [type to-user] :as _props}]
(cond->> (:bot-messages chat-data)
(some? type) (filter #(= type (-> % val :type)))
(some? to-user) (filter #(= to-user (-> % val :to-user)))))
(defn- drop-bot-msg!
[chat-id {:keys [type to-user] :as props}]
{:pre [(or (some? type) (some? to-user))]}
(let [to-drop (map key (find-bot-messages (get-chat-data chat-id) props))]
(update-chat-data! chat-id
update-in [:bot-messages] #(apply dissoc % to-drop))
to-drop))
(defn- get-original-bot-msg
[chat-id reply-msg]
;; NB: There's always only one original msg.
(->> (:bot-messages (get-chat-data chat-id))
(filter #(tg-api/is-reply-to? (key %) reply-msg))
(map (fn [[k v]] (assoc v :msg-id k)))
first))
(defn- check-bot-msg
[bot-msg {:keys [type to-user] :as props}]
{:pre [(or (some? type) (some? to-user))]}
(when (some? bot-msg)
(every? #(= (val %) (-> % key bot-msg)) props)))
(defn- change-bot-msg-state!
[chat-id msg-id msg-type-states new-state]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [bot-msg (get-bot-msg chat-data msg-id)
curr-state (:state bot-msg)]
(if (or (nil? curr-state) ;; to set an initial state
(contains? (get msg-type-states curr-state) new-state))
(assoc-in chat-data [:bot-messages msg-id :state] new-state)
(do
(log/errorf "Failed to change state from '%s' to '%s' for message=%s in chat=%s"
curr-state new-state msg-id chat-id)
chat-data)))))]
(:state (get-bot-msg updated-chat-data msg-id))))
;; - CHATS > GROUP CHAT
(defn- get-chat-title
[chat-data]
(:title chat-data))
(defn- set-chat-title!
[chat-id chat-title]
(assoc-in-chat-data! chat-id [:title] chat-title))
;; - CHATS > GROUP CHAT > EXPENSE ITEMS
;; TODO: Optionally sort them according popularity.
(defn- get-group-chat-expense-items
[chat-data]
(:expense-items chat-data))
(defn- find-expense-item
[chat-data exp-it-code]
(get (get-group-chat-expense-items chat-data) exp-it-code))
(defn- create-group-chat-expense-item!
[chat-id {:keys [exp-it-code exp-it-data]}]
{:pre [(some? exp-it-code) (some? exp-it-data)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-expense-item % exp-it-code))
#(assoc-in % [:expense-items exp-it-code] exp-it-data))]
(if (some? updated-chat-data)
(find-expense-item updated-chat-data exp-it-code)
:failure/the-expense-item-code-is-already-used)))
(defn- update-group-chat-expense-item!
[chat-id {:keys [exp-it-code exp-it-data]}]
{:pre [(some? exp-it-code) (some? exp-it-data)]}
(let [updated-chat-data
(update-chat-data!
chat-id
update-in [:expense-items exp-it-code] merge exp-it-data)]
(find-expense-item updated-chat-data exp-it-code)))
(defn- change-group-chat-expense-item-code!
[chat-id {:keys [exp-it-code new-exp-it-code]}]
{:pre [(some? exp-it-code) (some? new-exp-it-code)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-expense-item % new-exp-it-code))
(fn [chat-data]
(-> chat-data
(update :expense-items dissoc exp-it-code)
(assoc-in [:expense-items new-exp-it-code]
(get-in chat-data [:expense-items exp-it-code])))))]
(if (some? updated-chat-data)
(find-expense-item updated-chat-data new-exp-it-code)
:failure/the-expense-item-code-is-already-used)))
(defn- can-expense-item-be-deleted?
[[_code data]]
(not (and (contains? data :pops)
(< 0 (:pops data)))))
(defn- delete-group-chat-expense-item!
[chat-id exp-it-to-delete]
{:pre [(some? exp-it-to-delete)]}
(let [exp-it-code (first exp-it-to-delete)
updated-chat-data
(conditionally-update-chat-data!
chat-id
#(let [exp-it (find-expense-item % exp-it-code)]
(can-expense-item-be-deleted? [exp-it-code exp-it]))
#(update % :expense-items dissoc exp-it-code))]
(if (some? updated-chat-data)
true
:failure/the-expense-item-cannot-be-deleted)))
(defn- data->expense-item
"Retrieves a group chat's expense item by parsing the callback button data."
[callback-btn-data chat-data]
(let [exp-it-code (str/replace-first callback-btn-data cd-expense-item-prefix "")]
[exp-it-code (find-expense-item chat-data exp-it-code)]))
;; - CHATS > GROUP CHAT > ACCOUNTS
(def ^:private all-account-types
[:acc-type/personal :acc-type/group :acc-type/general])
(defn- get-group-chat-accounts
"Retrieves accounts of all or specific types (if the 'acc-types' is present)
for a group chat with the specified 'chat-id'.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact 'filter-pred'."
;; TODO: Sort them according popularity.
([chat-id]
(get-group-chat-accounts chat-id
{:acc-types all-account-types}))
([chat-id {:keys [acc-types filter-pred sort-by-popularity]
:or {acc-types all-account-types
filter-pred is-account-active?}}]
(if (< 1 (count acc-types))
;; multiple types
(->> acc-types
(mapcat #(get-group-chat-accounts chat-id
{:acc-types [%]
:filter-pred filter-pred})))
;; single type
(when-let [chat-data (get-chat-data chat-id)]
(get-accounts-of-type chat-data (first acc-types) filter-pred)))))
(defn- get-group-chat-accounts-by-type
"Retrieves accounts, grouped in a map by account type, for a group chat with
the specified 'chat-id'.
NB: This function differs from the plain vanilla 'get-accounts-of-type' one
in that it filters out inactive (revoked) accounts by default. However,
this behavior can be overridden by providing the exact '?filter-pred'."
([chat-id]
(get-group-chat-accounts-by-type chat-id is-account-active?))
([chat-id ?filter-pred]
(group-by :type
(get-group-chat-accounts chat-id
{:acc-types all-account-types
:filter-pred ?filter-pred}))))
(defn- is-not-virtual-member?
[acc]
(and (is-account-active? acc)
(some? (:user-id acc))))
(defn- get-number-of-missing-personal-accounts
"Returns the number of missing personal accounts in a group chat,
which have to be created before the group chat is ready for the
expenses accounting."
[chat-id]
(let [chat-members-count (get-members-count (get-chat-data chat-id))
existing-pers-accs (->> {:acc-types [:acc-type/personal]
:filter-pred is-not-virtual-member?}
(get-group-chat-accounts chat-id)
count)]
(- chat-members-count existing-pers-accs 1)))
(defn- is-group-acc-member?
[chat-id group-acc user-id]
(let [chat-data (get-chat-data chat-id)
pers-acc-id (get-personal-account-id chat-data {:user-id user-id})
group-acc-members (:members group-acc)]
(contains? group-acc-members pers-acc-id)))
(defn- all-group-acc-members-are-inactive?
[chat-id group-acc]
(let [group-acc-members (:members group-acc)]
(->> {:acc-types [:acc-type/personal]
:filter-pred #(and (is-account-active? %)
(contains? group-acc-members (:id %)))}
(get-group-chat-accounts chat-id)
empty?)))
(defn- can-rename-account?
[chat-id user-id]
(fn [acc]
(and (is-account-active? acc)
(or (and (= :acc-type/personal (:type acc))
(contains? #{user-id nil} (:user-id acc)))
(and (= :acc-type/group (:type acc))
(or (= (:created-by acc) user-id)
(is-group-acc-member? chat-id acc user-id)
(all-group-acc-members-are-inactive? chat-id acc)))))))
(defn- can-revoke-account?
[chat-id user-id]
(fn [acc]
(and (is-account-active? acc)
(or (and (= :acc-type/personal (:type acc))
(not= (:user-id acc) user-id))
(and (= :acc-type/group (:type acc))
(or (= (:created-by acc) user-id)
(is-group-acc-member? chat-id acc user-id)
(all-group-acc-members-are-inactive? chat-id acc)))))))
(defn- can-reinstate-account?
[_chat-id _user-id]
(fn [acc]
(is-account-revoked? acc)))
(defn- get-group-chat-account
[chat-data {acc-type :type :as props}]
(case acc-type
:acc-type/personal
(get-personal-account chat-data props)
:acc-type/group
(get-group-account chat-data props)
:acc-type/general
(get-current-general-account chat-data)))
(defn- is-group-chat-eligible-for-selection?
"Checks the ability of a specified user to select a given group chat."
[chat-id user-id]
(let [chat-data (get-chat-data chat-id)
pers-acc (get-group-chat-account chat-data {:type :acc-type/personal
:user-id user-id})]
(is-account-active? pers-acc)))
(defn- data->account
"Retrieves a group chat's account by parsing the callback button data."
[callback-btn-data chat-data]
(let [account (str/replace-first callback-btn-data cd-account-prefix "")
account-path (str/split account (re-pattern id-separator))]
(get-group-chat-account chat-data
{:type (keyword "acc-type" (nth account-path 0))
:id (u-nums/parse-int (nth account-path 1))})))
(defn- create-group-chat-account!
[chat-id {:keys [acc-type acc-name created-dt created-by members]}]
{:pre [(some? acc-type) (some? acc-name) (some? created-dt)]}
(case acc-type
:acc-type/personal (when-some [pers-acc (create-personal-account! chat-id acc-name created-dt)]
(create-general-account! chat-id created-dt)
pers-acc)
:acc-type/group (let [members-ids (map :id members)]
(create-group-account! chat-id acc-name created-dt created-by members-ids))))
(defn- change-group-chat-account-name!
[chat-id {:keys [acc-type acc-id new-acc-name]}]
{:pre [(some? acc-type) (some? acc-id) (some? new-acc-name)]}
(let [updated-chat-data
(conditionally-update-chat-data!
chat-id
#(nil? (find-account-by-name % acc-type new-acc-name))
assoc-in [:accounts acc-type acc-id :name] new-acc-name)]
(if (some? updated-chat-data)
(get-group-chat-account updated-chat-data {:type acc-type
:id acc-id})
:failure/the-account-name-is-already-taken)))
(defn- change-account-activity-status!
"Changes the activity status of a personal or group account (just marks it as
'revoked' or removes this mark) and, for personal accounts only, updates the
general account (revokes an existing and creates a new version, if needed)."
[chat-id acc {:keys [revoke? reinstate? datetime] :as _activity_status_upd}]
{:pre [(or (some? revoke?) (some? reinstate?))
(not (and (some? revoke?) (some? reinstate?)))
(contains? #{:acc-type/personal :acc-type/group} (:type acc))]}
(let [acc-id (:id acc)
acc-type (:type acc)
updated-chat-data
(conditionally-update-chat-data!
chat-id
#(some? (get-account-by-id % acc-type acc-id))
(fn [chat-data]
(cond-> chat-data
(true? revoke?)
(assoc-in [:accounts acc-type acc-id :revoked] datetime)
(true? reinstate?)
(update-in [:accounts acc-type acc-id] dissoc :revoked))))]
(when (= :acc-type/personal (:type acc))
(let [member-action (cond
(true? revoke?) :remove-member
(true? reinstate?) :add-member)]
(create-general-account! chat-id datetime member-action acc-id)))
(get-account-by-id updated-chat-data acc-type acc-id)))
;; - CHATS > GROUP CHAT > USER INPUT
(defn- get-user-input-data
[chat-data user-id input-name]
(get-in chat-data [:input user-id input-name]))
(defn- set-user-input-data!
[chat-id user-id input-name ?input-data]
(if (nil? ?input-data)
(update-chat-data! chat-id
update-in [:input user-id] dissoc input-name)
(update-chat-data! chat-id
assoc-in [:input user-id input-name] ?input-data)))
(defn- drop-user-input-data!
[chat-id user-id]
(update-chat-data! chat-id
update-in [:input] dissoc user-id))
(defn- clean-up-chat-data!
[chat-id {:keys [bot-messages input]}]
(doseq [bot-msg bot-messages]
(drop-bot-msg! chat-id bot-msg))
(doseq [user-input input]
(if (contains? user-input :name)
(set-user-input-data! chat-id (:user user-input) (:name user-input) nil)
(drop-user-input-data! chat-id (:user user-input)))))
(defn- release-message-lock!
"Releases the \"input lock\" acquired by the user for the message in chat."
[chat-id user-id msg-id]
(update-chat-data!
chat-id
(fn [chat-data]
(let [user-locked (get-user-input-data chat-data user-id :locked-messages)]
(if (contains? user-locked msg-id)
(update-in chat-data [:input user-id :locked-messages] set/difference #{msg-id})
chat-data))))
nil)
(defn- acquire-message-lock!
"Acquires an \"input lock\" for a specific message in chat and the specified
user, but only if the message has not yet been locked by another user.
IMPLEMENTATION NOTE:
The chat data stores IDs of all locked message for each member in ':input',
so that none of the users can intercept the input of another and interfere
with it. These locks are time-limited — to protect against forgetful users'
inactivity.
Moreover, since the user-specific input data is auto-erased when the user
leaves/is removed from the chat, these message locks will also be released
automatically, and immediately."
[chat-id user-id msg-id]
(let [updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [all-locked (->> (vals (:input chat-data))
(map :locked-messages)
(reduce #(set/union %1 %2) #{}))
user-locked (get-user-input-data chat-data user-id :locked-messages)]
(if (or (not (contains? all-locked msg-id))
(contains? user-locked msg-id))
(update-in chat-data [:input user-id :locked-messages] set/union #{msg-id})
chat-data))))
user-locked (get-user-input-data updated-chat-data user-id :locked-messages)
has-message-lock? (contains? user-locked msg-id)]
(when has-message-lock?
(go
(<! (timeout (* 5 60 1000))) ;; after 5 minutes
(release-message-lock! chat-id user-id msg-id)))
has-message-lock?))
;; - CHATS > PRIVATE CHAT
(defn- can-write-to-user?
[user-id]
(let [chat-state (-> user-id get-chat-data get-chat-state)]
(and (some? chat-state)
(not= default-chat-state chat-state))))
(defn- get-private-chat-groups
[chat-data]
(get chat-data :groups))
;; NB: This is a design decision to only accumulate groups and not delete them.
(defn- update-private-chat-groups!
([chat-id new-group-chat-id]
(let [updated-chat-data
(update-chat-data! chat-id
update :groups conj new-group-chat-id)]
(get-private-chat-groups updated-chat-data)))
([chat-id old-group-chat-id new-group-chat-id]
(let [swap-ids-fn
(comp set (partial replace {old-group-chat-id new-group-chat-id}))
updated-chat-data (update-chat-data! chat-id
update :groups swap-ids-fn)]
(get-private-chat-groups updated-chat-data))))
(defn- ->group-ref
[group-chat-id group-chat-title]
{:id group-chat-id
:title group-chat-title})
;; - CHATS > PRIVATE CHAT > USER INPUT
(defn- get-user-input
[chat-data]
(get chat-data :user-input))
(defn- update-user-input!
[chat-id {:keys [type data] :as _operation}]
(let [append-digit
(fn [old-val]
(if (or (nil? old-val)
(empty? old-val))
(when (not= "0" data) data)
(str (or old-val "") data)))
append-ar-op
(fn [old-val]
(if (or (nil? old-val)
(empty? old-val))
old-val ;; do not allow
(let [last-char (-> old-val
str/trim
last
str)]
(if (contains? cd-ar-ops-set
last-char)
old-val ;; do not allow
(str (or old-val "")
" " data " ")))))
cancel
(fn [old-val]
(let [trimmed (str/trim old-val)]
(if (< 0 (count trimmed))
(-> trimmed
(subs 0 (dec (count trimmed)))
str/trim)
trimmed)))
clear
(constantly nil)
updated-chat-data
(update-chat-data!
chat-id
(fn [chat-data]
(let [old-val (get chat-data :user-input)
new-val ((case type
:append-digit append-digit
:append-ar-op append-ar-op
:cancel cancel
:clear clear) old-val)]
(assoc chat-data :user-input new-val))))]
(get-user-input updated-chat-data)))
;; - CHATS > SUPERGROUP CHAT
(defn- migrate-group-chat-to-supergroup!
[chat-id migrate-to-chat-id]
(let [new-chat (setup-new-supergroup-chat! migrate-to-chat-id chat-id)
chat-data (if (some? new-chat)
(:data new-chat)
(get-chat-data chat-id))
group-users (-> chat-data
(get :user-account-mapping)
keys)]
;; NB: Here we iterate only real users, and this is exactly what we need.
(doseq [user-id group-users]
(update-private-chat-groups! user-id chat-id migrate-to-chat-id))))
;; RESPONSES
(def ^:private responses
{:chat-type/group
{:introduction-msg
{:response-fn get-introduction-msg
:response-params [:chat-members-count :first-name]}
:personal-account-name-request-msg
{:response-fn get-personal-account-name-request-msg
:response-params [:existing-chat? :chat-members]}
:personal-accounts-left-msg
{:response-fn get-personal-accounts-left-msg
:response-params [:count]}
:bot-readiness-msg
{:response-fn get-bot-readiness-msg
:response-params [:bot-username]}
:settings-msg
{:response-fn get-settings-msg
:response-params [:first-time?]}
:new-account-name-request-msg
{:response-fn get-new-account-name-request-msg
:response-params [:user]}
:the-account-name-is-already-taken-msg
{:response-fn get-the-account-name-is-already-taken-msg
:response-params [:user]}
:group-members-selection-msg
{:response-fn get-group-members-selection-msg
:response-params [:user :selected :remaining]}
:new-group-members-msg
{:response-fn get-new-group-members-msg
:response-params [:acc-names]}
:account-rename-request-msg
{:response-fn get-account-rename-request-msg
:response-params [:user :acc-name]}
:new-expense-item-desc-request-msg
{:response-fn get-new-expense-item-desc-request-msg
:response-params [:user]}
:new-expense-item-code-request-msg
{:response-fn get-new-expense-item-code-request-msg
:response-params [:user]}
:the-expense-item-code-is-already-used-msg
{:response-fn get-the-expense-item-code-is-already-used-msg
:response-params [:user]}
:the-expense-item-cannot-be-deleted-msg
{:response-fn get-the-expense-item-cannot-be-deleted-msg
:response-params [:exp-it-code :exp-it-desc]}
:expense-item-redesc-request-msg
{:response-fn get-expense-item-redesc-request-msg
:response-params [:user :exp-it-desc]}
:expense-item-recode-request-msg
{:response-fn get-expense-item-recode-request-msg
:response-params [:user :exp-it-desc]}
:successful-changes-msg
{:response-fn (constantly successful-changes-msg)}
:canceled-changes-msg
{:response-fn (constantly canceled-changes-msg)}
:waiting-for-user-input-notification
{:response-fn (constantly waiting-for-user-input-notification)}
:waiting-for-other-user-notification
{:response-fn (constantly waiting-for-other-user-notification)}
:message-already-in-use-notification
{:response-fn (constantly message-already-in-use-notification)}
:no-eligible-accounts-notification
{:response-fn (constantly no-eligible-accounts-notification)}
:no-group-members-selected-notification
{:response-fn (constantly no-group-members-selected-notification)}
:no-eligible-expense-items-notification
{:response-fn (constantly no-eligible-expense-items-notification)}
; message-specific
:settings
{:accounts-mgmt-options-msg
{:response-fn get-accounts-mgmt-options-msg
:response-params [:accounts-by-type]}
:account-type-selection-msg
{:response-fn get-account-type-selection-msg
:response-params [:account-types :extra-buttons]}
:account-selection-msg
{:response-fn get-account-selection-msg
:response-params [:accounts :txt :extra-buttons]}
:expense-items-mgmt-options-msg
{:response-fn get-expense-items-mgmt-options-msg
:response-params [:expense-items]}
:expense-item-selection-msg
{:response-fn get-expense-item-selection-msg
:response-params [:expense-items :extra-buttons]}
:restored-settings-msg
{:response-fn (partial get-settings-msg false)}}}
:chat-type/private
{:private-introduction-msg
{:response-fn get-private-introduction-msg
:response-params [:first-name]}
:inline-calculator-msg
{:response-fn get-inline-calculator-msg
:response-params [:new-user-input]}
:interactive-input-success-msg
{:response-fn get-interactive-input-success-msg
:response-params [:parsed-val]}
:interactive-input-disclaimer-msg
{:response-fn (constantly interactive-input-disclaimer-msg)}
:invalid-input-msg
{:response-fn (constantly invalid-input-msg)}
:group-selection-msg
{:response-fn get-group-selection-msg
:response-params [:group-refs]}
:expense-item-selection-msg
{:response-fn get-expense-item-selection-msg
:response-params [:expense-items]}
:expense-manual-description-msg
{:response-fn get-expense-manual-description-msg
:response-params [:first-name]}
:account-selection-msg
{:response-fn get-account-selection-msg
:response-params [:accounts :txt]}
:new-expense-msg
{:response-fn get-new-expense-msg
:response-params [:expense-amount :expense-details
:payer-acc-name :debtor-acc-name]}
:added-to-new-group-msg
{:response-fn get-added-to-new-group-msg
:response-params [:chat-title]}
:removed-from-group-msg
{:response-fn get-removed-from-group-msg
:response-params [:chat-title]}
:invalid-input-notification
{:response-fn (constantly invalid-input-notification)}
:expense-added-successfully-msg
{:response-fn (constantly expense-added-successfully-msg)}
:failed-to-add-new-expense-msg
{:response-fn get-failed-to-add-new-expense-msg
:response-params [:reason]}}})
;; STATES & STATE TRANSITIONS
;; TODO: Re-write with an existing state machine (FSM) library.
(defn- to-response
[{:keys [response-fn response-params]} ?param-vals]
(when (some? response-fn)
(apply response-fn (map (or ?param-vals {}) response-params))))
(defn- handle-state-transition!
[event state-transitions change-state-fn]
(let [transition-keys (:transition event)
transition (get-in state-transitions transition-keys)
chat-type (first transition-keys)
response-keys (u-coll/collect [chat-type] (:response transition))
response-data (get-in responses response-keys)]
(change-state-fn (:to-state transition))
(to-response response-data (:param-vals event))))
; chat states
;; TODO: There is a serious issue of a chat transition happening right before the exception happens.
;; Both private chats state and group chats' message state are vulnerable to this.
;; Solution: surround all update handlers with transaction boundaries.
(def ^:private group-chat-states
{:initial #{:managed
:evicted}
:managed #{:managed
:evicted}
:evicted #{:managed}})
(def ^:private private-chat-states
{:initial #{:input}
:input {:to #{:group-selection
:expense-detailing
:interactive-input
:input}
:init-fn (fn [chat-data]
(select-keys chat-data [:groups]))}
:interactive-input #{:group-selection
:expense-detailing
:input}
:group-selection #{:expense-detailing
:input}
:expense-detailing #{:account-selection
:input}
:account-selection #{:input}})
(def ^:private chat-state-transitions
{:chat-type/group
{:mark-managed
{:to-state :managed
:response :bot-readiness-msg}
:mark-evicted
{:to-state :evicted}}
:chat-type/private
{:request-amount
{:to-state :input
:response :private-introduction-msg}
:show-calculator
{:to-state :interactive-input
:response :inline-calculator-msg}
:select-group
{:to-state :group-selection
:response :group-selection-msg}
:select-expense-item
{:to-state :expense-detailing
:response :expense-item-selection-msg}
:request-expense-desc
{:to-state :expense-detailing
:response :expense-manual-description-msg}
:select-account
{:to-state :account-selection
:response :account-selection-msg}
:cancel-input
{:to-state :input}
:notify-input-success
{:to-state :input
:response :expense-added-successfully-msg}
:notify-input-failure
{:to-state :input
:response :failed-to-add-new-expense-msg}}})
(defn- handle-chat-state-transition!
[chat-id event]
(let [chat-type (first (:transition event))
chat-type-states (case chat-type
:chat-type/group group-chat-states
:chat-type/private private-chat-states)
change-state-fn (partial change-chat-state! chat-id chat-type-states)]
(handle-state-transition! event chat-state-transitions change-state-fn)))
; message states
(def ^:private group-msg-states
{:settings
{:initial #{:accounts-mgmt
:expense-items-mgmt
:shares-mgmt}
:accounts-mgmt #{:account-type-selection
:account-renaming
:account-revocation
:account-reinstatement
:initial}
:account-type-selection #{:accounts-mgmt
:initial}
:account-renaming #{:accounts-mgmt
:initial}
:account-revocation #{:accounts-mgmt
:initial}
:account-reinstatement #{:accounts-mgmt
:initial}
:expense-items-mgmt #{:expense-item-description
:expense-item-encoding
:expense-item-deletion
:initial}
:expense-item-description #{:expense-items-mgmt
:initial}
:expense-item-encoding #{:expense-items-mgmt
:initial}
:expense-item-deletion #{:expense-items-mgmt
:initial}
:shares-mgmt #{:initial}}})
(def ^:private msg-state-transitions
{:chat-type/group
{:settings
{:manage-accounts
{:to-state :accounts-mgmt
:response [:settings :accounts-mgmt-options-msg]}
:select-acc-type
{:to-state :account-type-selection
:response [:settings :account-type-selection-msg]}
:rename-account
{:to-state :account-renaming
:response [:settings :account-selection-msg]}
:revoke-account
{:to-state :account-revocation
:response [:settings :account-selection-msg]}
:reinstate-account
{:to-state :account-reinstatement
:response [:settings :account-selection-msg]}
:manage-expense-items
{:to-state :expense-items-mgmt
:response [:settings :expense-items-mgmt-options-msg]}
:redesc-expense-item
{:to-state :expense-item-description
:response [:settings :expense-item-selection-msg]}
:recode-expense-item
{:to-state :expense-item-encoding
:response [:settings :expense-item-selection-msg]}
:delete-expense-item
{:to-state :expense-item-deletion
:response [:settings :expense-item-selection-msg]}
:manage-shares
{:to-state :shares-mgmt}
:restore
{:to-state :initial
:response [:settings :restored-settings-msg]}}}})
(defn- handle-msg-state-transition!
[chat-id msg-id msg-event]
(let [chat-type (first (:transition msg-event))
all-msg-types-states (case chat-type
:chat-type/group group-msg-states)
msg-type (second (:transition msg-event))
msg-type-states (get all-msg-types-states msg-type)
change-state-fn (partial change-bot-msg-state! chat-id msg-id msg-type-states)]
(handle-state-transition! msg-event msg-state-transitions change-state-fn)))
;; RECIPROCAL ACTIONS
;; TODO: Switch to Event-Driven model. Is simpler?
;; HTTP requests should be transformed into events
;; that are handled by appropriate listeners (fns)
;; that, in turn, may result in emitting events.
;; - ABSTRACT ACTIONS
(defmulti ^:private send!
(fn [_token _ids response _opts] (:type response)))
(defmethod send! :text
[token {:keys [chat-PI:KEY:<KEY>END_PI msg-id] :as _ids}
{:keys [text options] :as _response} {:keys [replace?] :as _opts}]
(if (is-bot-evicted-from-chat? chat-id)
(log/debug "Dropped sending a message to an evicted chat=" chat-id)
;; NB: Looks for the 'replace?' among the passed options to replace
;; the existing response message rather than sending a new one.
(if-not (true? replace?)
(m-api/send-text token chat-id options text)
(m-api/edit-text token chat-id msg-id options text))))
(defmethod send! :inline
[token {:keys [inline-query-id] :as _ids}
{:keys [results options] :as _response} _opts]
(m-api/answer-inline token inline-query-id options results))
(defmethod send! :callback
[token {:keys [callback-query-id] :as _ids}
{:keys [options] :as _response} _opts]
(tg-client/answer-callback-query token callback-query-id options))
(defn- make-tg-bot-api-request!
"Makes a request to the Telegram Bot API. By default, this function awaits the feedback
(a Telegram's response) synchronously and returns a pre-defined code ':finished-sync'.
Options are key-value pairs and may be one of:
:async?
An indicator to make the whole process asynchronous (causes the fn
to return immediately with the ':launched-async' code)
:on-failure
A fn used to handle an exception in case of the request failure
:on-success
A fn used to handle the Telegram's response in case of the successful request
NB: Properly wrapped in try-catch and logged to highlight the exact HTTP client error."
[request-fn {:keys [async? on-failure on-success] :as _?options}]
(let [token (config/get-prop :bot-api-token)
handle-tg-bot-api-req (fn []
(try
(request-fn token)
(catch Throwable t
(if (some? on-failure)
(on-failure t)
(log/error t "Failed making a Telegram Bot API request"))
:req-failed)))
handle-tg-response-fn (fn [tg-response]
(log/debug "Telegram returned:" tg-response)
(try
;; TODO: There are 2 possible outcomes. Do we need to differentiate them somehow?
;; - successful request ('ok' equals true)
;; - unsuccessful request ('ok' equals false, error is in the 'description')
(when (and (some? on-success)
(true? (:ok tg-response)))
(on-success (:result tg-response)))
(catch Exception e
(log/error e "Failed to handle the response from Telegram"))))
handle-when-succeeded (fn [res]
(when-not (= :req-failed res)
(handle-tg-response-fn res)))]
(if (true? async?)
(letfn [(with-one-off-channel [req-fn handle-fn]
(let [resp-chan (chan)]
(go (handle-fn (<! resp-chan))
(close! resp-chan))
(go (>! resp-chan (req-fn)))))]
(with-one-off-channel handle-tg-bot-api-req handle-when-succeeded)
:launched-async)
(do
(handle-when-succeeded (handle-tg-bot-api-req))
:finished-sync))))
(defn- respond!
"Uniformly responds to the user action, whether it a message, inline or callback query,
or some event (e.g. service message or chat member status update).
This fn takes an optional parameter, which is an options map of a specific API method."
([ids response]
(respond! ids response nil))
([ids response ?options]
(make-tg-bot-api-request!
(fn [token]
(send! token ids response ?options))
(assoc ?options
;; TODO: Add the 'response' to the 'failed-responses' queue for the bot Admin
;; to be able to manually handle it later, if this feature is necessary.
:on-failure #(log/errorf % "Failed to respond to %s with %s" ids response)))))
(defn- respond!*
"A variant of the 'respond!' function that is used with the 'keys' of one of
the predefined responses, rather than with an arbitrary response value."
[ids response-keys & {:keys [param-vals] :as ?options}]
{:pre [(vector? response-keys)]}
(encore/when-let [response-data (get-in responses response-keys)
response (to-response response-data param-vals)]
(respond! ids response
(dissoc ?options :param-vals))))
;; TODO: GET RID OF MOST OF THESE !-FNS MAKING THEM PURE AND PASSING THEM DATA!
(defn- proceed-with-chat-and-respond!
"Continues the course of transitions between the states of the chat and sends
a message (answers an inline/callback query) in response to a user/an event."
[{:keys [chat-id] :as ids} event & {:as ?options}]
{:pre [(some? chat-id)]}
(when-let [response (handle-chat-state-transition! chat-id event)]
(respond! ids response ?options)))
(defn- proceed-with-msg-and-respond!
"Continues the course of transitions between the states of the extant message
in some chat and replaces its content in response to a user/an event."
[{:keys [chat-id msg-id] :as ids} msg-event & {:as ?options}]
{:pre [(some? chat-id) (some? msg-id)]}
(when-let [response (handle-msg-state-transition! chat-id msg-id msg-event)]
(respond! ids response
(assoc ?options :replace? true))))
(defn- delete-text!
[token {:keys [PI:KEY:<KEY>END_PI msg-id] :as _ids}]
(if (is-bot-evicted-from-chat? chat-id)
(log/debug "Dropped deleting the bot's response from an evicted chat=" chat-id)
(m-api/delete-text token chat-id msg-id)))
(defn- delete-response!
"Deletes one of the bot's previous response messages.
NB: - A message can only be deleted if it was sent less than 48 hours ago.
- Bots can delete outgoing messages in private chats, groups, and supergroups.
This fn takes an optional parameter, which is an options map of a specific API method."
([ids]
(delete-response! ids nil))
([ids ?options]
(make-tg-bot-api-request!
(fn [token]
(delete-text! token ids))
(assoc ?options
:on-failure #(log/errorf % "Failed to delete the response message %s" ids)))))
;; - SPECIFIC ACTIONS
(defn- send-retry-command!
[{{chat-id :id} :chat :as message}]
(let [commands-to-retry (tg-client/get-commands {:message message})]
(respond! {:chat-id chat-id}
(get-retry-commands-msg commands-to-retry))))
(defn- send-retry-message!
[{{chat-id :id} :chat :as _message}]
(respond! {:chat-id chat-id}
retry-resend-message-msg))
(defn- send-retry-callback-query!
[{callback-query-id :id :as _callback-query}]
(respond! {:callback-query-id callback-query-id}
retry-callback-query-notification))
(defn- notify-of-inconsistent-chat-state!
[{{chat-id :id} :chat :as _chat-member-updated-or-message}]
(log/errorf "Chat=%s has entered an inconsistent state" chat-id)
'(notify-bot-admin)) ;; TODO: Implement Admin notifications feature.
; private chats
(defn- report-to-user!
[user-id response-keys param-vals]
(when (can-write-to-user? user-id)
(respond!* {:chat-id user-id} response-keys :param-vals param-vals)))
(defn- proceed-with-adding-new-expense!
[chat-id debtor-acc]
(let [chat-data (get-chat-data chat-id)
group-chat-id (:group chat-data)
group-chat-data (get-chat-data group-chat-id)
payer-acc-id (get-personal-account-id
group-chat-data {:user-id chat-id})
debtor-acc-id (:id debtor-acc)
expense-amount (:amount chat-data)
expense-details (or (:expense-item chat-data)
(:expense-desc chat-data))
new-transaction {:chat-id group-chat-id
:payer-acc-id payer-acc-id
:debtor-acc-id debtor-acc-id
:expense-amount expense-amount
:expense-details expense-details}]
(slingshot/try+
(add-transaction! (tlogs/create! new-transaction))
(catch Exception e
;; TODO: Retry to log the failed transaction?
(log/error e "Failed to log transaction:" new-transaction)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason data-persistence-error}}))
(else
(let [pers-accs-count (->> {:acc-types [:acc-type/personal]}
(get-group-chat-accounts chat-id)
count)
payer-acc-name (when-not (or (= pers-accs-count 1)
(= payer-acc-id debtor-acc-id))
(:name (get-group-chat-account
group-chat-data {:type :acc-type/personal
:id payer-acc-id})))
debtor-acc-name (when-not (= pers-accs-count 1)
(:name debtor-acc))]
(respond!* {:chat-id group-chat-id}
[:chat-type/private :new-expense-msg]
:param-vals {:expense-amount expense-amount
:expense-details expense-details
:payer-acc-name payer-acc-name
:debtor-acc-name debtor-acc-name}))
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-success]})))))
;; TODO: Abstract this away — "selecting 1 of N, with a special case for N=1".
(defn- proceed-with-account!
[chat-id]
(let [group-chat-id (:group (get-chat-data chat-id))
active-accounts (get-group-chat-accounts group-chat-id)]
(cond
(< 1 (count active-accounts))
(let [other-accounts (filter #(not= (:user-id %) chat-id) active-accounts)]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :select-account]
:param-vals {:accounts other-accounts
:txt select-payer-account-txt}}))
(empty? active-accounts)
(do
(log/error "No eligible accounts to select a debtor account from")
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason no-debtor-account-error}}))
:else
(let [debtor-acc (first active-accounts)]
(log/debug "Debtor account auto-selected:" debtor-acc)
(proceed-with-adding-new-expense! chat-id debtor-acc)))))
(defn- proceed-with-expense-details!
[chat-id group-chat-id first-name]
(let [group-chat-data (get-chat-data group-chat-id)
expense-items (get-group-chat-expense-items group-chat-data)
event (if (seq expense-items)
{:transition [:chat-type/private :select-expense-item]
:param-vals {:expense-items expense-items}}
{:transition [:chat-type/private :request-expense-desc]
:param-vals {:first-name first-name}})]
(proceed-with-chat-and-respond! {:chat-id chat-id} event)))
;; TODO: Abstract this away — "selecting 1 of N, with a special case for N=1".
(defn- proceed-with-group!
[chat-id first-name]
(let [is-eligible? (fn [group-chat-id]
(is-group-chat-eligible-for-selection? group-chat-id chat-id))
groups (->> (get-chat-data chat-id)
get-private-chat-groups
(filter is-eligible?))]
(cond
(< 1 (count groups))
(let [group-refs (->> groups
(map #(vector % (-> % get-chat-data get-chat-title)))
(map #(apply ->group-ref %)))]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :select-group]
:param-vals {:group-refs group-refs}}))
(empty? groups)
(do
(log/error "No eligible groups to record expenses to")
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :notify-input-failure]
:param-vals {:reason no-group-to-record-error}}))
:else
(let [group-chat-id (first groups)]
(log/debug "Group chat auto-selected:" group-chat-id)
(assoc-in-chat-data! chat-id [:group] group-chat-id)
(proceed-with-expense-details! chat-id group-chat-id first-name)))))
;; TODO: Abstract away the "selecting N of {M; optional ALL}, M>=N>0" scenario.
(defn- clean-up-interactive-input-data!
[chat-id]
(let [dropped-msgs (concat (drop-bot-msg! chat-id {:type :inline-calculator})
(drop-bot-msg! chat-id {:type :cancel-disclaimer}))]
(doseq [msg-id dropped-msgs]
(delete-response! {:chat-id chat-id :msg-id msg-id}))))
; group chats
; - chat & msgs state
(defn- proceed-with-bot-eviction!
[chat-id]
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/group :mark-evicted]}))
(defn- proceed-with-restoring-group-chat-intro!
[chat-id user-id msg-id]
(release-message-lock! chat-id user-id msg-id)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :restore]}))
; - personal accounts
(defn- proceed-with-personal-accounts-name-request!
[chat-id existing-chat? ?new-chat-members]
(respond!* {:chat-id chat-id}
[:chat-type/group :personal-account-name-request-msg]
:param-vals {:existing-chat? existing-chat?
:chat-members ?new-chat-members}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :name-request})))
(defn- proceed-with-group-chat-finalization!
[chat-id show-settings?]
;; NB: Tries to create a new version of the "general account"
;; even if the group chat already existed before.
(create-general-account! chat-id (get-datetime-in-tg-format))
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/group :mark-managed]
:param-vals {:bot-username (get-bot-username)}})
(when show-settings?
(respond!* {:chat-id chat-id}
[:chat-type/group :settings-msg]
:param-vals {:first-time? true}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :settings
:state :initial}))))
(defn- check-personal-accounts-and-proceed!
([chat-id]
(let [existing-chat? (does-bot-manage-the-chat? {:chat-id chat-id})]
(check-personal-accounts-and-proceed! chat-id existing-chat?)))
([chat-id existing-chat?]
;; NB: We need to update the list of chat personal accounts with new ones
;; for those users:
;; - who were members of the previously non-existent group chat at the
;; time the bot was added there (or were added along with the bot),
;; - who have joined the existing group chat during the absence of the
;; previously evicted bot, if there are any. (Users with an existing
;; active personal account should be ignored in this case.)
(let [pers-accs-missing (get-number-of-missing-personal-accounts chat-id)]
(if (> pers-accs-missing 0)
(if (and (seq (find-bot-messages (get-chat-data chat-id) {:type :name-request}))
(not (is-bot-evicted-from-chat? chat-id))) ;; just in case, to not stuck
(respond!* {:chat-id chat-id}
[:chat-type/group :personal-accounts-left-msg]
:param-vals {:count pers-accs-missing})
(proceed-with-personal-accounts-name-request! chat-id existing-chat? nil))
(do
(drop-bot-msg! chat-id {:type :name-request})
(proceed-with-group-chat-finalization! chat-id (not existing-chat?)))))))
(defn- proceed-with-new-chat-members!
[chat-id new-chat-members]
(update-members-count! chat-id (partial + (count new-chat-members)))
(proceed-with-personal-accounts-name-request! chat-id true new-chat-members))
(defn- proceed-with-left-chat-member!
[chat-id left-chat-member]
(update-members-count! chat-id dec)
;; NB: It is necessary to trigger the personal accounts check, just in case we
;; are in the middle of the accounts creation process. If so, it will help
;; us to avoid stale ':name-request' message in chat data and, what's even
;; more important, will run the group chat finalization routine.
(check-personal-accounts-and-proceed! chat-id)
(encore/when-let [chat-data (get-chat-data chat-id)
user-id (:id left-chat-member)
pers-acc (get-personal-account chat-data {:user-id user-id})
datetime (get-datetime-in-tg-format)]
(change-account-activity-status! chat-id pers-acc
{:revoke? true :datetime datetime})
(drop-user-input-data! chat-id user-id)
(report-to-user! user-id
[:chat-type/private :removed-from-group-msg]
{:chat-title (get-chat-title chat-data)})))
; - accounts mgmt
(defn- proceed-with-accounts-mgmt!
[chat-id msg-id]
(let [accounts-by-type (get-group-chat-accounts-by-type chat-id)]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-accounts]
:param-vals {:accounts-by-type accounts-by-type}})))
(defn- proceed-with-account-type-selection!
[chat-id msg-id]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :select-acc-type]
:param-vals {:account-types [:acc-type/group :acc-type/personal]
:extra-buttons [back-button]}}))
(defn- proceed-with-account-naming!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-account-name-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-acc-name})))
(defn- proceed-with-the-account-name-is-already-taken!
[chat-id {user-id :id :as user} bot-msg-type]
(respond!* {:chat-id chat-id}
[:chat-type/group :the-account-name-is-already-taken-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type bot-msg-type})))
(defn- proceed-with-next-account-creation-steps!
[chat-id acc-type {user-id :id :as user}]
(let [input-data {:acc-type acc-type}]
(set-user-input-data! chat-id user-id :create-account input-data))
(case acc-type
:acc-type/personal
(proceed-with-account-naming! chat-id user)
:acc-type/group
(let [personal-accs (get-group-chat-accounts chat-id
{:acc-types [:acc-type/personal]})]
(respond!* {:chat-id chat-id}
[:chat-type/group :group-members-selection-msg]
:param-vals {:user user
:selected nil
:remaining personal-accs}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :group-members-selection})))))
(defn- proceed-with-account-member-selection!
[chat-id msg-id user already-selected-account-members]
(let [personal-accs (set (get-group-chat-accounts chat-id
{:acc-types [:acc-type/personal]}))
selected-accs (set already-selected-account-members)
remaining-accs (set/difference personal-accs selected-accs)
accounts-remain? (seq remaining-accs)]
(when accounts-remain?
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/group :group-members-selection-msg]
:param-vals {:user user
:selected selected-accs
:remaining remaining-accs}
:replace? true))
accounts-remain?))
(defn- proceed-with-end-of-account-members-selection!
[chat-id msg-id {user-id :id :as user} members]
(drop-bot-msg! chat-id {:to-user user-id
:type :group-members-selection})
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/group :new-group-members-msg]
:param-vals {:acc-names (map :name members)}
:replace? true)
(proceed-with-account-naming! chat-id user))
(defn- proceed-with-next-group-account-creation-steps!
[chat-id msg-id {user-id :id :as user}]
(let [members (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(get :members))
can-proceed? (proceed-with-account-member-selection! chat-id msg-id user members)]
(when-not can-proceed?
(proceed-with-end-of-account-members-selection! chat-id msg-id user members))))
(defn- proceed-with-account-selection!
([chat-id msg-id callback-query-id
state-transition-name]
(proceed-with-account-selection! chat-id msg-id callback-query-id
state-transition-name nil))
([chat-id msg-id callback-query-id
state-transition-name ?filter-pred]
(let [eligible-accs (get-group-chat-accounts chat-id
{:acc-types [:acc-type/group
:acc-type/personal]
:filter-pred ?filter-pred})]
(if (seq eligible-accs)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings state-transition-name]
:param-vals {:accounts eligible-accs
:txt select-account-txt
:extra-buttons [back-button]}})
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-eligible-accounts-notification])))))
(defn- proceed-with-account-renaming!
[chat-id {user-id :id :as user} acc-to-rename]
(let [input-data {:acc-type (:type acc-to-rename)
:acc-id (:id acc-to-rename)}]
(set-user-input-data! chat-id user-id :rename-account input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :account-rename-request-msg]
:param-vals {:user user
:acc-name (:name acc-to-rename)}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-acc-rename})))
(defn- proceed-with-personal-account-creation!
[chat-id chat-title
acc-name created-dt {user-id :id :as user} first-msg-id]
(let [create-acc-res (create-personal-account! chat-id acc-name created-dt
:user-id user-id :first-msg-id first-msg-id)]
(if (is-failure? create-acc-res)
(case create-acc-res
:failure/user-already-has-an-active-account
(respond!* {:chat-id chat-id} [:chat-type/group :canceled-changes-msg])
:failure/the-account-name-is-already-taken
(proceed-with-the-account-name-is-already-taken! chat-id user :name-request))
(report-to-user! user-id
[:chat-type/private :added-to-new-group-msg]
{:chat-title chat-title}))))
(defn- proceed-with-account-operation!
[chat-id {user-id :id :as user}
bot-msg-type input-name acc-op-fn]
(let [chat-data (get-chat-data chat-id)
input-data (get-user-input-data chat-data user-id input-name)
acc-op-res (acc-op-fn chat-id input-data)]
(if (is-failure? acc-op-res)
(case acc-op-res
:failure/the-account-name-is-already-taken
(proceed-with-the-account-name-is-already-taken! chat-id user bot-msg-type)
(throw (ex-info "Unexpected operation result" {:result acc-op-res})))
(do
(clean-up-chat-data! chat-id {:bot-messages [{:to-user user-id
:type bot-msg-type}]
:input [{:user user-id
:name input-name}]})
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg])))))
; - expense items mgmt
(defn- proceed-with-expense-items-mgmt!
[chat-id msg-id]
(let [chat-data (get-chat-data chat-id)
expense-items (get-group-chat-expense-items chat-data)]
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-expense-items]
:param-vals {:expense-items expense-items}})))
(defn- proceed-with-expense-item-description!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-expense-item-desc-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-desc})))
(defn- proceed-with-expense-item-encoding!
[chat-id {user-id :id :as user}]
(respond!* {:chat-id chat-id}
[:chat-type/group :new-expense-item-code-request-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-code})))
(defn- proceed-with-the-expense-item-code-is-already-used!
[chat-id {user-id :id :as user} bot-msg-type]
(respond!* {:chat-id chat-id}
[:chat-type/group :the-expense-item-code-is-already-used-msg]
:param-vals {:user user}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type bot-msg-type})))
(defn- proceed-with-expense-item-creation-steps!
[chat-id user]
;; TODO: Re-implement as a "logical action flow": name + desc.
(proceed-with-expense-item-description! chat-id user))
(defn- proceed-with-expense-item-operation!
[chat-id {user-id :id :as user}
bot-msg-type input-name exp-it-op-fn]
(let [chat-data (get-chat-data chat-id)
input-data (get-user-input-data chat-data user-id input-name)
exp-it-op-res (exp-it-op-fn chat-id input-data)]
(if (is-failure? exp-it-op-res)
(case exp-it-op-res
:failure/the-expense-item-code-is-already-used
(proceed-with-the-expense-item-code-is-already-used! chat-id user bot-msg-type)
(throw (ex-info "Unexpected operation result" {:result exp-it-op-res})))
(do
(clean-up-chat-data! chat-id {:bot-messages [{:to-user user-id
:type bot-msg-type}]
:input [{:user user-id
:name input-name}]})
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg])))))
(defn- proceed-with-expense-item-selection!
([chat-id msg-id callback-query-id
state-transition-name]
(proceed-with-expense-item-selection! chat-id msg-id callback-query-id
state-transition-name nil))
([chat-id msg-id callback-query-id
state-transition-name ?filter-pred]
(let [chat-data (get-chat-data chat-id)
eligible-expense-items (cond->> (get-group-chat-expense-items chat-data)
(some? ?filter-pred) (filter ?filter-pred))]
(if (seq eligible-expense-items)
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings state-transition-name]
:param-vals {:expense-items eligible-expense-items
:extra-buttons [back-button]}})
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-eligible-expense-items-notification])))))
(defn- proceed-with-expense-item-re-description!
[chat-id {user-id :id :as user} exp-it-to-redesc]
(let [input-data {:exp-it-code (first exp-it-to-redesc)}]
(set-user-input-data! chat-id user-id :redesc-expense-item input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :expense-item-redesc-request-msg]
:param-vals {:user user
:exp-it-desc (:desc (second exp-it-to-redesc))}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-redesc})))
(defn- proceed-with-expense-item-re-encoding!
[chat-id {user-id :id :as user} exp-it-to-recode]
(let [input-data {:exp-it-code (first exp-it-to-recode)}]
(set-user-input-data! chat-id user-id :recode-expense-item input-data))
(respond!* {:chat-id chat-id}
[:chat-type/group :expense-item-recode-request-msg]
:param-vals {:user user
:exp-it-desc (:desc (second exp-it-to-recode))}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:to-user user-id
:type :request-exp-it-recode})))
(defn- proceed-with-expense-item-deletion!
[chat-id exp-it-to-delete]
(let [delete-exp-it-res (delete-group-chat-expense-item! chat-id exp-it-to-delete)]
(if (is-failure? delete-exp-it-res)
(case delete-exp-it-res
:failure/the-expense-item-cannot-be-deleted
(respond!* {:chat-id chat-id}
[:chat-type/group :the-expense-item-cannot-be-deleted-msg]
:param-vals {:exp-it-code (first exp-it-to-delete)
:exp-it-desc (:desc (second exp-it-to-delete))})
(throw (ex-info "Unexpected operation result" {:result delete-exp-it-res})))
(respond!* {:chat-id chat-id}
[:chat-type/group :successful-changes-msg]))))
;; TODO: Linearize calls to these macros with a wrapper macro & a map.
(defmacro do-when-chat-is-ready-or-send-notification!
[chat-state callback-query-id & body]
`(if (does-bot-manage-the-chat? {:chat-state ~chat-state})
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :waiting-for-user-input-notification])))
(defmacro do-with-expected-user-or-send-notification!
[chat-id user-id msg-id callback-query-id & body]
`(if (check-bot-msg (get-bot-msg (get-chat-data ~chat-id) ~msg-id)
{:to-user ~user-id})
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :waiting-for-other-user-notification])))
(defmacro try-with-message-lock-or-send-notification!
[chat-id user-id msg-id callback-query-id & body]
`(if (acquire-message-lock! ~chat-id ~user-id ~msg-id)
(do ~@body)
(respond!* {:callback-query-id ~callback-query-id}
[:chat-type/group :message-already-in-use-notification])))
;; - COMMANDS ACTIONS
; private chats
(defn- cmd-private-start!
[{chat-id :id :as chat}
{first-name :first_name :as _user}]
(log/debug "Conversation started in a private chat:" chat)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :request-amount]
:param-vals {:first-name first-name}}))
;; TODO: Implement proper '/help' message (w/ the list of commands, etc.).
(defn- cmd-private-help!
[{chat-id :id :as chat}]
(log/debug "Help requested in a private chat:" chat)
(respond! {:chat-id chat-id}
{:type :text
:text "Help is on the way!"}))
(defn- cmd-private-calc!
[{chat-id :id :as chat}]
(when (= :input (-> chat-id get-chat-data get-chat-state))
(log/debug "Calculator opened in a private chat:" chat)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :show-calculator]}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :inline-calculator}))
(respond!* {:chat-id chat-id}
[:chat-type/private :interactive-input-disclaimer-msg]
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :cancel-disclaimer}))))
(defn- cmd-private-cancel!
[{chat-id :id :as chat}]
(log/debug "The operation is canceled in a private chat:" chat)
;; clean-up the messages
(case (get-chat-state (get-chat-data chat-id))
:interactive-input
(clean-up-interactive-input-data! chat-id)
nil)
(proceed-with-chat-and-respond!
{:chat-id chat-id}
{:transition [:chat-type/private :cancel-input]}))
; group chats
;; TODO: Implement proper '/help' message (w/ the list of commands, etc.).
(defn- cmd-group-help!
[{chat-id :id :as chat}]
(log/debug "Help requested in a group chat:" chat)
(respond! {:chat-id chat-id}
{:type :text
:text "Help is on the way!"}))
(defn- cmd-group-settings!
[{chat-id :id :as chat}]
(log/debug "Settings requested in a group chat:" chat)
(respond!* {:chat-id chat-id}
[:chat-type/group :settings-msg]
:param-vals {:first-time? false}
:on-success #(set-bot-msg! chat-id (:message_id %)
{:type :settings
:state :initial})))
;; API RESPONSES
;; IMPORTANT: The main idea of this API is to organize handlers of any type (message, command, any
;; query, etc.) into a chain (in the order of their declaration within the 'defhandler'
;; body) that will process updates in the following way:
;; - the first handler of the type have to log an incoming update (its payload object);
;; - any intermediate handler have to either:
;; - result in an "operation [result] code" ('succeed', 'failed') OR in an "immediate
;; response" (only for Webhook updates) — which will stop the further processing;
;; - result in 'nil' — which will pass the update for processing to the next handler;
;; - the last handler, in case the update wasn't processed, have to "ignore" it — which
;; is also interpreted as the whole operation had 'succeed'.
;; NB: Any non-nil will do.
(def op-succeed {:ok true})
(def op-failed {:ok false})
(defmacro ^:private ignore
[msg & args]
`(do
(log/debugf (str "Ignored: " ~msg) ~@args)
op-succeed))
(defn- cb-succeed
[callback-query-id]
(tg-api/build-immediate-response "answerCallbackQuery"
{:callback_query_id callback-query-id}))
(defn- cb-ignored
[callback-query-id]
;; TODO: For a long-polling version, respond as usual.
(tg-api/build-immediate-response "answerCallbackQuery"
(assoc ignored-callback-query-notification
:callback_query_id callback-query-id)))
;; TODO: This have to be combined with an Event-Driven model,
;; i.e. in case of long-term request processing the bot
;; should immediately respond with sending the 'typing'
;; chat action (use "sendChatAction" method and see the
;; /sendChatAction specs for the request parameters).
;; BOT API
;; TODO: The design should be similar to the Lupapiste web handlers with their 'in-/outjects'.
;; TODO: Add a rate limiter. Use the 'limiter' from Encore? Or some full-featured RPC library?
;; This is to overcome the recent error — HTTP 429 — "Too many requests, retry after X".
; The Bots FAQ on the official Telegram website lists the following limits on server requests:
; - No more than 1 message per second in a single chat,
; - No more than 20 messages per minute in one group,
; - No more than 30 messages per second in total.
(defmacro handle-with-care!
[bindings & handler-body-and-care-fn]
(let [body (butlast handler-body-and-care-fn)
care-fn (last handler-body-and-care-fn)]
`(fn [arg#]
(try
((fn ~bindings ~@body) arg#)
(catch Exception e#
(log/error e# "Failed to handle an incoming update:" arg#)
(when-some [ex-data# (ex-data e#)]
(log/error "The associated exception data:" ex-data#))
(~care-fn arg#)
op-failed)))))
(tg-client/defhandler
handler
;; NB: This function is applied to the arguments of all handlers that follow
;; and merges its result with the original value of the argument.
(fn [upd upd-type]
(let [chat (case upd-type
(:message :my_chat_member) (-> upd upd-type :chat)
(:callback_query) (-> upd upd-type :message :chat)
nil)
msg (case upd-type
:message (:message upd)
:callback_query (-> upd :callback_query :message)
nil)
chat-data (get-chat-data (or (:id chat)
(:id (:chat msg))))]
(cond-> nil
(some? chat)
(merge {:chat-type (cond
(tg-api/is-private? chat) :chat-type/private
(tg-api/is-group? chat) :chat-type/group)
:chat-state (get-chat-state chat-data)})
(some? msg)
(merge (when-some [bot-msg (get-bot-msg chat-data (:message_id msg))]
{:bot-msg bot-msg})))))
;; - BOT COMMANDS
; group chats
(tg-client/command-fn
"help"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/group (:chat-type message))
(cmd-group-help! chat)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"settings"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/group (:chat-type message))
(cmd-group-settings! chat)
op-succeed)
send-retry-command!))
; private chats
(tg-client/command-fn
"start"
(handle-with-care!
[{user :from chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-start! chat user)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"help"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-help! chat)
op-succeed)
send-retry-command!))
(tg-client/command-fn
"calc"
(handle-with-care!
[{chat :chat :as message}]
(when (and (= :chat-type/private (:chat-type message))
(cmd-private-calc! chat))
op-succeed)
send-retry-command!))
(tg-client/command-fn
"cancel"
(handle-with-care!
[{chat :chat :as message}]
(when (= :chat-type/private (:chat-type message))
(cmd-private-cancel! chat)
op-succeed)
send-retry-command!))
;; - INLINE QUERIES
(m-hlr/inline-fn
(fn [inline-query]
(log/debug "Inline query:" inline-query)))
;; TODO: Try to implement an inline query answered w/ 'switch_pm_text' parameter?
(m-hlr/inline-fn
(fn [{inline-query-id :id _user :from query-str :query _offset :offset
:as _inline-query}]
(ignore "inline query id=%s, query=%s" inline-query-id query-str)))
;; - CALLBACK QUERIES
(m-hlr/callback-fn
(fn [callback-query]
(log/debug "Callback query:" callback-query)))
; group chats
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-accounts callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-accounts-mgmt! chat-id msg-id)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :accounts-mgmt (-> callback-query :bot-msg :state)))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(when-let [respond! (condp = callback-btn-data
cd-accounts-create #(proceed-with-account-type-selection!
chat-id msg-id)
cd-accounts-rename #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:rename-account
(can-rename-account? chat-id user-id))
cd-accounts-revoke #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:revoke-account
(can-revoke-account? chat-id user-id))
cd-accounts-reinstate #(proceed-with-account-selection!
chat-id msg-id callback-query-id
:reinstate-account
(can-reinstate-account? chat-id user-id))
nil)]
(respond!)
(cb-succeed callback-query-id)))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-type-selection (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-type-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [acc-type-name (str/replace-first callback-btn-data
cd-account-type-prefix "")
acc-type (keyword "acc-type" acc-type-name)]
(proceed-with-next-account-creation-steps! chat-id acc-type user))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
picked-acc (data->account callback-btn-data chat-data)
input-data (-> chat-data
(get-user-input-data user-id :create-account)
(update :members #(u-coll/add-or-remove picked-acc %)))]
(set-user-input-data! chat-id user-id :create-account input-data))
(proceed-with-next-group-account-creation-steps! chat-id msg-id user)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(= cd-undo callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(drop-bot-msg! chat-id {:to-user user-id
:type :group-members-selection})
(set-user-input-data! chat-id user-id :create-account nil)
(delete-response! {:chat-id chat-id :msg-id msg-id})
(respond!* {:chat-id chat-id}
[:chat-type/group :canceled-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :group-members-selection (-> callback-query :bot-msg :type))
(= cd-done callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(do-with-expected-user-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [members (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(get :members))]
(if (seq members)
(do
(proceed-with-end-of-account-members-selection! chat-id msg-id user members)
(cb-succeed callback-query-id))
(respond!* {:callback-query-id callback-query-id}
[:chat-type/group :no-group-members-selected-notification]))))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-renaming (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
account-to-rename (data->account callback-btn-data chat-data)]
(proceed-with-account-renaming! chat-id user account-to-rename))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-revocation (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
account-to-revoke (data->account callback-btn-data chat-data)
datetime (get-datetime-in-tg-format)]
;; NB: It makes sense to ask the user if the revoked account owner
;; should be excluded from the chat, but this is possible only
;; for bots with 'admin' rights.
(change-account-activity-status! chat-id account-to-revoke
{:revoke? true :datetime datetime}))
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(respond!* {:chat-id chat-id} [:chat-type/group :successful-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :account-reinstatement (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-account-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(let [chat-data (get-chat-data chat-id)
account-to-reinstate (data->account callback-btn-data chat-data)
datetime (get-datetime-in-tg-format)]
(change-account-activity-status! chat-id account-to-reinstate
{:reinstate? true :datetime datetime}))
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(respond!* {:chat-id chat-id} [:chat-type/group :successful-changes-msg])))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-expense-items callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-expense-items-mgmt! chat-id msg-id)))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-items-mgmt (-> callback-query :bot-msg :state)))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(when-let [respond! (condp = callback-btn-data
cd-expense-items-create #(proceed-with-expense-item-creation-steps!
chat-id user)
cd-expense-items-redesc #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:redesc-expense-item)
cd-expense-items-recode #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:recode-expense-item)
cd-expense-items-delete #(proceed-with-expense-item-selection!
chat-id msg-id callback-query-id
:delete-expense-item
can-expense-item-be-deleted?)
nil)]
(respond!)
(cb-succeed callback-query-id)))))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-description (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-re-description! chat-id user expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id :as user} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-encoding (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-re-encoding! chat-id user expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :expense-item-deletion (-> callback-query :bot-msg :state))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(let [chat-data (get-chat-data chat-id)
expense-item (data->expense-item callback-btn-data chat-data)]
(proceed-with-expense-item-deletion! chat-id expense-item))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= :initial (-> callback-query :bot-msg :state))
(= cd-shares callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(proceed-with-msg-and-respond!
{:chat-id chat-id :msg-id msg-id}
{:transition [:chat-type/group :settings :manage-shares]})))
(cb-succeed callback-query-id))
send-retry-callback-query!))
;; TODO: Implement handlers for ':shares-mgmt'.
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{user-id :id} :from
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/group (:chat-type callback-query))
(= :settings (-> callback-query :bot-msg :type))
(= cd-back callback-btn-data))
(do-when-chat-is-ready-or-send-notification!
(:chat-state callback-query) callback-query-id
(try-with-message-lock-or-send-notification!
chat-id user-id msg-id callback-query-id
(case (-> callback-query :bot-msg :state)
(:initial ;; for when something went wrong
:accounts-mgmt :expense-items-mgmt :shares-mgmt)
(proceed-with-restoring-group-chat-intro! chat-id user-id msg-id)
(:account-type-selection :account-renaming :account-revocation :account-reinstatement)
(proceed-with-accounts-mgmt! chat-id msg-id)
(:expense-item-description :expense-item-encoding :expense-item-deletion)
(proceed-with-expense-items-mgmt! chat-id msg-id))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
; private chats
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{first-name :first_name} :from
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :group-selection (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-group-chat-prefix))
(let [group-chat-id-str (str/replace-first callback-btn-data cd-group-chat-prefix "")
group-chat-id (u-nums/parse-int group-chat-id-str)]
(assoc-in-chat-data! chat-id [:group] group-chat-id)
(proceed-with-expense-details! chat-id group-chat-id first-name))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :expense-detailing (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-expense-item-prefix))
(let [expense-item (str/replace-first callback-btn-data cd-expense-item-prefix "")]
(assoc-in-chat-data! chat-id [:expense-item] expense-item)
(proceed-with-account! chat-id))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :account-selection (:chat-state callback-query))
(str/starts-with? callback-btn-data cd-account-prefix))
(let [group-chat-id (:group (get-chat-data chat-id))
group-chat-data (get-chat-data group-chat-id)
debtor-acc (data->account callback-btn-data group-chat-data)]
(proceed-with-adding-new-expense! chat-id debtor-acc))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{msg-id :message_id {chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :interactive-input (:chat-state callback-query)))
(when-let [non-terminal-operation (condp apply [callback-btn-data]
cd-digits-set {:type :append-digit
:data callback-btn-data}
cd-ar-ops-set {:type :append-ar-op
:data callback-btn-data}
(partial = cd-clear) {:type :cancel}
(partial = cd-cancel) {:type :clear}
nil)]
(let [old-user-input (get-user-input (get-chat-data chat-id))
new-user-input (update-user-input! chat-id non-terminal-operation)]
(when (not= old-user-input new-user-input)
(respond!* {:chat-id chat-id :msg-id msg-id}
[:chat-type/private :inline-calculator-msg]
:param-vals {:new-user-input new-user-input}
:replace? true)))
(cb-succeed callback-query-id)))
send-retry-callback-query!))
(m-hlr/callback-fn
(handle-with-care!
[{callback-query-id :id
{first-name :first_name} :from
{{chat-id :id} :chat} :message
callback-btn-data :data
:as callback-query}]
(when (and (= :chat-type/private (:chat-type callback-query))
(= :interactive-input (:chat-state callback-query))
(= cd-enter callback-btn-data))
(let [user-input (get-user-input (get-chat-data chat-id))
parsed-val (u-nums/parse-arithmetic-expression user-input)]
(if (and (number? parsed-val) (pos? parsed-val))
(do
(log/debug "User input:" parsed-val)
(assoc-in-chat-data! chat-id [:amount] parsed-val)
(clean-up-interactive-input-data! chat-id)
(respond!* {:chat-id chat-id}
[:chat-type/private :interactive-input-success-msg]
:param-vals {:parsed-val parsed-val})
(proceed-with-group! chat-id first-name))
(do
(log/debugf "Invalid user input: \"%s\"" parsed-val)
(respond!* {:callback-query-id callback-query-id}
[:chat-type/private :invalid-input-notification]))))
(cb-succeed callback-query-id))
send-retry-callback-query!))
(m-hlr/callback-fn
(fn [{callback-query-id :id _user :from _msg :message _msg-id :inline_message_id
_chat-instance :chat_instance callback-btn-data :data
:as _callback-query}]
(ignore "callback query id=%s, data=%s" callback-query-id callback-btn-data)
(cb-ignored callback-query-id)))
;; - CHAT MEMBER STATUS UPDATES
(tg-client/bot-chat-member-status-fn
(handle-with-care!
[{{chat-id :id _type :type chat-title :title _username :username :as chat} :chat
{_user-id :id first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
date :date
{_old-user :user _old-status :status :as _old-chat-member} :old_chat_member
{_new-user :user _new-status :status :as _new-chat-member} :new_chat_member
:as my-chat-member-updated}]
(log/debug "Bot chat member status updated in:" chat)
(cond
(tg-api/has-joined? my-chat-member-updated)
(let [token (config/get-prop :bot-api-token)
chat-members-count (tg-client/get-chat-member-count token chat-id)
new-chat (setup-new-group-chat! chat-id chat-title chat-members-count)
existing-chat? (nil? new-chat)]
(if existing-chat?
(do
(log/debugf "The chat=%s already exists" chat-id)
(update-members-count! chat-id (constantly chat-members-count)))
(respond!* {:chat-id chat-id}
[:chat-type/group :introduction-msg]
:param-vals {:chat-members-count chat-members-count
:first-name first-name}))
(check-personal-accounts-and-proceed! chat-id existing-chat?)
op-succeed)
(tg-api/has-left? my-chat-member-updated)
(do
(update-members-count! chat-id dec)
(proceed-with-bot-eviction! chat-id)
op-succeed)
:else
(ignore "bot chat member status update dated %s in chat=%s" date chat-id))
notify-of-inconsistent-chat-state!))
(tg-client/chat-member-status-fn
(fn [{{chat-id :id _type :type _chat-title :title _username :username :as chat} :chat
{_user-id :id _first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
date :date
{_old-user :user _old-status :status :as _old-chat-member} :old_chat_member
{_new-user :user _new-status :status :as _new-chat-member} :new_chat_member
:as _chat-member-updated}]
(log/debug "Chat member status updated in:" chat)
;; NB: The bot must be an administrator in the chat to receive 'chat_member' updates
;; about other chat members. By default, only 'my_chat_member' updates about the
;; bot itself are received.
(ignore "chat member status update dated %s in chat=%s" date chat-id)))
;; - PLAIN MESSAGES
; group chats
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id :as chat} :chat
new-chat-members :new_chat_members
:as _message}]
(when (some? new-chat-members)
(log/debug "New chat members in chat:" chat)
(let [new-chat-members (filter #(not (:is_bot %)) new-chat-members)]
(when (seq new-chat-members)
(proceed-with-new-chat-members! chat-id new-chat-members)
op-succeed)))
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id :as chat} :chat
left-chat-member :left_chat_member
:as _message}]
(when (some? left-chat-member)
(log/debug "Chat member left chat:" chat)
(when-not (:is_bot left-chat-member)
(proceed-with-left-chat-member! chat-id left-chat-member)
op-succeed))
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(fn [{msg-id :message_id group-chat-created :group_chat_created :as _message}]
(when (some? group-chat-created)
(ignore "message id=%s" msg-id))))
(m-hlr/message-fn
(handle-with-care!
[{msg-id :message_id date :date text :text
{user-id :id :as user} :from
{chat-id :id chat-title :title} :chat
:as message}]
;; TODO: Figure out how to proceed if someone accidentally closes the reply.
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:type :name-request}))
;; NB: Here the 'user-id' exists for sure, since it is the User's response.
(when-some [_new-chat (setup-new-private-chat! user-id chat-id)]
(update-private-chat-groups! user-id chat-id))
(proceed-with-personal-account-creation! chat-id chat-title
text date user msg-id)
(check-personal-accounts-and-proceed! chat-id)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{date :date text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-acc-name}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-account)
(assoc :acc-name text)
(assoc :created-dt date)
(assoc :created-by user-id))]
(set-user-input-data! chat-id user-id :create-account input-data))
(proceed-with-account-operation! chat-id user
:request-acc-name
:create-account
create-group-chat-account!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-acc-rename}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :rename-account)
(assoc :new-acc-name text))]
(set-user-input-data! chat-id user-id :rename-account input-data))
(proceed-with-account-operation! chat-id user
:request-acc-rename
:rename-account
change-group-chat-account-name!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-desc}))
(let [input-data {:exp-it-data {:desc text}}]
(set-user-input-data! chat-id user-id :create-expense-item input-data))
(proceed-with-expense-item-encoding! chat-id user)
(drop-bot-msg! chat-id {:to-user user-id
:type :request-exp-it-desc})
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{emoji :emoji} :sticker
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-code}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :create-expense-item)
(assoc :exp-it-code (or text emoji)))]
(set-user-input-data! chat-id user-id :create-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-code
:create-expense-item
create-group-chat-expense-item!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-redesc}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :redesc-expense-item)
(assoc-in [:exp-it-data :desc] text))]
(set-user-input-data! chat-id user-id :redesc-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-redesc
:redesc-expense-item
update-group-chat-expense-item!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text
{emoji :emoji} :sticker
{user-id :id :as user} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(check-bot-msg (get-original-bot-msg chat-id message)
{:to-user user-id
:type :request-exp-it-recode}))
(let [input-data (-> (get-chat-data chat-id)
(get-user-input-data user-id :recode-expense-item)
(assoc :new-exp-it-code (or text emoji)))]
(set-user-input-data! chat-id user-id :recode-expense-item input-data))
(proceed-with-expense-item-operation! chat-id user
:request-exp-it-recode
:recode-expense-item
change-group-chat-expense-item-code!)
op-succeed)
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id} :chat
new-chat-title :new_chat_title
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(some? new-chat-title))
(log/debugf "Chat %s title was changed to '%s'" chat-id new-chat-title)
(set-chat-title! chat-id new-chat-title)
op-succeed)
notify-of-inconsistent-chat-state!))
(m-hlr/message-fn
(handle-with-care!
[{{chat-id :id} :chat
migrate-to-chat-id :migrate_to_chat_id
:as message}]
(when (and (= :chat-type/group (:chat-type message))
(some? migrate-to-chat-id))
(log/debugf "Group %s has been migrated to a supergroup %s" chat-id migrate-to-chat-id)
(migrate-group-chat-to-supergroup! chat-id migrate-to-chat-id)
op-succeed)
notify-of-inconsistent-chat-state!))
; private chats
(m-hlr/message-fn
(handle-with-care!
[{text :text
{PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI} :from
{chat-id :id} :chat
:as message}]
(when (and (= :chat-type/private (:chat-type message))
(= :input (:chat-state message)))
(let [input (u-nums/parse-number text)]
(if (number? input)
(do
(log/debug "User input:" input)
(assoc-in-chat-data! chat-id [:amount] input)
(proceed-with-group! chat-id first-name)
op-succeed)
(respond!* {:chat-id chat-id}
[:chat-type/private :invalid-input-msg]))))
send-retry-message!))
(m-hlr/message-fn
(handle-with-care!
[{text :text {chat-id :id} :chat
:as message}]
(when (and (= :chat-type/private (:chat-type message))
(= :expense-detailing (:chat-state message)))
(log/debugf "Expense description: \"%s\"" text)
(assoc-in-chat-data! chat-id [:expense-desc] text)
(proceed-with-account! chat-id)
op-succeed)
send-retry-message!))
;; NB: A "match-all catch-through" case. Excessive list of parameters is for clarity.
(m-hlr/message-fn
(fn [{msg-id :message_id _date :date _text :text
{_user-id :id _first-name :first_name _last-name :last_name
_username :username _is-bot :is_bot _lang :language_code :as _user} :from
{_chat-id :id _type :type _chat-title :title _username :username :as chat} :chat
_sender-chat :sender_chat
_forward-from :forward_from
_forward-from-chat :forward_from_chat
_forward-from-message-id :forward_from_message_id
_forward-signature :forward_signature
_forward-sender-name :forward_sender_name
_forward-date :forward_date
_original-msg :reply_to_message ;; for replies
_via-bot :via_bot
_edit-date :edit_date
_author-signature :author_signature
_entities :entities
_new-chat-members :new_chat_members
_left-chat-member :left_chat_member
_new-chat-title :new_chat_title
_new-chat-photo :new_chat_photo
_delete-chat-photo :delete_chat_photo
_group-chat-created :group_chat_created
_supergroup-chat-created :supergroup_chat_created
_channel-chat-created :channel_chat_created
_message-auto-delete-timer-changed :message_auto_delete_timer_changed
_migrate-to-chat-id :migrate_to_chat_id
_migrate-from-chat-id :migrate_from_chat_id
_pinned-message :pinned_message
_reply-markup :reply_markup
:as _message}]
(log/debug "Unprocessed message in chat:" chat)
(ignore "message id=%s" msg-id))))
(defn bot-api
[update]
(log/debug "Received update:" update)
(handler update))
|
[
{
"context": "your new password below\"]\n [:input {:type \"password\"\n :required true\n ",
"end": 835,
"score": 0.7630965113639832,
"start": 827,
"tag": "PASSWORD",
"value": "password"
}
] |
src/cljs/shotbot/re_frame/reset_password/views.cljs
|
skygear-demo/shotbot3
| 2 |
(ns shotbot.re-frame.reset-password.views
(:require [re-frame.core :refer [dispatch subscribe]]
))
(defn panel []
(let [message (subscribe [:reset-password/message])]
(fn panel-reaction []
[:div.reset-password-panel
[:div.reset-password-header
[:span]
[:div.logo
[:img {:src "img/icon-shotbot.svg"}]
[:span "Shotbot"]]
[:div.login {:on-click (fn [_]
(dispatch [:reset-password/login]))}
[:img {:src "img/icon-login.svg"}]
[:span "Login"]]]
[:form {:on-submit (fn [evt]
(.preventDefault evt)
(dispatch [:reset-password/reset-password]))}
[:h1 "RESET PASSWORD"]
[:p "Enter your new password below"]
[:input {:type "password"
:required true
:placeholder "New Password"
:on-change (fn [evt]
(dispatch [:reset-password/set-new-password
evt.target.value]))}]
[:input {:type "password"
:required true
:placeholder "Confirm Password"
:on-change (fn [evt]
(dispatch [:reset-password/set-confirm-password
evt.target.value]))}]
[:span.message @message]
[:input {:type "submit"
:value "Reset"}]
]
[:div]])))
|
28217
|
(ns shotbot.re-frame.reset-password.views
(:require [re-frame.core :refer [dispatch subscribe]]
))
(defn panel []
(let [message (subscribe [:reset-password/message])]
(fn panel-reaction []
[:div.reset-password-panel
[:div.reset-password-header
[:span]
[:div.logo
[:img {:src "img/icon-shotbot.svg"}]
[:span "Shotbot"]]
[:div.login {:on-click (fn [_]
(dispatch [:reset-password/login]))}
[:img {:src "img/icon-login.svg"}]
[:span "Login"]]]
[:form {:on-submit (fn [evt]
(.preventDefault evt)
(dispatch [:reset-password/reset-password]))}
[:h1 "RESET PASSWORD"]
[:p "Enter your new password below"]
[:input {:type "<PASSWORD>"
:required true
:placeholder "New Password"
:on-change (fn [evt]
(dispatch [:reset-password/set-new-password
evt.target.value]))}]
[:input {:type "password"
:required true
:placeholder "Confirm Password"
:on-change (fn [evt]
(dispatch [:reset-password/set-confirm-password
evt.target.value]))}]
[:span.message @message]
[:input {:type "submit"
:value "Reset"}]
]
[:div]])))
| true |
(ns shotbot.re-frame.reset-password.views
(:require [re-frame.core :refer [dispatch subscribe]]
))
(defn panel []
(let [message (subscribe [:reset-password/message])]
(fn panel-reaction []
[:div.reset-password-panel
[:div.reset-password-header
[:span]
[:div.logo
[:img {:src "img/icon-shotbot.svg"}]
[:span "Shotbot"]]
[:div.login {:on-click (fn [_]
(dispatch [:reset-password/login]))}
[:img {:src "img/icon-login.svg"}]
[:span "Login"]]]
[:form {:on-submit (fn [evt]
(.preventDefault evt)
(dispatch [:reset-password/reset-password]))}
[:h1 "RESET PASSWORD"]
[:p "Enter your new password below"]
[:input {:type "PI:PASSWORD:<PASSWORD>END_PI"
:required true
:placeholder "New Password"
:on-change (fn [evt]
(dispatch [:reset-password/set-new-password
evt.target.value]))}]
[:input {:type "password"
:required true
:placeholder "Confirm Password"
:on-change (fn [evt]
(dispatch [:reset-password/set-confirm-password
evt.target.value]))}]
[:span.message @message]
[:input {:type "submit"
:value "Reset"}]
]
[:div]])))
|
[
{
"context": "e is a cellular automaton devised by mathematician John Conway.\n The 'board' consists of both live (#) and dea",
"end": 167,
"score": 0.9995320439338684,
"start": 156,
"tag": "NAME",
"value": "John Conway"
}
] |
src/clojure4j/explorer/questions/$91to$100/$94_game_h_game_of_life.clj
|
ningDr/clojure-4-me
| 0 |
(ns clojure4j.explorer.questions.$91to$100.$94-game-h-game-of-life)
(defn game-of-life
"The game of life is a cellular automaton devised by mathematician John Conway.
The 'board' consists of both live (#) and dead ( ) cells.
Each cell interacts with its eight neighbours (horizontal, vertical, diagonal),
and its next state is dependent on the following rules:
1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2) Any live cell with two or three live neighbours lives on to the next generation.
3) Any live cell with more than three live neighbours dies, as if by overcrowding.
4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Write a function that accepts a board, and returns a board representing the next generation of cells."
[arg]
(println "********************")
(println (= (arg [" "
" ## "
" ## "
" ## "
" ## "
" "])
[" "
" ## "
" # "
" # "
" ## "
" "]))
(println (arg [" "
" "
" ### "
" "
" "]))
(println (= (arg [" "
" "
" ### "
" "
" "])
[" "
" # "
" # "
" # "
" "]))
(println (= (arg [" "
" "
" ### "
" ### "
" "
" "])
[" "
" # "
" # # "
" # # "
" # "
" "]))
)
(def board [" "
" ## "
" ## "
" ## "
" ## "
" "])
(game-of-life (fn [board]
(let [element-len (count (first board))
transfer (mapv #(mapv (fn [i] (if (= i \#) 1 0)) (seq %)) board)
get-sum (fn [t x y]
(let [a (nth t (- y 1))
b (nth t y)
c (nth t (+ y 1))
v (- x 1)
z (+ x 1)]
(+
(nth a v) (nth b v) (nth c v)
(nth a z) (nth b z) (nth c z)
(nth a x) (nth c x))))
cal-sum (for [x (range 1 (- element-len 1))]
(for [y (range 1 (- element-len 1))]
{:x (nth (nth transfer x) y)
:f (get-sum transfer y x)}))
cc (mapv #(conj (reduce (fn [m n] (conj m (cond
(> 2 (:f n)) 0
(and (= 3 (:f n)) (zero? (:x n))) 1
(> 4 (:f n)) (:x n)
(> 3 (:f n)) 0
:else 0
))) [0] %) 0) cal-sum)
dd (reduce #(conj %1 %2) [] (take element-len (repeat 0)))
ee (conj (reduce #(conj %1 %2) [dd] cc) dd)]
(mapv #(reduce (fn [x y] (str x (if (= y 1) \# " "))) "" %) ee))))
(def a [[0 0 0 0 0] [0 0 1 0 0] [0 0 1 0 0] [0 0 1 0 0] [0 0 0 0 0]])
(def b (for [x (range 0 5)]
(for [y (range 0 5)]
(vector x y (nth (nth a x) y)))))
(def res (reduce #(concat %1 %2) [] b))
;(def transfer (mapv #(mapv (fn [i] (if (= i \#) 1 0)) (seq %)) board))
;
;(defn get-sum [t x y]
; (let [a (nth t (- y 1))
; b (nth t y)
; c (nth t (+ y 1))
; v (- x 1)
; z (+ x 1)]
; (+
; (nth a v) (nth b v) (nth c v)
; (nth a z) (nth b z) (nth c z)
; (nth a x) (nth c x))))
;
;(for [x (range 1 5)]
; (for [y (range 1 5)]
; {:x (nth (nth transfer y) x)
; :f (get-sum transfer x y)}))
;
;(def zz '(({:x 1, :f 3} {:x 1, :f 3} {:x 0, :f 2} {:x 0, :f 0})
; ({:x 1, :f 3} {:x 1, :f 4} {:x 0, :f 4} {:x 0, :f 2})
; ({:x 0, :f 2} {:x 0, :f 4} {:x 1, :f 4} {:x 1, :f 3})
; ({:x 0, :f 0} {:x 0, :f 2} {:x 1, :f 3} {:x 1, :f 3})))
;
;(def cc (mapv #(conj (reduce (fn [m n] (conj m (cond
; (> 2 (:f n)) 0
; (> 4 (:f n)) (:x n)
; (> 3 (:f n)) 0
; (and (= 3 (:f n)) (zero? (:x n))) 1
; :else 0
; ))) [0] %) 0) zz))
;
;(def dd (reduce #(conj %1 %2) [] (take 6 (repeat 0))))
;
;(def ee (conj (reduce #(conj %1 %2) [dd] cc) dd))
;
;(mapv #(reduce (fn [x y] (str x (if (= y 1) \# " "))) "" %) ee)
|
72568
|
(ns clojure4j.explorer.questions.$91to$100.$94-game-h-game-of-life)
(defn game-of-life
"The game of life is a cellular automaton devised by mathematician <NAME>.
The 'board' consists of both live (#) and dead ( ) cells.
Each cell interacts with its eight neighbours (horizontal, vertical, diagonal),
and its next state is dependent on the following rules:
1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2) Any live cell with two or three live neighbours lives on to the next generation.
3) Any live cell with more than three live neighbours dies, as if by overcrowding.
4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Write a function that accepts a board, and returns a board representing the next generation of cells."
[arg]
(println "********************")
(println (= (arg [" "
" ## "
" ## "
" ## "
" ## "
" "])
[" "
" ## "
" # "
" # "
" ## "
" "]))
(println (arg [" "
" "
" ### "
" "
" "]))
(println (= (arg [" "
" "
" ### "
" "
" "])
[" "
" # "
" # "
" # "
" "]))
(println (= (arg [" "
" "
" ### "
" ### "
" "
" "])
[" "
" # "
" # # "
" # # "
" # "
" "]))
)
(def board [" "
" ## "
" ## "
" ## "
" ## "
" "])
(game-of-life (fn [board]
(let [element-len (count (first board))
transfer (mapv #(mapv (fn [i] (if (= i \#) 1 0)) (seq %)) board)
get-sum (fn [t x y]
(let [a (nth t (- y 1))
b (nth t y)
c (nth t (+ y 1))
v (- x 1)
z (+ x 1)]
(+
(nth a v) (nth b v) (nth c v)
(nth a z) (nth b z) (nth c z)
(nth a x) (nth c x))))
cal-sum (for [x (range 1 (- element-len 1))]
(for [y (range 1 (- element-len 1))]
{:x (nth (nth transfer x) y)
:f (get-sum transfer y x)}))
cc (mapv #(conj (reduce (fn [m n] (conj m (cond
(> 2 (:f n)) 0
(and (= 3 (:f n)) (zero? (:x n))) 1
(> 4 (:f n)) (:x n)
(> 3 (:f n)) 0
:else 0
))) [0] %) 0) cal-sum)
dd (reduce #(conj %1 %2) [] (take element-len (repeat 0)))
ee (conj (reduce #(conj %1 %2) [dd] cc) dd)]
(mapv #(reduce (fn [x y] (str x (if (= y 1) \# " "))) "" %) ee))))
(def a [[0 0 0 0 0] [0 0 1 0 0] [0 0 1 0 0] [0 0 1 0 0] [0 0 0 0 0]])
(def b (for [x (range 0 5)]
(for [y (range 0 5)]
(vector x y (nth (nth a x) y)))))
(def res (reduce #(concat %1 %2) [] b))
;(def transfer (mapv #(mapv (fn [i] (if (= i \#) 1 0)) (seq %)) board))
;
;(defn get-sum [t x y]
; (let [a (nth t (- y 1))
; b (nth t y)
; c (nth t (+ y 1))
; v (- x 1)
; z (+ x 1)]
; (+
; (nth a v) (nth b v) (nth c v)
; (nth a z) (nth b z) (nth c z)
; (nth a x) (nth c x))))
;
;(for [x (range 1 5)]
; (for [y (range 1 5)]
; {:x (nth (nth transfer y) x)
; :f (get-sum transfer x y)}))
;
;(def zz '(({:x 1, :f 3} {:x 1, :f 3} {:x 0, :f 2} {:x 0, :f 0})
; ({:x 1, :f 3} {:x 1, :f 4} {:x 0, :f 4} {:x 0, :f 2})
; ({:x 0, :f 2} {:x 0, :f 4} {:x 1, :f 4} {:x 1, :f 3})
; ({:x 0, :f 0} {:x 0, :f 2} {:x 1, :f 3} {:x 1, :f 3})))
;
;(def cc (mapv #(conj (reduce (fn [m n] (conj m (cond
; (> 2 (:f n)) 0
; (> 4 (:f n)) (:x n)
; (> 3 (:f n)) 0
; (and (= 3 (:f n)) (zero? (:x n))) 1
; :else 0
; ))) [0] %) 0) zz))
;
;(def dd (reduce #(conj %1 %2) [] (take 6 (repeat 0))))
;
;(def ee (conj (reduce #(conj %1 %2) [dd] cc) dd))
;
;(mapv #(reduce (fn [x y] (str x (if (= y 1) \# " "))) "" %) ee)
| true |
(ns clojure4j.explorer.questions.$91to$100.$94-game-h-game-of-life)
(defn game-of-life
"The game of life is a cellular automaton devised by mathematician PI:NAME:<NAME>END_PI.
The 'board' consists of both live (#) and dead ( ) cells.
Each cell interacts with its eight neighbours (horizontal, vertical, diagonal),
and its next state is dependent on the following rules:
1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2) Any live cell with two or three live neighbours lives on to the next generation.
3) Any live cell with more than three live neighbours dies, as if by overcrowding.
4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Write a function that accepts a board, and returns a board representing the next generation of cells."
[arg]
(println "********************")
(println (= (arg [" "
" ## "
" ## "
" ## "
" ## "
" "])
[" "
" ## "
" # "
" # "
" ## "
" "]))
(println (arg [" "
" "
" ### "
" "
" "]))
(println (= (arg [" "
" "
" ### "
" "
" "])
[" "
" # "
" # "
" # "
" "]))
(println (= (arg [" "
" "
" ### "
" ### "
" "
" "])
[" "
" # "
" # # "
" # # "
" # "
" "]))
)
(def board [" "
" ## "
" ## "
" ## "
" ## "
" "])
(game-of-life (fn [board]
(let [element-len (count (first board))
transfer (mapv #(mapv (fn [i] (if (= i \#) 1 0)) (seq %)) board)
get-sum (fn [t x y]
(let [a (nth t (- y 1))
b (nth t y)
c (nth t (+ y 1))
v (- x 1)
z (+ x 1)]
(+
(nth a v) (nth b v) (nth c v)
(nth a z) (nth b z) (nth c z)
(nth a x) (nth c x))))
cal-sum (for [x (range 1 (- element-len 1))]
(for [y (range 1 (- element-len 1))]
{:x (nth (nth transfer x) y)
:f (get-sum transfer y x)}))
cc (mapv #(conj (reduce (fn [m n] (conj m (cond
(> 2 (:f n)) 0
(and (= 3 (:f n)) (zero? (:x n))) 1
(> 4 (:f n)) (:x n)
(> 3 (:f n)) 0
:else 0
))) [0] %) 0) cal-sum)
dd (reduce #(conj %1 %2) [] (take element-len (repeat 0)))
ee (conj (reduce #(conj %1 %2) [dd] cc) dd)]
(mapv #(reduce (fn [x y] (str x (if (= y 1) \# " "))) "" %) ee))))
(def a [[0 0 0 0 0] [0 0 1 0 0] [0 0 1 0 0] [0 0 1 0 0] [0 0 0 0 0]])
(def b (for [x (range 0 5)]
(for [y (range 0 5)]
(vector x y (nth (nth a x) y)))))
(def res (reduce #(concat %1 %2) [] b))
;(def transfer (mapv #(mapv (fn [i] (if (= i \#) 1 0)) (seq %)) board))
;
;(defn get-sum [t x y]
; (let [a (nth t (- y 1))
; b (nth t y)
; c (nth t (+ y 1))
; v (- x 1)
; z (+ x 1)]
; (+
; (nth a v) (nth b v) (nth c v)
; (nth a z) (nth b z) (nth c z)
; (nth a x) (nth c x))))
;
;(for [x (range 1 5)]
; (for [y (range 1 5)]
; {:x (nth (nth transfer y) x)
; :f (get-sum transfer x y)}))
;
;(def zz '(({:x 1, :f 3} {:x 1, :f 3} {:x 0, :f 2} {:x 0, :f 0})
; ({:x 1, :f 3} {:x 1, :f 4} {:x 0, :f 4} {:x 0, :f 2})
; ({:x 0, :f 2} {:x 0, :f 4} {:x 1, :f 4} {:x 1, :f 3})
; ({:x 0, :f 0} {:x 0, :f 2} {:x 1, :f 3} {:x 1, :f 3})))
;
;(def cc (mapv #(conj (reduce (fn [m n] (conj m (cond
; (> 2 (:f n)) 0
; (> 4 (:f n)) (:x n)
; (> 3 (:f n)) 0
; (and (= 3 (:f n)) (zero? (:x n))) 1
; :else 0
; ))) [0] %) 0) zz))
;
;(def dd (reduce #(conj %1 %2) [] (take 6 (repeat 0))))
;
;(def ee (conj (reduce #(conj %1 %2) [dd] cc) dd))
;
;(mapv #(reduce (fn [x y] (str x (if (= y 1) \# " "))) "" %) ee)
|
[
{
"context": ":doc \"Useful zip manipulation fns\"\n :author \"Sam Aaron\"}\n overtone.helpers.zip\n (:import [java.util.zi",
"end": 69,
"score": 0.9998872876167297,
"start": 60,
"tag": "NAME",
"value": "Sam Aaron"
}
] |
src/overtone/helpers/zip.clj
|
egoist999p/overtone
| 3,870 |
(ns
^{:doc "Useful zip manipulation fns"
:author "Sam Aaron"}
overtone.helpers.zip
(:import [java.util.zip ZipFile ZipEntry ZipInputStream]
[java.io StringWriter FileInputStream FileOutputStream])
(:use [clojure.java.io :only [file]]
[overtone.helpers file])
(:require [org.satta.glob :as satta-glob]
[clojure.java.io :as io]))
(defn zip-file
"Returns an open java.util.zip.ZipFile object representing the zip file
pointed to by path."
[path]
(let [path (resolve-tilde-path path)
file (file path)]
(ZipFile. file)))
(defn zip-entry
"Returns a java.util.zip.ZipEntry object representing the entry with name
entry-name within the zipfile pointed to by path. Ensures zipfile is closed.
Returns nil if entry-name not found within zipfile."
[path entry-name]
(let [^ZipFile zip (zip-file path)
entry (.getEntry zip entry-name)]
(.close zip)
entry))
(defn zip-ls
"Returns a seq of java.util.zip.ZipEntry objects representing the contents of
the zip file at the specified path. Ensures zipfile is closed"
[path]
(let [^ZipFile zip (zip-file path)
entries (.entries zip)
entries (doall (enumeration-seq entries))]
(.close zip)
entries))
(defn zip-cat
"Returns a string containing the contents of the specified entry within the
zipfile pointed to by path. Ensures zipfile is closed. Returns nil if
entry-name not found within zipfile."
[path entry-name]
(let [sw (StringWriter.)
^ZipFile zip (zip-file path)
entry (zip-entry path entry-name)]
(if (and zip entry)
(do
(io/copy (.getInputStream zip entry) sw)
(.close zip)
(.toString sw))
(do
(.close zip)
nil))))
(defn unzip
"Unzip a zip file pointed to by zip-path into dest-path dir. Does not allow
zip file content paths to contain .. parent shortcut for security reasons i.e.
all unzipped files will be extracted beneath dest-path. If zip file contains
compressed subdirectories, these will be created too."
[zip-path dest-path]
(let [zip-path (resolve-tilde-path zip-path)
dest-path (resolve-tilde-path dest-path)
dest-path (canonical-path dest-path)]
(when-not (dir-exists? dest-path)
(throw (Exception. (str "Destination directory does not exist: " dest-path))))
(when-not (file-exists? zip-path)
(throw (Exception. (str "Source zip file does not exist: " zip-path))))
(let [^ZipFile zip (zip-file zip-path)
entries (.entries zip)
entries (doall (enumeration-seq entries))]
(dorun
(map
(fn [^java.io.File entry]
(let [name (.getName entry)
full-dest-path (mk-path dest-path name)
^java.lang.String full-dest-path (canonical-path full-dest-path)]
(when-not (subdir? full-dest-path dest-path)
(throw (Exception. "Security warning - unzip was requested to create a path which is not within original dest-path. Aborting operation.")))
(if (.isDirectory entry)
(mkdir-p! full-dest-path)
(let [is (.getInputStream zip entry)
fs (FileOutputStream. full-dest-path)]
(io/copy is fs)))))
entries)))))
|
117823
|
(ns
^{:doc "Useful zip manipulation fns"
:author "<NAME>"}
overtone.helpers.zip
(:import [java.util.zip ZipFile ZipEntry ZipInputStream]
[java.io StringWriter FileInputStream FileOutputStream])
(:use [clojure.java.io :only [file]]
[overtone.helpers file])
(:require [org.satta.glob :as satta-glob]
[clojure.java.io :as io]))
(defn zip-file
"Returns an open java.util.zip.ZipFile object representing the zip file
pointed to by path."
[path]
(let [path (resolve-tilde-path path)
file (file path)]
(ZipFile. file)))
(defn zip-entry
"Returns a java.util.zip.ZipEntry object representing the entry with name
entry-name within the zipfile pointed to by path. Ensures zipfile is closed.
Returns nil if entry-name not found within zipfile."
[path entry-name]
(let [^ZipFile zip (zip-file path)
entry (.getEntry zip entry-name)]
(.close zip)
entry))
(defn zip-ls
"Returns a seq of java.util.zip.ZipEntry objects representing the contents of
the zip file at the specified path. Ensures zipfile is closed"
[path]
(let [^ZipFile zip (zip-file path)
entries (.entries zip)
entries (doall (enumeration-seq entries))]
(.close zip)
entries))
(defn zip-cat
"Returns a string containing the contents of the specified entry within the
zipfile pointed to by path. Ensures zipfile is closed. Returns nil if
entry-name not found within zipfile."
[path entry-name]
(let [sw (StringWriter.)
^ZipFile zip (zip-file path)
entry (zip-entry path entry-name)]
(if (and zip entry)
(do
(io/copy (.getInputStream zip entry) sw)
(.close zip)
(.toString sw))
(do
(.close zip)
nil))))
(defn unzip
"Unzip a zip file pointed to by zip-path into dest-path dir. Does not allow
zip file content paths to contain .. parent shortcut for security reasons i.e.
all unzipped files will be extracted beneath dest-path. If zip file contains
compressed subdirectories, these will be created too."
[zip-path dest-path]
(let [zip-path (resolve-tilde-path zip-path)
dest-path (resolve-tilde-path dest-path)
dest-path (canonical-path dest-path)]
(when-not (dir-exists? dest-path)
(throw (Exception. (str "Destination directory does not exist: " dest-path))))
(when-not (file-exists? zip-path)
(throw (Exception. (str "Source zip file does not exist: " zip-path))))
(let [^ZipFile zip (zip-file zip-path)
entries (.entries zip)
entries (doall (enumeration-seq entries))]
(dorun
(map
(fn [^java.io.File entry]
(let [name (.getName entry)
full-dest-path (mk-path dest-path name)
^java.lang.String full-dest-path (canonical-path full-dest-path)]
(when-not (subdir? full-dest-path dest-path)
(throw (Exception. "Security warning - unzip was requested to create a path which is not within original dest-path. Aborting operation.")))
(if (.isDirectory entry)
(mkdir-p! full-dest-path)
(let [is (.getInputStream zip entry)
fs (FileOutputStream. full-dest-path)]
(io/copy is fs)))))
entries)))))
| true |
(ns
^{:doc "Useful zip manipulation fns"
:author "PI:NAME:<NAME>END_PI"}
overtone.helpers.zip
(:import [java.util.zip ZipFile ZipEntry ZipInputStream]
[java.io StringWriter FileInputStream FileOutputStream])
(:use [clojure.java.io :only [file]]
[overtone.helpers file])
(:require [org.satta.glob :as satta-glob]
[clojure.java.io :as io]))
(defn zip-file
"Returns an open java.util.zip.ZipFile object representing the zip file
pointed to by path."
[path]
(let [path (resolve-tilde-path path)
file (file path)]
(ZipFile. file)))
(defn zip-entry
"Returns a java.util.zip.ZipEntry object representing the entry with name
entry-name within the zipfile pointed to by path. Ensures zipfile is closed.
Returns nil if entry-name not found within zipfile."
[path entry-name]
(let [^ZipFile zip (zip-file path)
entry (.getEntry zip entry-name)]
(.close zip)
entry))
(defn zip-ls
"Returns a seq of java.util.zip.ZipEntry objects representing the contents of
the zip file at the specified path. Ensures zipfile is closed"
[path]
(let [^ZipFile zip (zip-file path)
entries (.entries zip)
entries (doall (enumeration-seq entries))]
(.close zip)
entries))
(defn zip-cat
"Returns a string containing the contents of the specified entry within the
zipfile pointed to by path. Ensures zipfile is closed. Returns nil if
entry-name not found within zipfile."
[path entry-name]
(let [sw (StringWriter.)
^ZipFile zip (zip-file path)
entry (zip-entry path entry-name)]
(if (and zip entry)
(do
(io/copy (.getInputStream zip entry) sw)
(.close zip)
(.toString sw))
(do
(.close zip)
nil))))
(defn unzip
"Unzip a zip file pointed to by zip-path into dest-path dir. Does not allow
zip file content paths to contain .. parent shortcut for security reasons i.e.
all unzipped files will be extracted beneath dest-path. If zip file contains
compressed subdirectories, these will be created too."
[zip-path dest-path]
(let [zip-path (resolve-tilde-path zip-path)
dest-path (resolve-tilde-path dest-path)
dest-path (canonical-path dest-path)]
(when-not (dir-exists? dest-path)
(throw (Exception. (str "Destination directory does not exist: " dest-path))))
(when-not (file-exists? zip-path)
(throw (Exception. (str "Source zip file does not exist: " zip-path))))
(let [^ZipFile zip (zip-file zip-path)
entries (.entries zip)
entries (doall (enumeration-seq entries))]
(dorun
(map
(fn [^java.io.File entry]
(let [name (.getName entry)
full-dest-path (mk-path dest-path name)
^java.lang.String full-dest-path (canonical-path full-dest-path)]
(when-not (subdir? full-dest-path dest-path)
(throw (Exception. "Security warning - unzip was requested to create a path which is not within original dest-path. Aborting operation.")))
(if (.isDirectory entry)
(mkdir-p! full-dest-path)
(let [is (.getInputStream zip entry)
fs (FileOutputStream. full-dest-path)]
(io/copy is fs)))))
entries)))))
|
[
{
"context": " :password \"Password1234\"\n :tunnel-ho",
"end": 3173,
"score": 0.9993554949760437,
"start": 3161,
"tag": "PASSWORD",
"value": "Password1234"
},
{
"context": " :tunnel-private-key-passphrase \"Password1234\"}\n :id 3})\n ",
"end": 4050,
"score": 0.9993589520454407,
"start": 4038,
"tag": "PASSWORD",
"value": "Password1234"
},
{
"context": "ession/with-current-user\n (mt/user->id :rasta)\n (is (= {\"description\" nil\n ",
"end": 4902,
"score": 0.6688712239265442,
"start": 4898,
"tag": "USERNAME",
"value": "asta"
},
{
"context": "description\" nil\n \"name\" \"testpg\"\n \"id\" 3}\n ",
"end": 4979,
"score": 0.9886912703514099,
"start": 4973,
"tag": "USERNAME",
"value": "testpg"
},
{
"context": "description\" nil\n \"name\" \"testbq\"\n \"id\" 2\n ",
"end": 5132,
"score": 0.9680396318435669,
"start": 5126,
"tag": "USERNAME",
"value": "testbq"
},
{
"context": "session/with-current-user\n (mt/user->id :crowberto)\n (is (= {\"description\" nil\n ",
"end": 5383,
"score": 0.9215849041938782,
"start": 5374,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "description\" nil\n \"name\" \"testpg\"\n \"details\" {\"tunnel-user\" ",
"end": 5460,
"score": 0.9762392044067383,
"start": 5454,
"tag": "USERNAME",
"value": "testpg"
},
{
"context": " \"tunnel-private-key-passphrase\" \"**MetabasePass**\"\n \"additional-opt",
"end": 5847,
"score": 0.9925304651260376,
"start": 5835,
"tag": "PASSWORD",
"value": "MetabasePass"
},
{
"context": " \"password\" \"**MetabasePass**\"\n \"tunnel-host\" ",
"end": 6439,
"score": 0.9954615831375122,
"start": 6427,
"tag": "PASSWORD",
"value": "MetabasePass"
},
{
"context": "description\" nil\n \"name\" \"testbq\"\n \"details\" {\"use-service-ac",
"end": 6672,
"score": 0.9250662326812744,
"start": 6666,
"tag": "USERNAME",
"value": "testbq"
}
] |
c#-metabase/test/metabase/models/database_test.clj
|
hanakhry/Crime_Admin
| 0 |
(ns metabase.models.database-test
(:require [cheshire.core :refer [decode encode]]
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.models :refer [Database]]
[metabase.models.database :as mdb]
[metabase.models.permissions :as perms]
[metabase.models.user :as user]
[metabase.server.middleware.session :as mw.session]
[metabase.task :as task]
[metabase.task.sync-databases :as task.sync-databases]
[metabase.test :as mt]
[schema.core :as s]
[toucan.db :as db]))
(defn- trigger-for-db [db-id]
(some (fn [{trigger-key :key, :as trigger}]
(when (str/ends-with? trigger-key (str \. db-id))
trigger))
(:triggers (task/job-info "metabase.task.sync-and-analyze.job"))))
(deftest perms-test
(testing "After creating a Database, All Users group should get full permissions by default"
(mt/with-temp Database [db]
(is (= true
(perms/set-has-full-permissions? (user/permissions-set (mt/user->id :rasta))
(perms/object-path db)))))))
(deftest tasks-test
(testing "Sync tasks should get scheduled for a newly created Database"
(mt/with-temp-scheduler
;; temporarily disable the `maybe-update-db-schedules` behavior that normally happens when the sync databases
;; task gets initialized so we don't end up getting all of our database sync schedules randomized.
(with-redefs [task.sync-databases/maybe-update-db-schedules identity]
(task/init! ::task.sync-databases/SyncDatabases))
(mt/with-temp Database [{db-id :id}]
(is (schema= {:description (s/eq (format "sync-and-analyze Database %d" db-id))
:key (s/eq (format "metabase.task.sync-and-analyze.trigger.%d" db-id))
:misfire-instruction (s/eq "DO_NOTHING")
:state (s/eq "NORMAL")
:may-fire-again? (s/eq true)
:schedule (s/eq "0 50 * * * ? *")
:final-fire-time (s/eq nil)
:data (s/eq {"db-id" db-id})
s/Keyword s/Any}
(trigger-for-db db-id)))
(testing "When deleting a Database, sync tasks should get removed"
(db/delete! Database :id db-id)
(is (= nil
(trigger-for-db db-id))))))))
(deftest sensitive-data-redacted-test
(let [encode-decode (fn [obj] (decode (encode obj)))
;; this is trimmed for the parts we care about in the test
pg-db (mdb/map->DatabaseInstance
{:description nil
:name "testpg"
:details {:additional-options nil
:ssl false
:password "Password1234"
:tunnel-host "localhost"
:port 5432
:dbname "mydb"
:host "localhost"
:tunnel-enabled true
:tunnel-auth-option "ssh-key"
:tunnel-port 22
:tunnel-private-key "PRIVATE KEY IS HERE"
:user "metabase"
:tunnel-user "a-tunnel-user"
:tunnel-private-key-passphrase "Password1234"}
:id 3})
bq-db (mdb/map->DatabaseInstance
{:description nil
:name "testbq"
:details {:use-service-account nil
:dataset-id "office_checkins"
:service-account-json "SERVICE-ACCOUNT-JSON-HERE"
:use-jvm-timezone false
:project-id "metabase-bigquery-driver"}
:id 2
:engine :bigquery})]
(testing "sensitive fields are redacted when database details are encoded"
(testing "details removed for non-admin users"
(mw.session/with-current-user
(mt/user->id :rasta)
(is (= {"description" nil
"name" "testpg"
"id" 3}
(encode-decode pg-db)))
(is (= {"description" nil
"name" "testbq"
"id" 2
"engine" "bigquery"}
(encode-decode bq-db)))))
(testing "details are obfuscated for admin users"
(mw.session/with-current-user
(mt/user->id :crowberto)
(is (= {"description" nil
"name" "testpg"
"details" {"tunnel-user" "a-tunnel-user"
"dbname" "mydb"
"host" "localhost"
"tunnel-auth-option" "ssh-key"
"tunnel-private-key-passphrase" "**MetabasePass**"
"additional-options" nil
"tunnel-port" 22
"user" "metabase"
"tunnel-private-key" "**MetabasePass**"
"ssl" false
"tunnel-enabled" true
"port" 5432
"password" "**MetabasePass**"
"tunnel-host" "localhost"}
"id" 3}
(encode-decode pg-db)))
(is (= {"description" nil
"name" "testbq"
"details" {"use-service-account" nil
"dataset-id" "office_checkins"
"service-account-json" "**MetabasePass**"
"use-jvm-timezone" false
"project-id" "metabase-bigquery-driver"}
"id" 2
"engine" "bigquery"}
(encode-decode bq-db))))))))
;; register a dummy "driver" for the sole purpose of running sensitive-fields-test
(driver/register! :test-sensitive-driver, :parent #{:h2})
;; define a couple custom connection properties for this driver, one of which has :type :password
(defmethod driver/connection-properties :test-sensitive-driver
[_]
[{:name "custom-field-1"
:display-name "Custom Field 1"
:placeholder "Not particularly secret field"
:type :string
:required true}
{:name "custom-field-2-secret"
:display-name "Custom Field 2"
:placeholder "Has some secret stuff in it"
:type :password
:required true}])
(deftest sensitive-fields-test
(testing "get-sensitive-fields returns the custom :password type field in addition to all default ones"
(is (= (conj driver.u/default-sensitive-fields :custom-field-2-secret)
(driver.u/sensitive-fields :test-sensitive-driver))))
(testing "get-sensitive-fields-for-db returns default fields for null or empty database map"
(is (= driver.u/default-sensitive-fields
(mdb/sensitive-fields-for-db nil)))
(is (= driver.u/default-sensitive-fields
(mdb/sensitive-fields-for-db {})))))
|
19522
|
(ns metabase.models.database-test
(:require [cheshire.core :refer [decode encode]]
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.models :refer [Database]]
[metabase.models.database :as mdb]
[metabase.models.permissions :as perms]
[metabase.models.user :as user]
[metabase.server.middleware.session :as mw.session]
[metabase.task :as task]
[metabase.task.sync-databases :as task.sync-databases]
[metabase.test :as mt]
[schema.core :as s]
[toucan.db :as db]))
(defn- trigger-for-db [db-id]
(some (fn [{trigger-key :key, :as trigger}]
(when (str/ends-with? trigger-key (str \. db-id))
trigger))
(:triggers (task/job-info "metabase.task.sync-and-analyze.job"))))
(deftest perms-test
(testing "After creating a Database, All Users group should get full permissions by default"
(mt/with-temp Database [db]
(is (= true
(perms/set-has-full-permissions? (user/permissions-set (mt/user->id :rasta))
(perms/object-path db)))))))
(deftest tasks-test
(testing "Sync tasks should get scheduled for a newly created Database"
(mt/with-temp-scheduler
;; temporarily disable the `maybe-update-db-schedules` behavior that normally happens when the sync databases
;; task gets initialized so we don't end up getting all of our database sync schedules randomized.
(with-redefs [task.sync-databases/maybe-update-db-schedules identity]
(task/init! ::task.sync-databases/SyncDatabases))
(mt/with-temp Database [{db-id :id}]
(is (schema= {:description (s/eq (format "sync-and-analyze Database %d" db-id))
:key (s/eq (format "metabase.task.sync-and-analyze.trigger.%d" db-id))
:misfire-instruction (s/eq "DO_NOTHING")
:state (s/eq "NORMAL")
:may-fire-again? (s/eq true)
:schedule (s/eq "0 50 * * * ? *")
:final-fire-time (s/eq nil)
:data (s/eq {"db-id" db-id})
s/Keyword s/Any}
(trigger-for-db db-id)))
(testing "When deleting a Database, sync tasks should get removed"
(db/delete! Database :id db-id)
(is (= nil
(trigger-for-db db-id))))))))
(deftest sensitive-data-redacted-test
(let [encode-decode (fn [obj] (decode (encode obj)))
;; this is trimmed for the parts we care about in the test
pg-db (mdb/map->DatabaseInstance
{:description nil
:name "testpg"
:details {:additional-options nil
:ssl false
:password "<PASSWORD>"
:tunnel-host "localhost"
:port 5432
:dbname "mydb"
:host "localhost"
:tunnel-enabled true
:tunnel-auth-option "ssh-key"
:tunnel-port 22
:tunnel-private-key "PRIVATE KEY IS HERE"
:user "metabase"
:tunnel-user "a-tunnel-user"
:tunnel-private-key-passphrase "<PASSWORD>"}
:id 3})
bq-db (mdb/map->DatabaseInstance
{:description nil
:name "testbq"
:details {:use-service-account nil
:dataset-id "office_checkins"
:service-account-json "SERVICE-ACCOUNT-JSON-HERE"
:use-jvm-timezone false
:project-id "metabase-bigquery-driver"}
:id 2
:engine :bigquery})]
(testing "sensitive fields are redacted when database details are encoded"
(testing "details removed for non-admin users"
(mw.session/with-current-user
(mt/user->id :rasta)
(is (= {"description" nil
"name" "testpg"
"id" 3}
(encode-decode pg-db)))
(is (= {"description" nil
"name" "testbq"
"id" 2
"engine" "bigquery"}
(encode-decode bq-db)))))
(testing "details are obfuscated for admin users"
(mw.session/with-current-user
(mt/user->id :crowberto)
(is (= {"description" nil
"name" "testpg"
"details" {"tunnel-user" "a-tunnel-user"
"dbname" "mydb"
"host" "localhost"
"tunnel-auth-option" "ssh-key"
"tunnel-private-key-passphrase" "**<PASSWORD>**"
"additional-options" nil
"tunnel-port" 22
"user" "metabase"
"tunnel-private-key" "**MetabasePass**"
"ssl" false
"tunnel-enabled" true
"port" 5432
"password" "**<PASSWORD>**"
"tunnel-host" "localhost"}
"id" 3}
(encode-decode pg-db)))
(is (= {"description" nil
"name" "testbq"
"details" {"use-service-account" nil
"dataset-id" "office_checkins"
"service-account-json" "**MetabasePass**"
"use-jvm-timezone" false
"project-id" "metabase-bigquery-driver"}
"id" 2
"engine" "bigquery"}
(encode-decode bq-db))))))))
;; register a dummy "driver" for the sole purpose of running sensitive-fields-test
(driver/register! :test-sensitive-driver, :parent #{:h2})
;; define a couple custom connection properties for this driver, one of which has :type :password
(defmethod driver/connection-properties :test-sensitive-driver
[_]
[{:name "custom-field-1"
:display-name "Custom Field 1"
:placeholder "Not particularly secret field"
:type :string
:required true}
{:name "custom-field-2-secret"
:display-name "Custom Field 2"
:placeholder "Has some secret stuff in it"
:type :password
:required true}])
(deftest sensitive-fields-test
(testing "get-sensitive-fields returns the custom :password type field in addition to all default ones"
(is (= (conj driver.u/default-sensitive-fields :custom-field-2-secret)
(driver.u/sensitive-fields :test-sensitive-driver))))
(testing "get-sensitive-fields-for-db returns default fields for null or empty database map"
(is (= driver.u/default-sensitive-fields
(mdb/sensitive-fields-for-db nil)))
(is (= driver.u/default-sensitive-fields
(mdb/sensitive-fields-for-db {})))))
| true |
(ns metabase.models.database-test
(:require [cheshire.core :refer [decode encode]]
[clojure.string :as str]
[clojure.test :refer :all]
[metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.models :refer [Database]]
[metabase.models.database :as mdb]
[metabase.models.permissions :as perms]
[metabase.models.user :as user]
[metabase.server.middleware.session :as mw.session]
[metabase.task :as task]
[metabase.task.sync-databases :as task.sync-databases]
[metabase.test :as mt]
[schema.core :as s]
[toucan.db :as db]))
(defn- trigger-for-db [db-id]
(some (fn [{trigger-key :key, :as trigger}]
(when (str/ends-with? trigger-key (str \. db-id))
trigger))
(:triggers (task/job-info "metabase.task.sync-and-analyze.job"))))
(deftest perms-test
(testing "After creating a Database, All Users group should get full permissions by default"
(mt/with-temp Database [db]
(is (= true
(perms/set-has-full-permissions? (user/permissions-set (mt/user->id :rasta))
(perms/object-path db)))))))
(deftest tasks-test
(testing "Sync tasks should get scheduled for a newly created Database"
(mt/with-temp-scheduler
;; temporarily disable the `maybe-update-db-schedules` behavior that normally happens when the sync databases
;; task gets initialized so we don't end up getting all of our database sync schedules randomized.
(with-redefs [task.sync-databases/maybe-update-db-schedules identity]
(task/init! ::task.sync-databases/SyncDatabases))
(mt/with-temp Database [{db-id :id}]
(is (schema= {:description (s/eq (format "sync-and-analyze Database %d" db-id))
:key (s/eq (format "metabase.task.sync-and-analyze.trigger.%d" db-id))
:misfire-instruction (s/eq "DO_NOTHING")
:state (s/eq "NORMAL")
:may-fire-again? (s/eq true)
:schedule (s/eq "0 50 * * * ? *")
:final-fire-time (s/eq nil)
:data (s/eq {"db-id" db-id})
s/Keyword s/Any}
(trigger-for-db db-id)))
(testing "When deleting a Database, sync tasks should get removed"
(db/delete! Database :id db-id)
(is (= nil
(trigger-for-db db-id))))))))
(deftest sensitive-data-redacted-test
(let [encode-decode (fn [obj] (decode (encode obj)))
;; this is trimmed for the parts we care about in the test
pg-db (mdb/map->DatabaseInstance
{:description nil
:name "testpg"
:details {:additional-options nil
:ssl false
:password "PI:PASSWORD:<PASSWORD>END_PI"
:tunnel-host "localhost"
:port 5432
:dbname "mydb"
:host "localhost"
:tunnel-enabled true
:tunnel-auth-option "ssh-key"
:tunnel-port 22
:tunnel-private-key "PRIVATE KEY IS HERE"
:user "metabase"
:tunnel-user "a-tunnel-user"
:tunnel-private-key-passphrase "PI:PASSWORD:<PASSWORD>END_PI"}
:id 3})
bq-db (mdb/map->DatabaseInstance
{:description nil
:name "testbq"
:details {:use-service-account nil
:dataset-id "office_checkins"
:service-account-json "SERVICE-ACCOUNT-JSON-HERE"
:use-jvm-timezone false
:project-id "metabase-bigquery-driver"}
:id 2
:engine :bigquery})]
(testing "sensitive fields are redacted when database details are encoded"
(testing "details removed for non-admin users"
(mw.session/with-current-user
(mt/user->id :rasta)
(is (= {"description" nil
"name" "testpg"
"id" 3}
(encode-decode pg-db)))
(is (= {"description" nil
"name" "testbq"
"id" 2
"engine" "bigquery"}
(encode-decode bq-db)))))
(testing "details are obfuscated for admin users"
(mw.session/with-current-user
(mt/user->id :crowberto)
(is (= {"description" nil
"name" "testpg"
"details" {"tunnel-user" "a-tunnel-user"
"dbname" "mydb"
"host" "localhost"
"tunnel-auth-option" "ssh-key"
"tunnel-private-key-passphrase" "**PI:PASSWORD:<PASSWORD>END_PI**"
"additional-options" nil
"tunnel-port" 22
"user" "metabase"
"tunnel-private-key" "**MetabasePass**"
"ssl" false
"tunnel-enabled" true
"port" 5432
"password" "**PI:PASSWORD:<PASSWORD>END_PI**"
"tunnel-host" "localhost"}
"id" 3}
(encode-decode pg-db)))
(is (= {"description" nil
"name" "testbq"
"details" {"use-service-account" nil
"dataset-id" "office_checkins"
"service-account-json" "**MetabasePass**"
"use-jvm-timezone" false
"project-id" "metabase-bigquery-driver"}
"id" 2
"engine" "bigquery"}
(encode-decode bq-db))))))))
;; register a dummy "driver" for the sole purpose of running sensitive-fields-test
(driver/register! :test-sensitive-driver, :parent #{:h2})
;; define a couple custom connection properties for this driver, one of which has :type :password
(defmethod driver/connection-properties :test-sensitive-driver
[_]
[{:name "custom-field-1"
:display-name "Custom Field 1"
:placeholder "Not particularly secret field"
:type :string
:required true}
{:name "custom-field-2-secret"
:display-name "Custom Field 2"
:placeholder "Has some secret stuff in it"
:type :password
:required true}])
(deftest sensitive-fields-test
(testing "get-sensitive-fields returns the custom :password type field in addition to all default ones"
(is (= (conj driver.u/default-sensitive-fields :custom-field-2-secret)
(driver.u/sensitive-fields :test-sensitive-driver))))
(testing "get-sensitive-fields-for-db returns default fields for null or empty database map"
(is (= driver.u/default-sensitive-fields
(mdb/sensitive-fields-for-db nil)))
(is (= driver.u/default-sensitive-fields
(mdb/sensitive-fields-for-db {})))))
|
[
{
"context": "swap! credentials assoc host {:name name :password password})))\n details))))\n\n(defn connect [url & con",
"end": 3038,
"score": 0.9774638414382935,
"start": 3030,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "acet-prefix-on-a-single-facet-field\n ;; http://192.168.0.200:8983/solr/i2ksearch/select?facet.field={!key=f1%2",
"end": 20762,
"score": 0.9997246265411377,
"start": 20749,
"tag": "IP_ADDRESS",
"value": "192.168.0.200"
}
] |
src/clojure_solr.clj
|
sflorez/clojure-solr
| 0 |
(ns clojure-solr
(:require [clojure.string :as str]
[clojure.pprint :as pprint])
(:require [clj-time.core :as t])
(:require [clj-time.format :as tformat])
(:require [clj-time.coerce :as tcoerce])
(:import (java.net URI)
(java.util Base64 HashMap List ArrayList)
(java.nio.charset Charset)
(org.apache.http HttpRequest HttpRequestInterceptor HttpHeaders)
(org.apache.http.auth AuthScope UsernamePasswordCredentials)
(org.apache.http.client.protocol HttpClientContext)
(org.apache.http.impl.auth BasicScheme)
(org.apache.http.impl.client BasicCredentialsProvider HttpClientBuilder)
(org.apache.http.protocol HttpContext HttpCoreContext)
(org.apache.solr.client.solrj SolrQuery SolrRequest$METHOD)
(org.apache.solr.client.solrj.impl HttpSolrClient HttpClientUtil)
(org.apache.solr.client.solrj.embedded EmbeddedSolrServer)
(org.apache.solr.client.solrj.response QueryResponse FacetField PivotField RangeFacet RangeFacet$Count RangeFacet$Date)
(org.apache.solr.common SolrInputDocument)
(org.apache.solr.common.params ModifiableSolrParams CursorMarkParams MoreLikeThisParams)
(org.apache.solr.common.util NamedList)
(org.apache.solr.util DateMathParser)))
(def ^:private url-details (atom {}))
(def ^:private credentials-provider (BasicCredentialsProvider.))
(def ^:private credentials (atom {}))
(declare ^:dynamic *connection*)
(def ^:dynamic *trace-fn* nil)
(declare make-param)
(defn trace
[str]
(when *trace-fn*
(*trace-fn* str)))
(defmacro with-trace
[fn & body]
`(binding [*trace-fn* ~fn]
~@body))
(defn make-basic-credentials
[name password]
(UsernamePasswordCredentials. name password))
(defn make-auth-scope
[host port]
(AuthScope. host port))
(defn set-credentials
[uri name password]
(.setCredentials credentials-provider
(make-auth-scope (.getHost uri) (.getPort uri))
(make-basic-credentials name password)))
(defn get-url-details
[url]
(let [details (get @url-details url)]
(if details
details
(let [[_ scheme name password rest] (re-matches #"(https?)://(.+):(.+)@(.*)" url)
details (if (and scheme name password rest)
{:clean-url (str scheme "://" rest)
:password password
:name name}
{:clean-url url})
uri (URI. (:clean-url details))]
(swap! url-details assoc url details)
(when (and name password)
(let [host (if (= (.getPort uri) -1)
(str (.getScheme uri) "://" (.getHost uri))
(str (.getScheme uri) "://" (.getHost uri) ":" (.getPort uri)))]
;;(println "**** CLOJURE-SOLR: Adding credentials for host" host)
(set-credentials uri name password)
(swap! credentials assoc host {:name name :password password})))
details))))
(defn connect [url & conn-manager]
(let [params (ModifiableSolrParams.)
{:keys [clean-url name password]} (get-url-details url)
builder (doto (HttpClientBuilder/create)
(.setDefaultCredentialsProvider credentials-provider)
(.setConnectionManager (when conn-manager (first conn-manager)))
(.addInterceptorFirst
(reify
HttpRequestInterceptor
(^void process [this ^HttpRequest request ^HttpContext context]
(let [auth-state (.getAttribute context HttpClientContext/TARGET_AUTH_STATE)]
(when (nil? (.getAuthScheme auth-state))
(let [target-host (.getAttribute context HttpCoreContext/HTTP_TARGET_HOST)
auth-scope (make-auth-scope (.getHostName target-host) (.getPort target-host))
creds (.getCredentials credentials-provider auth-scope)]
;;(println "**** CLOJURE-SOLR: HttpRequestInterceptor here. Looking for" auth-scope)
(when creds
(.update auth-state (BasicScheme.) creds)))))))))
client (.build builder)]
(HttpSolrClient. clean-url client)))
(defn- make-document [boost-map doc]
(let [sdoc (SolrInputDocument.)]
(doseq [[key value] doc]
(let [key-string (name key)
boost (get boost-map key)]
(if boost
(.addField sdoc key-string value boost)
(.addField sdoc key-string value))))
sdoc))
(defn add-document!
([doc boost-map]
(.add *connection* (make-document boost-map doc)))
([doc]
(add-document! doc {})))
(defn add-documents!
([coll boost-map]
(.add *connection* (map (partial make-document boost-map) coll)))
([coll]
(add-documents! coll {})))
(defn commit! []
(.commit *connection*))
(defn- doc-to-hash [doc]
(into {} (for [[k v] (clojure.lang.PersistentArrayMap/create doc)]
[(keyword k)
(cond (= java.util.ArrayList (type v)) (into [] v)
:else v)])))
(defn- make-param [p]
(cond
(string? p) (into-array String [p])
(coll? p) (into-array String (map str p))
:else (into-array String [(str p)])))
(def http-methods {:get SolrRequest$METHOD/GET, :GET SolrRequest$METHOD/GET
:post SolrRequest$METHOD/POST, :POST SolrRequest$METHOD/POST})
(defn- parse-method [method]
(get http-methods method SolrRequest$METHOD/GET))
(defn extract-facets
[query-results facet-hier-sep limiting? formatters key-fields]
(map (fn [^FacetField f]
(let [field-name (.getName f)
facet-name (get key-fields field-name field-name)]
{:name facet-name
:values (sort-by :path
(map (fn [v]
(let [result
(merge
{:value (.getName v)
:count (.getCount v)}
(when-let [split-path (and facet-hier-sep (str/split (.getName v) facet-hier-sep))]
{:split-path split-path
:title (last split-path)
:depth (count split-path)}))]
((get formatters facet-name identity) result)))
(.getValues f)))}))
^List (if limiting?
(.getLimitingFacets query-results)
(.getFacetFields query-results))))
(def date-time-formatter
(tformat/formatters :date-time-no-ms))
(def query-result-date-time-parser
(tformat/formatter t/utc "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'" "YYYY-MM-dd'T'HH:mm:ss'Z'"))
(defn format-range-value
"Timezone is only used if it's a date facet (and timezone is not null)."
[val timezone end?]
(let [d (try (tformat/parse date-time-formatter val)
(catch Exception _))]
(cond (or d (instance? java.util.Date val))
(let [d (or d (tcoerce/from-date val))]
(tformat/unparse (if timezone (tformat/with-zone date-time-formatter timezone) date-time-formatter)
(if end? (t/minus d (t/seconds 1)) d)))
:else (str val))))
(defn format-standard-filter-query
[name value]
(format "%s:%s" name value))
(defn format-raw-query
[name value]
(format "{!raw f=%s}%s" name value))
(defn format-facet-query
[{:keys [name value formatter]}]
(if (and (string? value) (re-find #"\[" value)) ;; range filter
(format-standard-filter-query name value)
(if formatter
(formatter name value)
(format-raw-query name value))))
(defn extract-facet-ranges
"Explicitly pass facet-date-ranges in case one or more ranges are date ranges, and we need to grab a timezone."
[query-results facet-date-ranges]
(sort-by :name
(map (fn [^RangeFacet r]
(let [date-range? (some (fn [{:keys [field]}] (= field (.getName r)))
facet-date-ranges)
timezone (:timezone (first (filter (fn [{:keys [field]}] (= field (.getName r)))
facet-date-ranges)))
gap (.getGap r)
values
(map (fn [val]
(let [start-val (.getValue val)
start-str (format-range-value start-val nil false)
end-val (cond date-range?
(.parseMath (doto (DateMathParser.)
(.setNow
(tcoerce/to-date
(tformat/parse query-result-date-time-parser start-val))))
gap)
(re-matches #"\d+" start-val)
(+ (Integer/parseInt start-val) gap)
:else (+ (Double/parseDouble start-val) gap))
end-str (format-range-value end-val nil true)]
{:count (.getCount val)
:value (format (if date-range? "[%s TO %s]" "[%s TO %s}") start-str end-str)
:min-inclusive start-str
:max-noninclusive end-str}))
(.getCounts r))
values-before (if (and (.getBefore r) (> (.getBefore r) 0))
(concat [{:count (.getBefore r)
:value (format (if date-range? "[* TO %s]" "[* TO %s}")
(format-range-value (.getStart r) nil true))
:min-inclusive nil
:max-noninclusive (format-range-value (.getStart r) timezone true)}]
values)
values)
values-before-after (if (and (.getAfter r) (> (.getAfter r) 0))
(concat values-before
[{:count (.getAfter r)
:value (format "[%s TO *]"
(format-range-value (.getEnd r) nil false))
:min-inclusive (format-range-value (.getEnd r) timezone false)
:max-noninclusive nil}])
values-before)]
{:name (.getName r)
:values (map #(dissoc % :orig-value) values-before-after)
:start (.getStart r)
:end (.getEnd r)
:gap (.getGap r)
:before (.getBefore r)
:after (.getAfter r)}))
(.getFacetRanges query-results))))
(defn extract-facet-queries
[facet-queries result]
(filter identity
(map (fn [query]
(let [formatted-query (if (string? query) query (format-facet-query query))
count (get result formatted-query)]
(when count
(if (string? query)
{:query query :count count}
(assoc query :count count)))))
facet-queries)))
(defn extract-pivots
[^QueryResponse query-results facet-date-ranges]
(let [^NamedList facet-pivot (.getFacetPivot query-results)]
(when facet-pivot
(into
{}
(map
(fn [index]
(let [facet1-name (.getName facet-pivot index)
^ArrayList pivot-fields (.getVal facet-pivot index)
ranges (into {}
(for [^PivotField pivot-field pivot-fields
:let [facet1-value (.getValue pivot-field)
facet-ranges (extract-facet-ranges pivot-field facet-date-ranges)]
:when (not-empty facet-ranges)]
[facet1-value
(into {}
(map (fn [range]
[(:name range) (:values range)])
facet-ranges))]))
pivot-counts (into {}
(for [^PivotField pivot-field pivot-fields]
(let [facet1-value (.getValue pivot-field)
^List pivot-values (.getPivot pivot-field)]
[facet1-value
(into {}
(map (fn [^PivotField pivot]
(if (.getFacetRanges pivot)
[(.getValue pivot)
{:count (.getCount pivot)
:ranges (extract-facet-ranges pivot facet-date-ranges)}]
[(.getValue pivot)
(.getCount pivot)]))
pivot-values))])))]
;;(println facet1-name)
[facet1-name (cond (and (not-empty ranges) (not-empty pivot-counts) (= (count ranges) (count pivot-counts)))
{:counts pivot-counts :ranges ranges}
(not-empty pivot-counts)
pivot-counts
(not-empty ranges)
ranges
:else nil)]))
(range 0 (.size facet-pivot)))))))
(defn show-query
[q flags]
(trace "Solr Query:")
(trace q)
(trace " Facet filters:")
(if (not-empty (:facet-filters flags))
(doseq [ff (:facet-filters flags)]
(trace (format " %s" (format-facet-query ff))))
(trace " none"))
(trace " Facet queries:")
(if (not-empty (:facet-queries flags))
(doseq [ff (:facet-queries flags)]
(trace (format " %s" (format-facet-query ff))))
(trace " none"))
(trace " Facet fields:")
(if (not-empty (:facet-fields flags))
(doseq [ff (:facet-fields flags)]
(trace (format " %s" (if (map? ff) (pr-str ff) ff))))
(trace " none"))
(let [other (dissoc flags :facet-filters :facet-qieries :facet-fields)]
(when (not-empty other)
(trace " Other parameters to Solr:")
(doseq [[k v] other]
(trace (format " %s: %s" k (pr-str v))))))
)
(def facet-exclude-parameters
#{:name :result-formatter})
(defn search*
"Query solr through solrj.
q: Query field
Optional keys, passed in a map:
:method :get or :post (default :get)
:rows Number of rows to return (default is Solr default: 1000)
:start Offset into query result at which to start returning rows (default 0)
:fields Fields to return
:facet-fields Discrete-valued fields to facet. Can be a string, keyword, or map containing
{:name ... :prefix ...}.
:facet-queries Vector of facet queries, each encoded in a string or a map of
{:name, :value, :formatter}. :formatter is optional and defaults to the raw query formatter.
The result is in the :facet-queries response.
:facet-date-ranges Date fields to facet as a vector or maps. Each map contains
:field Field name
:tag Optional, for referencing in a pivot facet
:start Earliest date (as java.util.Date)
:end Latest date (as java.util.Date)
:gap Faceting gap, as String, per Solr (+1HOUR, etc)
:others Comma-separated string: before,after,between,none,all. Optional.
:include Comma-separated string: lower,upper,edge,outer,all. Optional.
:hardend Boolean (See Solr doc). Optional.
:missing Boolean--return empty buckets if true. Optional.
:facet-numeric-ranges Numeric fields to facet, as a vector of maps. Map fields as for
date ranges, but start, end and gap must be numbers.
:facet-mincount Minimum number of docs in a facet for the bucket to be returned.
:facet-hier-sep Useful for path hierarchy token faceting. A regex, such as \\|.
:facet-filters Solr filter expression on facet values. Passed as a map in the form:
{:name 'facet-name' :value 'facet-value' :formatter (fn [name value] ...) }
where :formatter is optional and is used to format the query.
:facet-pivot-fields Vector of pivots to compute, each a list of facet fields.
If a facet is tagged (e.g., {:tag ts} in :facet-date-ranges)
then the string should be {!range=ts}other-facet. Otherwise,
use comma separated lists: this-facet,other-facet.
:cursor-mark true -- initial cursor; else a previous cursor value from
(:next-cursor-mark (meta result))
Additional keys can be passed, using Solr parameter names as keywords.
Returns the query results as the value of the call, with faceting results as metadata.
Use (meta result) to get facet data."
[q {:keys [method fields facet-fields facet-date-ranges facet-numeric-ranges facet-queries
facet-mincount facet-hier-sep facet-filters facet-pivot-fields cursor-mark] :as flags}]
(show-query q flags)
(let [query (cond (string? q) (SolrQuery. q)
(instance? SolrQuery q) q
:else (throw (Exception. "q parameter must be a string or SolrQuery")))
method (parse-method method)
facet-result-formatters (into {} (map #(if (map? %)
[(:name %) (:result-formatter % identity)]
[% identity])
facet-fields))
facet-key-fields (into {} (map-indexed (fn [i f]
[(format "f%d" i) (if (map? f) (:name f) (name f))])
facet-fields))
facet-field-keys (into {} (map-indexed (fn [i f]
[(if (map? f) (:name f) (name f)) (format "f%d" i)])
facet-fields))]
(doseq [[key value] (dissoc flags :method :facet-fields :facet-date-ranges :facet-numeric-ranges :facet-filters)]
(.setParam query (apply str (rest (str key))) (make-param value)))
(when (not (empty? fields))
(cond (string? fields)
(.setFields query (into-array (str/split fields #",")))
(or (seq? fields) (vector? fields))
(.setFields query (into-array
(map (fn [f]
(cond (string? f) f
(keyword? f) (name f)
:else (throw (Exception. (format "Unsupported field name: %s" f)))))
fields)))
:else (throw (Exception. (format "Unsupported :fields parameter format: %s" fields)))))
;; How to facet the same attribute different ways (using different prefixes)
;; https://stackoverflow.com/questions/31340400/multiple-facet-prefix-on-a-single-facet-field
;; http://192.168.0.200:8983/solr/i2ksearch/select?facet.field={!key=f1%20facet.prefix="prefix1"}attribute&facet.field={!key=f2%20facet.prefix="prefix 2"}attribute&facet.limit=300&facet.query=attribute:<<query>>&facet=on&fq=attribute:<<query>>&rows=0
(let [facet-field-parameters
(for [facet-field facet-fields
:let [field-name (if (map? facet-field)
(:name facet-field)
(name facet-field))
key (get facet-field-keys field-name)]]
(if (map? facet-field)
(let [local-params
(reduce-kv (fn [params k v]
(if (facet-exclude-parameters k)
params
(format "%s facet.%s=\"%s\"" params (name k) v)))
(format "!key=%s" key)
facet-field)]
(format "{%s}%s" local-params field-name))
(format "{!key=%s}%s" key field-name)))]
(when (not-empty facet-field-parameters)
(.addFacetField query (into-array String facet-field-parameters))))
(doseq [facet-query facet-queries]
(cond (string? facet-query)
(.addFacetQuery query facet-query)
(map? facet-query)
(let [formatted-query (format-facet-query facet-query)]
(when (not-empty formatted-query) (.addFacetQuery query formatted-query)))
:else (throw (Exception. "Invalid facet query. Must be a string or a map of {:name, :value, :formatter (optional)}"))))
(doseq [{:keys [field start end gap others include hardend missing mincount tag]} facet-date-ranges]
(if tag
;; This is a workaround for a Solrj bug that causes tagged queries to be improperly formatted.
(do (.setParam query "facet" true)
(.add query "facet.range" (into-array String [(format "{!tag=%s}%s" tag field)]))
(.add query (format "f.%s.facet.range.start" field)
(into-array String [(tformat/unparse (tformat/formatters :date-time-no-ms)
(tcoerce/from-date start))]))
(.add query (format "f.%s.facet.range.end" field)
(into-array String [(tformat/unparse (tformat/formatters :date-time-no-ms)
(tcoerce/from-date end))]))
(.add query (format "f.%s.facet.range.gap" field) (into-array String [gap])))
(.addDateRangeFacet query field start end gap))
(when missing (.setParam query (format "f.%s.facet.missing" field) true))
(when others (.setParam query (format "f.%s.facet.range.other" field) (into-array String others)))
(when include (.setParam query (format "f.%s.facet.range.include" field) (into-array String [include])))
(when hardend (.setParam query (format "f.%s.facet.range.hardend" field) hardend)))
(doseq [{:keys [field start end gap others include hardend missing mincount tag]} facet-numeric-ranges]
(assert (instance? Number start))
(assert (instance? Number end))
(assert (instance? Number gap))
(if tag
;; This is a workaround for a Solrj bug that causes tagged queries to be improperly formatted.
(do (.setParam query "facet" true)
(.add query "facet.range" (into-array String [(format "{!tag=%s}%s" tag field)]))
(.add query (format "f.%s.facet.range.start" field) (into-array String [(.toString start)]))
(.add query (format "f.%s.facet.range.end" field) (into-array String [(.toString end)]))
(.add query (format "f.%s.facet.range.gap" field) (into-array String [(.toString gap)])))
(.addNumericRangeFacet query field start end gap))
(when missing (.setParam query (format "f.%s.facet.missing" field) true))
(when others (.setParam query (format "f.%s.facet.range.other" field) (into-array String others)))
(when include (.setParam query (format "f.%s.facet.range.include" field) (into-array String [include])))
(when hardend (.setParam query (format "f.%s.facet.range.hardend" field) hardend)))
(doseq [field facet-pivot-fields]
(.addFacetPivotField query (into-array String [field])))
(.addFilterQuery query (into-array String (filter not-empty (map format-facet-query facet-filters))))
(.setFacetMinCount query (or facet-mincount 1))
(cond (= cursor-mark true)
(.setParam query ^String (CursorMarkParams/CURSOR_MARK_PARAM) (into-array String [(CursorMarkParams/CURSOR_MARK_START)]))
(not (nil? cursor-mark))
(.setParam query ^String (CursorMarkParams/CURSOR_MARK_PARAM) (into-array String [cursor-mark])))
(trace "Executing query")
(let [query-results (.query *connection* query method)
results (.getResults query-results)]
(trace "Query complete")
(when (:debugQuery flags)
(trace (.getDebugMap query-results)))
(with-meta (map doc-to-hash results)
(merge
(when cursor-mark
(let [next (.getNextCursorMark query-results)]
{:next-cursor-mark next
:cursor-done (.equals next (if (= cursor-mark true)
(CursorMarkParams/CURSOR_MARK_START)
cursor-mark))}))
(when (:debugQuery flags)
{:debug (.getDebugMap query-results)})
(when (.getFieldStatsInfo query-results)
{:statistics
(into {}
(for [[field info] (.getFieldStatsInfo query-results)]
[field {:min (.getMin info)
:max (.getMax info)
:mean (.getMean info)
:stddev (.getStddev info)
:sum (.getSum info)
:count (.getCount info)
:missing (.getMissing info)
}]))})
{:start (.getStart results)
:rows-set (count results)
:rows-total (.getNumFound results)
:highlighting (.getHighlighting query-results)
:facet-fields (extract-facets query-results facet-hier-sep false facet-result-formatters facet-key-fields)
:facet-range-fields (extract-facet-ranges query-results facet-date-ranges)
:limiting-facet-fields (extract-facets query-results facet-hier-sep true facet-result-formatters facet-key-fields)
:facet-queries (extract-facet-queries facet-queries (.getFacetQuery query-results))
:facet-pivot-fields (extract-pivots query-results facet-date-ranges)
:results-obj results
:query-results-obj query-results})))))
(defn search
"Query solr through solrj.
q: Query field
Optional keys:
:method :get or :post (default :get)
:rows Number of rows to return (default is Solr default: 1000)
:start Offset into query result at which to start returning rows (default 0)
:fields Fields to return
:facet-fields Discrete-valued fields to facet. Can be a string, keyword, or map containing
{:name ... :prefix ...}.
:facet-queries Vector of facet queries, each encoded in a string or a map of
{:name, :value, :formatter}. :formatter is optional and defaults to the raw query formatter.
The result is in the :facet-queries response.
:facet-date-ranges Date fields to facet as a vector or maps. Each map contains
:field Field name
:tag Optional, for referencing in a pivot facet
:start Earliest date (as java.util.Date)
:end Latest date (as java.util.Date)
:gap Faceting gap, as String, per Solr (+1HOUR, etc)
:others Comma-separated string: before,after,between,none,all. Optional.
:include Comma-separated string: lower,upper,edge,outer,all. Optional.
:hardend Boolean (See Solr doc). Optional.
:missing Boolean--return empty buckets if true. Optional.
:facet-numeric-ranges Numeric fields to facet, as a vector of maps. Map fields as for
date ranges, but start, end and gap must be numbers.
:facet-mincount Minimum number of docs in a facet for the bucket to be returned.
:facet-hier-sep Useful for path hierarchy token faceting. A regex, such as \\|.
:facet-filters Solr filter expression on facet values. Passed as a map in the form:
{:name 'facet-name' :value 'facet-value' :formatter (fn [name value] ...) }
where :formatter is optional and is used to format the query.
:facet-pivot-fields Vector of pivots to compute, each a list of facet fields.
If a facet is tagged (e.g., {:tag ts} in :facet-date-ranges)
then the string should be {!range=ts}other-facet. Otherwise,
use comma separated lists: this-facet,other-facet.
:cursor-mark true -- initial cursor; else a previous cursor value from
(:next-cursor-mark (meta result))
Returns the query results as the value of the call, with faceting results as metadata.
Use (meta result) to get facet data."
[q & {:keys [method fields facet-fields facet-date-ranges facet-numeric-ranges facet-queries
facet-mincount facet-hier-sep facet-filters facet-pivot-fields] :as flags}]
(search* q flags))
(defn atomically-update!
"Atomically update a solr document:
doc: document fetched from solr previously, or the id of such a document (must not be a map)
unique-key: Name of the attribute that is the document's unique key
changes: Vector of maps containing :attribute, :func [one of :set, :inc, :add], and :value.
e.g.
(atomically-update! doc \"cdid\" [{:attribute :client :func :set :value \"darcy\"}])"
[doc unique-key-field changes]
(let [document (SolrInputDocument.)]
(.addField document (name unique-key-field) (if (map? doc) (get doc unique-key-field) doc))
(doseq [{:keys [attribute func value]} changes]
(.addField document (name attribute) (doto (HashMap. 1) (.put (name func) value))))
(.add *connection* document)))
(defn similar [doc similar-count & {:keys [method]}]
(let [query (SolrQuery. (format "id:%d" (:id doc)))
method (parse-method method)]
(.setParam query "mlt" (make-param true))
(.setParam query "mlt.fl" (make-param "fulltext"))
(.setParam query "mlt.count" (make-param similar-count))
(let [query-results (.query *connection* query method)]
(map doc-to-hash (.get (.get (.getResponse query-results) "moreLikeThis") (str (:id doc)))))))
(defn more-like-this
"Execute a Solr moreLikeThis (mlt) query.
id: unique id of doc to match.
unique-key: Name of key in schema that corresponds to id.
similarity-fields: Fields to match against. Pass as comma-separated list or vector.
params: Map of optional parameters:
match-include? -- this is not clearly documented. See Solr manual.
min-doc-freq -- ignore words that don't occur in at least this many docs. Default 3.
min-term-freq -- ignore terms that occur fewer times than this in a document. Default 2.
min-word-len -- minimum word length for matching. Default 5.
boost? -- Specifies if query will be boosted by interesting term relevance. Default true.
max-query-terms -- Maximum number of query terms in a search. Default 1000.
max-results -- Maximum number of similar docs returned. Default 5.
fields -- fields of docs to return. Pass as vector or comma-separated list.. Default: unique key + score.
method -- Solr Query method.
Other key/value pairs can be passed in params and are passed onto search*, so can be used
for filtering."
[id unique-key similarity-fields
{:keys [match-include?
min-doc-freq
min-term-freq
min-word-len
boost?
max-query-terms
max-results
fields
method]
:or {match-include? false
min-doc-freq (int 3)
min-term-freq (int 2)
min-word-len (int 5)
boost? true
max-results (int 5)
fields "score"
max-query-terms (int 1000)}
:as params}]
(let [query (doto (SolrQuery.)
(.setRequestHandler (str "/" MoreLikeThisParams/MLT))
(.set MoreLikeThisParams/MATCH_INCLUDE (make-param match-include?))
(.set MoreLikeThisParams/MIN_DOC_FREQ (make-param min-doc-freq))
(.set MoreLikeThisParams/MIN_TERM_FREQ (make-param min-term-freq))
(.set MoreLikeThisParams/MIN_WORD_LEN (make-param min-word-len))
(.set MoreLikeThisParams/BOOST (make-param boost?))
(.set MoreLikeThisParams/MAX_QUERY_TERMS (make-param max-query-terms))
(.set MoreLikeThisParams/SIMILARITY_FIELDS (make-param (if (string? similarity-fields)
similarity-fields
(str/join "," similarity-fields))))
(.setQuery (format "%s:\"%s\"" (name unique-key) (str id)))
(.set "fl" (make-param (format "%s,%s" (name unique-key)
(if (string? fields)
fields
(str/join "," fields)))))
(.setRows max-results))
query-results (search* query
(dissoc params
:match-include?
:min-doc-freq
:min-term-freq
:min-word-len
:boost?
:fields
:max-query-terms
:max-results
:method))]
(map doc-to-hash (:results-obj (meta query-results)))))
(defn delete-id! [id]
(.deleteById *connection* id))
(defn delete-query! [q]
(.deleteByQuery *connection* q))
(defn data-import [type]
(let [type (cond (= type :full) "full-import"
(= type :delta) "delta-import")
params (doto (ModifiableSolrParams.)
(.set "qt" (make-param "/dataimport"))
(.set "command" (make-param type)))]
(.query *connection* params)))
(defmacro with-connection [conn & body]
`(binding [*connection* ~conn]
(try
(do ~@body)
(finally (.close *connection*)))))
|
79835
|
(ns clojure-solr
(:require [clojure.string :as str]
[clojure.pprint :as pprint])
(:require [clj-time.core :as t])
(:require [clj-time.format :as tformat])
(:require [clj-time.coerce :as tcoerce])
(:import (java.net URI)
(java.util Base64 HashMap List ArrayList)
(java.nio.charset Charset)
(org.apache.http HttpRequest HttpRequestInterceptor HttpHeaders)
(org.apache.http.auth AuthScope UsernamePasswordCredentials)
(org.apache.http.client.protocol HttpClientContext)
(org.apache.http.impl.auth BasicScheme)
(org.apache.http.impl.client BasicCredentialsProvider HttpClientBuilder)
(org.apache.http.protocol HttpContext HttpCoreContext)
(org.apache.solr.client.solrj SolrQuery SolrRequest$METHOD)
(org.apache.solr.client.solrj.impl HttpSolrClient HttpClientUtil)
(org.apache.solr.client.solrj.embedded EmbeddedSolrServer)
(org.apache.solr.client.solrj.response QueryResponse FacetField PivotField RangeFacet RangeFacet$Count RangeFacet$Date)
(org.apache.solr.common SolrInputDocument)
(org.apache.solr.common.params ModifiableSolrParams CursorMarkParams MoreLikeThisParams)
(org.apache.solr.common.util NamedList)
(org.apache.solr.util DateMathParser)))
(def ^:private url-details (atom {}))
(def ^:private credentials-provider (BasicCredentialsProvider.))
(def ^:private credentials (atom {}))
(declare ^:dynamic *connection*)
(def ^:dynamic *trace-fn* nil)
(declare make-param)
(defn trace
[str]
(when *trace-fn*
(*trace-fn* str)))
(defmacro with-trace
[fn & body]
`(binding [*trace-fn* ~fn]
~@body))
(defn make-basic-credentials
[name password]
(UsernamePasswordCredentials. name password))
(defn make-auth-scope
[host port]
(AuthScope. host port))
(defn set-credentials
[uri name password]
(.setCredentials credentials-provider
(make-auth-scope (.getHost uri) (.getPort uri))
(make-basic-credentials name password)))
(defn get-url-details
[url]
(let [details (get @url-details url)]
(if details
details
(let [[_ scheme name password rest] (re-matches #"(https?)://(.+):(.+)@(.*)" url)
details (if (and scheme name password rest)
{:clean-url (str scheme "://" rest)
:password password
:name name}
{:clean-url url})
uri (URI. (:clean-url details))]
(swap! url-details assoc url details)
(when (and name password)
(let [host (if (= (.getPort uri) -1)
(str (.getScheme uri) "://" (.getHost uri))
(str (.getScheme uri) "://" (.getHost uri) ":" (.getPort uri)))]
;;(println "**** CLOJURE-SOLR: Adding credentials for host" host)
(set-credentials uri name password)
(swap! credentials assoc host {:name name :password <PASSWORD>})))
details))))
(defn connect [url & conn-manager]
(let [params (ModifiableSolrParams.)
{:keys [clean-url name password]} (get-url-details url)
builder (doto (HttpClientBuilder/create)
(.setDefaultCredentialsProvider credentials-provider)
(.setConnectionManager (when conn-manager (first conn-manager)))
(.addInterceptorFirst
(reify
HttpRequestInterceptor
(^void process [this ^HttpRequest request ^HttpContext context]
(let [auth-state (.getAttribute context HttpClientContext/TARGET_AUTH_STATE)]
(when (nil? (.getAuthScheme auth-state))
(let [target-host (.getAttribute context HttpCoreContext/HTTP_TARGET_HOST)
auth-scope (make-auth-scope (.getHostName target-host) (.getPort target-host))
creds (.getCredentials credentials-provider auth-scope)]
;;(println "**** CLOJURE-SOLR: HttpRequestInterceptor here. Looking for" auth-scope)
(when creds
(.update auth-state (BasicScheme.) creds)))))))))
client (.build builder)]
(HttpSolrClient. clean-url client)))
(defn- make-document [boost-map doc]
(let [sdoc (SolrInputDocument.)]
(doseq [[key value] doc]
(let [key-string (name key)
boost (get boost-map key)]
(if boost
(.addField sdoc key-string value boost)
(.addField sdoc key-string value))))
sdoc))
(defn add-document!
([doc boost-map]
(.add *connection* (make-document boost-map doc)))
([doc]
(add-document! doc {})))
(defn add-documents!
([coll boost-map]
(.add *connection* (map (partial make-document boost-map) coll)))
([coll]
(add-documents! coll {})))
(defn commit! []
(.commit *connection*))
(defn- doc-to-hash [doc]
(into {} (for [[k v] (clojure.lang.PersistentArrayMap/create doc)]
[(keyword k)
(cond (= java.util.ArrayList (type v)) (into [] v)
:else v)])))
(defn- make-param [p]
(cond
(string? p) (into-array String [p])
(coll? p) (into-array String (map str p))
:else (into-array String [(str p)])))
(def http-methods {:get SolrRequest$METHOD/GET, :GET SolrRequest$METHOD/GET
:post SolrRequest$METHOD/POST, :POST SolrRequest$METHOD/POST})
(defn- parse-method [method]
(get http-methods method SolrRequest$METHOD/GET))
(defn extract-facets
[query-results facet-hier-sep limiting? formatters key-fields]
(map (fn [^FacetField f]
(let [field-name (.getName f)
facet-name (get key-fields field-name field-name)]
{:name facet-name
:values (sort-by :path
(map (fn [v]
(let [result
(merge
{:value (.getName v)
:count (.getCount v)}
(when-let [split-path (and facet-hier-sep (str/split (.getName v) facet-hier-sep))]
{:split-path split-path
:title (last split-path)
:depth (count split-path)}))]
((get formatters facet-name identity) result)))
(.getValues f)))}))
^List (if limiting?
(.getLimitingFacets query-results)
(.getFacetFields query-results))))
(def date-time-formatter
(tformat/formatters :date-time-no-ms))
(def query-result-date-time-parser
(tformat/formatter t/utc "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'" "YYYY-MM-dd'T'HH:mm:ss'Z'"))
(defn format-range-value
"Timezone is only used if it's a date facet (and timezone is not null)."
[val timezone end?]
(let [d (try (tformat/parse date-time-formatter val)
(catch Exception _))]
(cond (or d (instance? java.util.Date val))
(let [d (or d (tcoerce/from-date val))]
(tformat/unparse (if timezone (tformat/with-zone date-time-formatter timezone) date-time-formatter)
(if end? (t/minus d (t/seconds 1)) d)))
:else (str val))))
(defn format-standard-filter-query
[name value]
(format "%s:%s" name value))
(defn format-raw-query
[name value]
(format "{!raw f=%s}%s" name value))
(defn format-facet-query
[{:keys [name value formatter]}]
(if (and (string? value) (re-find #"\[" value)) ;; range filter
(format-standard-filter-query name value)
(if formatter
(formatter name value)
(format-raw-query name value))))
(defn extract-facet-ranges
"Explicitly pass facet-date-ranges in case one or more ranges are date ranges, and we need to grab a timezone."
[query-results facet-date-ranges]
(sort-by :name
(map (fn [^RangeFacet r]
(let [date-range? (some (fn [{:keys [field]}] (= field (.getName r)))
facet-date-ranges)
timezone (:timezone (first (filter (fn [{:keys [field]}] (= field (.getName r)))
facet-date-ranges)))
gap (.getGap r)
values
(map (fn [val]
(let [start-val (.getValue val)
start-str (format-range-value start-val nil false)
end-val (cond date-range?
(.parseMath (doto (DateMathParser.)
(.setNow
(tcoerce/to-date
(tformat/parse query-result-date-time-parser start-val))))
gap)
(re-matches #"\d+" start-val)
(+ (Integer/parseInt start-val) gap)
:else (+ (Double/parseDouble start-val) gap))
end-str (format-range-value end-val nil true)]
{:count (.getCount val)
:value (format (if date-range? "[%s TO %s]" "[%s TO %s}") start-str end-str)
:min-inclusive start-str
:max-noninclusive end-str}))
(.getCounts r))
values-before (if (and (.getBefore r) (> (.getBefore r) 0))
(concat [{:count (.getBefore r)
:value (format (if date-range? "[* TO %s]" "[* TO %s}")
(format-range-value (.getStart r) nil true))
:min-inclusive nil
:max-noninclusive (format-range-value (.getStart r) timezone true)}]
values)
values)
values-before-after (if (and (.getAfter r) (> (.getAfter r) 0))
(concat values-before
[{:count (.getAfter r)
:value (format "[%s TO *]"
(format-range-value (.getEnd r) nil false))
:min-inclusive (format-range-value (.getEnd r) timezone false)
:max-noninclusive nil}])
values-before)]
{:name (.getName r)
:values (map #(dissoc % :orig-value) values-before-after)
:start (.getStart r)
:end (.getEnd r)
:gap (.getGap r)
:before (.getBefore r)
:after (.getAfter r)}))
(.getFacetRanges query-results))))
(defn extract-facet-queries
[facet-queries result]
(filter identity
(map (fn [query]
(let [formatted-query (if (string? query) query (format-facet-query query))
count (get result formatted-query)]
(when count
(if (string? query)
{:query query :count count}
(assoc query :count count)))))
facet-queries)))
(defn extract-pivots
[^QueryResponse query-results facet-date-ranges]
(let [^NamedList facet-pivot (.getFacetPivot query-results)]
(when facet-pivot
(into
{}
(map
(fn [index]
(let [facet1-name (.getName facet-pivot index)
^ArrayList pivot-fields (.getVal facet-pivot index)
ranges (into {}
(for [^PivotField pivot-field pivot-fields
:let [facet1-value (.getValue pivot-field)
facet-ranges (extract-facet-ranges pivot-field facet-date-ranges)]
:when (not-empty facet-ranges)]
[facet1-value
(into {}
(map (fn [range]
[(:name range) (:values range)])
facet-ranges))]))
pivot-counts (into {}
(for [^PivotField pivot-field pivot-fields]
(let [facet1-value (.getValue pivot-field)
^List pivot-values (.getPivot pivot-field)]
[facet1-value
(into {}
(map (fn [^PivotField pivot]
(if (.getFacetRanges pivot)
[(.getValue pivot)
{:count (.getCount pivot)
:ranges (extract-facet-ranges pivot facet-date-ranges)}]
[(.getValue pivot)
(.getCount pivot)]))
pivot-values))])))]
;;(println facet1-name)
[facet1-name (cond (and (not-empty ranges) (not-empty pivot-counts) (= (count ranges) (count pivot-counts)))
{:counts pivot-counts :ranges ranges}
(not-empty pivot-counts)
pivot-counts
(not-empty ranges)
ranges
:else nil)]))
(range 0 (.size facet-pivot)))))))
(defn show-query
[q flags]
(trace "Solr Query:")
(trace q)
(trace " Facet filters:")
(if (not-empty (:facet-filters flags))
(doseq [ff (:facet-filters flags)]
(trace (format " %s" (format-facet-query ff))))
(trace " none"))
(trace " Facet queries:")
(if (not-empty (:facet-queries flags))
(doseq [ff (:facet-queries flags)]
(trace (format " %s" (format-facet-query ff))))
(trace " none"))
(trace " Facet fields:")
(if (not-empty (:facet-fields flags))
(doseq [ff (:facet-fields flags)]
(trace (format " %s" (if (map? ff) (pr-str ff) ff))))
(trace " none"))
(let [other (dissoc flags :facet-filters :facet-qieries :facet-fields)]
(when (not-empty other)
(trace " Other parameters to Solr:")
(doseq [[k v] other]
(trace (format " %s: %s" k (pr-str v))))))
)
(def facet-exclude-parameters
#{:name :result-formatter})
(defn search*
"Query solr through solrj.
q: Query field
Optional keys, passed in a map:
:method :get or :post (default :get)
:rows Number of rows to return (default is Solr default: 1000)
:start Offset into query result at which to start returning rows (default 0)
:fields Fields to return
:facet-fields Discrete-valued fields to facet. Can be a string, keyword, or map containing
{:name ... :prefix ...}.
:facet-queries Vector of facet queries, each encoded in a string or a map of
{:name, :value, :formatter}. :formatter is optional and defaults to the raw query formatter.
The result is in the :facet-queries response.
:facet-date-ranges Date fields to facet as a vector or maps. Each map contains
:field Field name
:tag Optional, for referencing in a pivot facet
:start Earliest date (as java.util.Date)
:end Latest date (as java.util.Date)
:gap Faceting gap, as String, per Solr (+1HOUR, etc)
:others Comma-separated string: before,after,between,none,all. Optional.
:include Comma-separated string: lower,upper,edge,outer,all. Optional.
:hardend Boolean (See Solr doc). Optional.
:missing Boolean--return empty buckets if true. Optional.
:facet-numeric-ranges Numeric fields to facet, as a vector of maps. Map fields as for
date ranges, but start, end and gap must be numbers.
:facet-mincount Minimum number of docs in a facet for the bucket to be returned.
:facet-hier-sep Useful for path hierarchy token faceting. A regex, such as \\|.
:facet-filters Solr filter expression on facet values. Passed as a map in the form:
{:name 'facet-name' :value 'facet-value' :formatter (fn [name value] ...) }
where :formatter is optional and is used to format the query.
:facet-pivot-fields Vector of pivots to compute, each a list of facet fields.
If a facet is tagged (e.g., {:tag ts} in :facet-date-ranges)
then the string should be {!range=ts}other-facet. Otherwise,
use comma separated lists: this-facet,other-facet.
:cursor-mark true -- initial cursor; else a previous cursor value from
(:next-cursor-mark (meta result))
Additional keys can be passed, using Solr parameter names as keywords.
Returns the query results as the value of the call, with faceting results as metadata.
Use (meta result) to get facet data."
[q {:keys [method fields facet-fields facet-date-ranges facet-numeric-ranges facet-queries
facet-mincount facet-hier-sep facet-filters facet-pivot-fields cursor-mark] :as flags}]
(show-query q flags)
(let [query (cond (string? q) (SolrQuery. q)
(instance? SolrQuery q) q
:else (throw (Exception. "q parameter must be a string or SolrQuery")))
method (parse-method method)
facet-result-formatters (into {} (map #(if (map? %)
[(:name %) (:result-formatter % identity)]
[% identity])
facet-fields))
facet-key-fields (into {} (map-indexed (fn [i f]
[(format "f%d" i) (if (map? f) (:name f) (name f))])
facet-fields))
facet-field-keys (into {} (map-indexed (fn [i f]
[(if (map? f) (:name f) (name f)) (format "f%d" i)])
facet-fields))]
(doseq [[key value] (dissoc flags :method :facet-fields :facet-date-ranges :facet-numeric-ranges :facet-filters)]
(.setParam query (apply str (rest (str key))) (make-param value)))
(when (not (empty? fields))
(cond (string? fields)
(.setFields query (into-array (str/split fields #",")))
(or (seq? fields) (vector? fields))
(.setFields query (into-array
(map (fn [f]
(cond (string? f) f
(keyword? f) (name f)
:else (throw (Exception. (format "Unsupported field name: %s" f)))))
fields)))
:else (throw (Exception. (format "Unsupported :fields parameter format: %s" fields)))))
;; How to facet the same attribute different ways (using different prefixes)
;; https://stackoverflow.com/questions/31340400/multiple-facet-prefix-on-a-single-facet-field
;; http://192.168.0.200:8983/solr/i2ksearch/select?facet.field={!key=f1%20facet.prefix="prefix1"}attribute&facet.field={!key=f2%20facet.prefix="prefix 2"}attribute&facet.limit=300&facet.query=attribute:<<query>>&facet=on&fq=attribute:<<query>>&rows=0
(let [facet-field-parameters
(for [facet-field facet-fields
:let [field-name (if (map? facet-field)
(:name facet-field)
(name facet-field))
key (get facet-field-keys field-name)]]
(if (map? facet-field)
(let [local-params
(reduce-kv (fn [params k v]
(if (facet-exclude-parameters k)
params
(format "%s facet.%s=\"%s\"" params (name k) v)))
(format "!key=%s" key)
facet-field)]
(format "{%s}%s" local-params field-name))
(format "{!key=%s}%s" key field-name)))]
(when (not-empty facet-field-parameters)
(.addFacetField query (into-array String facet-field-parameters))))
(doseq [facet-query facet-queries]
(cond (string? facet-query)
(.addFacetQuery query facet-query)
(map? facet-query)
(let [formatted-query (format-facet-query facet-query)]
(when (not-empty formatted-query) (.addFacetQuery query formatted-query)))
:else (throw (Exception. "Invalid facet query. Must be a string or a map of {:name, :value, :formatter (optional)}"))))
(doseq [{:keys [field start end gap others include hardend missing mincount tag]} facet-date-ranges]
(if tag
;; This is a workaround for a Solrj bug that causes tagged queries to be improperly formatted.
(do (.setParam query "facet" true)
(.add query "facet.range" (into-array String [(format "{!tag=%s}%s" tag field)]))
(.add query (format "f.%s.facet.range.start" field)
(into-array String [(tformat/unparse (tformat/formatters :date-time-no-ms)
(tcoerce/from-date start))]))
(.add query (format "f.%s.facet.range.end" field)
(into-array String [(tformat/unparse (tformat/formatters :date-time-no-ms)
(tcoerce/from-date end))]))
(.add query (format "f.%s.facet.range.gap" field) (into-array String [gap])))
(.addDateRangeFacet query field start end gap))
(when missing (.setParam query (format "f.%s.facet.missing" field) true))
(when others (.setParam query (format "f.%s.facet.range.other" field) (into-array String others)))
(when include (.setParam query (format "f.%s.facet.range.include" field) (into-array String [include])))
(when hardend (.setParam query (format "f.%s.facet.range.hardend" field) hardend)))
(doseq [{:keys [field start end gap others include hardend missing mincount tag]} facet-numeric-ranges]
(assert (instance? Number start))
(assert (instance? Number end))
(assert (instance? Number gap))
(if tag
;; This is a workaround for a Solrj bug that causes tagged queries to be improperly formatted.
(do (.setParam query "facet" true)
(.add query "facet.range" (into-array String [(format "{!tag=%s}%s" tag field)]))
(.add query (format "f.%s.facet.range.start" field) (into-array String [(.toString start)]))
(.add query (format "f.%s.facet.range.end" field) (into-array String [(.toString end)]))
(.add query (format "f.%s.facet.range.gap" field) (into-array String [(.toString gap)])))
(.addNumericRangeFacet query field start end gap))
(when missing (.setParam query (format "f.%s.facet.missing" field) true))
(when others (.setParam query (format "f.%s.facet.range.other" field) (into-array String others)))
(when include (.setParam query (format "f.%s.facet.range.include" field) (into-array String [include])))
(when hardend (.setParam query (format "f.%s.facet.range.hardend" field) hardend)))
(doseq [field facet-pivot-fields]
(.addFacetPivotField query (into-array String [field])))
(.addFilterQuery query (into-array String (filter not-empty (map format-facet-query facet-filters))))
(.setFacetMinCount query (or facet-mincount 1))
(cond (= cursor-mark true)
(.setParam query ^String (CursorMarkParams/CURSOR_MARK_PARAM) (into-array String [(CursorMarkParams/CURSOR_MARK_START)]))
(not (nil? cursor-mark))
(.setParam query ^String (CursorMarkParams/CURSOR_MARK_PARAM) (into-array String [cursor-mark])))
(trace "Executing query")
(let [query-results (.query *connection* query method)
results (.getResults query-results)]
(trace "Query complete")
(when (:debugQuery flags)
(trace (.getDebugMap query-results)))
(with-meta (map doc-to-hash results)
(merge
(when cursor-mark
(let [next (.getNextCursorMark query-results)]
{:next-cursor-mark next
:cursor-done (.equals next (if (= cursor-mark true)
(CursorMarkParams/CURSOR_MARK_START)
cursor-mark))}))
(when (:debugQuery flags)
{:debug (.getDebugMap query-results)})
(when (.getFieldStatsInfo query-results)
{:statistics
(into {}
(for [[field info] (.getFieldStatsInfo query-results)]
[field {:min (.getMin info)
:max (.getMax info)
:mean (.getMean info)
:stddev (.getStddev info)
:sum (.getSum info)
:count (.getCount info)
:missing (.getMissing info)
}]))})
{:start (.getStart results)
:rows-set (count results)
:rows-total (.getNumFound results)
:highlighting (.getHighlighting query-results)
:facet-fields (extract-facets query-results facet-hier-sep false facet-result-formatters facet-key-fields)
:facet-range-fields (extract-facet-ranges query-results facet-date-ranges)
:limiting-facet-fields (extract-facets query-results facet-hier-sep true facet-result-formatters facet-key-fields)
:facet-queries (extract-facet-queries facet-queries (.getFacetQuery query-results))
:facet-pivot-fields (extract-pivots query-results facet-date-ranges)
:results-obj results
:query-results-obj query-results})))))
(defn search
"Query solr through solrj.
q: Query field
Optional keys:
:method :get or :post (default :get)
:rows Number of rows to return (default is Solr default: 1000)
:start Offset into query result at which to start returning rows (default 0)
:fields Fields to return
:facet-fields Discrete-valued fields to facet. Can be a string, keyword, or map containing
{:name ... :prefix ...}.
:facet-queries Vector of facet queries, each encoded in a string or a map of
{:name, :value, :formatter}. :formatter is optional and defaults to the raw query formatter.
The result is in the :facet-queries response.
:facet-date-ranges Date fields to facet as a vector or maps. Each map contains
:field Field name
:tag Optional, for referencing in a pivot facet
:start Earliest date (as java.util.Date)
:end Latest date (as java.util.Date)
:gap Faceting gap, as String, per Solr (+1HOUR, etc)
:others Comma-separated string: before,after,between,none,all. Optional.
:include Comma-separated string: lower,upper,edge,outer,all. Optional.
:hardend Boolean (See Solr doc). Optional.
:missing Boolean--return empty buckets if true. Optional.
:facet-numeric-ranges Numeric fields to facet, as a vector of maps. Map fields as for
date ranges, but start, end and gap must be numbers.
:facet-mincount Minimum number of docs in a facet for the bucket to be returned.
:facet-hier-sep Useful for path hierarchy token faceting. A regex, such as \\|.
:facet-filters Solr filter expression on facet values. Passed as a map in the form:
{:name 'facet-name' :value 'facet-value' :formatter (fn [name value] ...) }
where :formatter is optional and is used to format the query.
:facet-pivot-fields Vector of pivots to compute, each a list of facet fields.
If a facet is tagged (e.g., {:tag ts} in :facet-date-ranges)
then the string should be {!range=ts}other-facet. Otherwise,
use comma separated lists: this-facet,other-facet.
:cursor-mark true -- initial cursor; else a previous cursor value from
(:next-cursor-mark (meta result))
Returns the query results as the value of the call, with faceting results as metadata.
Use (meta result) to get facet data."
[q & {:keys [method fields facet-fields facet-date-ranges facet-numeric-ranges facet-queries
facet-mincount facet-hier-sep facet-filters facet-pivot-fields] :as flags}]
(search* q flags))
(defn atomically-update!
"Atomically update a solr document:
doc: document fetched from solr previously, or the id of such a document (must not be a map)
unique-key: Name of the attribute that is the document's unique key
changes: Vector of maps containing :attribute, :func [one of :set, :inc, :add], and :value.
e.g.
(atomically-update! doc \"cdid\" [{:attribute :client :func :set :value \"darcy\"}])"
[doc unique-key-field changes]
(let [document (SolrInputDocument.)]
(.addField document (name unique-key-field) (if (map? doc) (get doc unique-key-field) doc))
(doseq [{:keys [attribute func value]} changes]
(.addField document (name attribute) (doto (HashMap. 1) (.put (name func) value))))
(.add *connection* document)))
(defn similar [doc similar-count & {:keys [method]}]
(let [query (SolrQuery. (format "id:%d" (:id doc)))
method (parse-method method)]
(.setParam query "mlt" (make-param true))
(.setParam query "mlt.fl" (make-param "fulltext"))
(.setParam query "mlt.count" (make-param similar-count))
(let [query-results (.query *connection* query method)]
(map doc-to-hash (.get (.get (.getResponse query-results) "moreLikeThis") (str (:id doc)))))))
(defn more-like-this
"Execute a Solr moreLikeThis (mlt) query.
id: unique id of doc to match.
unique-key: Name of key in schema that corresponds to id.
similarity-fields: Fields to match against. Pass as comma-separated list or vector.
params: Map of optional parameters:
match-include? -- this is not clearly documented. See Solr manual.
min-doc-freq -- ignore words that don't occur in at least this many docs. Default 3.
min-term-freq -- ignore terms that occur fewer times than this in a document. Default 2.
min-word-len -- minimum word length for matching. Default 5.
boost? -- Specifies if query will be boosted by interesting term relevance. Default true.
max-query-terms -- Maximum number of query terms in a search. Default 1000.
max-results -- Maximum number of similar docs returned. Default 5.
fields -- fields of docs to return. Pass as vector or comma-separated list.. Default: unique key + score.
method -- Solr Query method.
Other key/value pairs can be passed in params and are passed onto search*, so can be used
for filtering."
[id unique-key similarity-fields
{:keys [match-include?
min-doc-freq
min-term-freq
min-word-len
boost?
max-query-terms
max-results
fields
method]
:or {match-include? false
min-doc-freq (int 3)
min-term-freq (int 2)
min-word-len (int 5)
boost? true
max-results (int 5)
fields "score"
max-query-terms (int 1000)}
:as params}]
(let [query (doto (SolrQuery.)
(.setRequestHandler (str "/" MoreLikeThisParams/MLT))
(.set MoreLikeThisParams/MATCH_INCLUDE (make-param match-include?))
(.set MoreLikeThisParams/MIN_DOC_FREQ (make-param min-doc-freq))
(.set MoreLikeThisParams/MIN_TERM_FREQ (make-param min-term-freq))
(.set MoreLikeThisParams/MIN_WORD_LEN (make-param min-word-len))
(.set MoreLikeThisParams/BOOST (make-param boost?))
(.set MoreLikeThisParams/MAX_QUERY_TERMS (make-param max-query-terms))
(.set MoreLikeThisParams/SIMILARITY_FIELDS (make-param (if (string? similarity-fields)
similarity-fields
(str/join "," similarity-fields))))
(.setQuery (format "%s:\"%s\"" (name unique-key) (str id)))
(.set "fl" (make-param (format "%s,%s" (name unique-key)
(if (string? fields)
fields
(str/join "," fields)))))
(.setRows max-results))
query-results (search* query
(dissoc params
:match-include?
:min-doc-freq
:min-term-freq
:min-word-len
:boost?
:fields
:max-query-terms
:max-results
:method))]
(map doc-to-hash (:results-obj (meta query-results)))))
(defn delete-id! [id]
(.deleteById *connection* id))
(defn delete-query! [q]
(.deleteByQuery *connection* q))
(defn data-import [type]
(let [type (cond (= type :full) "full-import"
(= type :delta) "delta-import")
params (doto (ModifiableSolrParams.)
(.set "qt" (make-param "/dataimport"))
(.set "command" (make-param type)))]
(.query *connection* params)))
(defmacro with-connection [conn & body]
`(binding [*connection* ~conn]
(try
(do ~@body)
(finally (.close *connection*)))))
| true |
(ns clojure-solr
(:require [clojure.string :as str]
[clojure.pprint :as pprint])
(:require [clj-time.core :as t])
(:require [clj-time.format :as tformat])
(:require [clj-time.coerce :as tcoerce])
(:import (java.net URI)
(java.util Base64 HashMap List ArrayList)
(java.nio.charset Charset)
(org.apache.http HttpRequest HttpRequestInterceptor HttpHeaders)
(org.apache.http.auth AuthScope UsernamePasswordCredentials)
(org.apache.http.client.protocol HttpClientContext)
(org.apache.http.impl.auth BasicScheme)
(org.apache.http.impl.client BasicCredentialsProvider HttpClientBuilder)
(org.apache.http.protocol HttpContext HttpCoreContext)
(org.apache.solr.client.solrj SolrQuery SolrRequest$METHOD)
(org.apache.solr.client.solrj.impl HttpSolrClient HttpClientUtil)
(org.apache.solr.client.solrj.embedded EmbeddedSolrServer)
(org.apache.solr.client.solrj.response QueryResponse FacetField PivotField RangeFacet RangeFacet$Count RangeFacet$Date)
(org.apache.solr.common SolrInputDocument)
(org.apache.solr.common.params ModifiableSolrParams CursorMarkParams MoreLikeThisParams)
(org.apache.solr.common.util NamedList)
(org.apache.solr.util DateMathParser)))
(def ^:private url-details (atom {}))
(def ^:private credentials-provider (BasicCredentialsProvider.))
(def ^:private credentials (atom {}))
(declare ^:dynamic *connection*)
(def ^:dynamic *trace-fn* nil)
(declare make-param)
(defn trace
[str]
(when *trace-fn*
(*trace-fn* str)))
(defmacro with-trace
[fn & body]
`(binding [*trace-fn* ~fn]
~@body))
(defn make-basic-credentials
[name password]
(UsernamePasswordCredentials. name password))
(defn make-auth-scope
[host port]
(AuthScope. host port))
(defn set-credentials
[uri name password]
(.setCredentials credentials-provider
(make-auth-scope (.getHost uri) (.getPort uri))
(make-basic-credentials name password)))
(defn get-url-details
[url]
(let [details (get @url-details url)]
(if details
details
(let [[_ scheme name password rest] (re-matches #"(https?)://(.+):(.+)@(.*)" url)
details (if (and scheme name password rest)
{:clean-url (str scheme "://" rest)
:password password
:name name}
{:clean-url url})
uri (URI. (:clean-url details))]
(swap! url-details assoc url details)
(when (and name password)
(let [host (if (= (.getPort uri) -1)
(str (.getScheme uri) "://" (.getHost uri))
(str (.getScheme uri) "://" (.getHost uri) ":" (.getPort uri)))]
;;(println "**** CLOJURE-SOLR: Adding credentials for host" host)
(set-credentials uri name password)
(swap! credentials assoc host {:name name :password PI:PASSWORD:<PASSWORD>END_PI})))
details))))
(defn connect [url & conn-manager]
(let [params (ModifiableSolrParams.)
{:keys [clean-url name password]} (get-url-details url)
builder (doto (HttpClientBuilder/create)
(.setDefaultCredentialsProvider credentials-provider)
(.setConnectionManager (when conn-manager (first conn-manager)))
(.addInterceptorFirst
(reify
HttpRequestInterceptor
(^void process [this ^HttpRequest request ^HttpContext context]
(let [auth-state (.getAttribute context HttpClientContext/TARGET_AUTH_STATE)]
(when (nil? (.getAuthScheme auth-state))
(let [target-host (.getAttribute context HttpCoreContext/HTTP_TARGET_HOST)
auth-scope (make-auth-scope (.getHostName target-host) (.getPort target-host))
creds (.getCredentials credentials-provider auth-scope)]
;;(println "**** CLOJURE-SOLR: HttpRequestInterceptor here. Looking for" auth-scope)
(when creds
(.update auth-state (BasicScheme.) creds)))))))))
client (.build builder)]
(HttpSolrClient. clean-url client)))
(defn- make-document [boost-map doc]
(let [sdoc (SolrInputDocument.)]
(doseq [[key value] doc]
(let [key-string (name key)
boost (get boost-map key)]
(if boost
(.addField sdoc key-string value boost)
(.addField sdoc key-string value))))
sdoc))
(defn add-document!
([doc boost-map]
(.add *connection* (make-document boost-map doc)))
([doc]
(add-document! doc {})))
(defn add-documents!
([coll boost-map]
(.add *connection* (map (partial make-document boost-map) coll)))
([coll]
(add-documents! coll {})))
(defn commit! []
(.commit *connection*))
(defn- doc-to-hash [doc]
(into {} (for [[k v] (clojure.lang.PersistentArrayMap/create doc)]
[(keyword k)
(cond (= java.util.ArrayList (type v)) (into [] v)
:else v)])))
(defn- make-param [p]
(cond
(string? p) (into-array String [p])
(coll? p) (into-array String (map str p))
:else (into-array String [(str p)])))
(def http-methods {:get SolrRequest$METHOD/GET, :GET SolrRequest$METHOD/GET
:post SolrRequest$METHOD/POST, :POST SolrRequest$METHOD/POST})
(defn- parse-method [method]
(get http-methods method SolrRequest$METHOD/GET))
(defn extract-facets
[query-results facet-hier-sep limiting? formatters key-fields]
(map (fn [^FacetField f]
(let [field-name (.getName f)
facet-name (get key-fields field-name field-name)]
{:name facet-name
:values (sort-by :path
(map (fn [v]
(let [result
(merge
{:value (.getName v)
:count (.getCount v)}
(when-let [split-path (and facet-hier-sep (str/split (.getName v) facet-hier-sep))]
{:split-path split-path
:title (last split-path)
:depth (count split-path)}))]
((get formatters facet-name identity) result)))
(.getValues f)))}))
^List (if limiting?
(.getLimitingFacets query-results)
(.getFacetFields query-results))))
(def date-time-formatter
(tformat/formatters :date-time-no-ms))
(def query-result-date-time-parser
(tformat/formatter t/utc "YYYY-MM-dd'T'HH:mm:ss.SSS'Z'" "YYYY-MM-dd'T'HH:mm:ss'Z'"))
(defn format-range-value
"Timezone is only used if it's a date facet (and timezone is not null)."
[val timezone end?]
(let [d (try (tformat/parse date-time-formatter val)
(catch Exception _))]
(cond (or d (instance? java.util.Date val))
(let [d (or d (tcoerce/from-date val))]
(tformat/unparse (if timezone (tformat/with-zone date-time-formatter timezone) date-time-formatter)
(if end? (t/minus d (t/seconds 1)) d)))
:else (str val))))
(defn format-standard-filter-query
[name value]
(format "%s:%s" name value))
(defn format-raw-query
[name value]
(format "{!raw f=%s}%s" name value))
(defn format-facet-query
[{:keys [name value formatter]}]
(if (and (string? value) (re-find #"\[" value)) ;; range filter
(format-standard-filter-query name value)
(if formatter
(formatter name value)
(format-raw-query name value))))
(defn extract-facet-ranges
"Explicitly pass facet-date-ranges in case one or more ranges are date ranges, and we need to grab a timezone."
[query-results facet-date-ranges]
(sort-by :name
(map (fn [^RangeFacet r]
(let [date-range? (some (fn [{:keys [field]}] (= field (.getName r)))
facet-date-ranges)
timezone (:timezone (first (filter (fn [{:keys [field]}] (= field (.getName r)))
facet-date-ranges)))
gap (.getGap r)
values
(map (fn [val]
(let [start-val (.getValue val)
start-str (format-range-value start-val nil false)
end-val (cond date-range?
(.parseMath (doto (DateMathParser.)
(.setNow
(tcoerce/to-date
(tformat/parse query-result-date-time-parser start-val))))
gap)
(re-matches #"\d+" start-val)
(+ (Integer/parseInt start-val) gap)
:else (+ (Double/parseDouble start-val) gap))
end-str (format-range-value end-val nil true)]
{:count (.getCount val)
:value (format (if date-range? "[%s TO %s]" "[%s TO %s}") start-str end-str)
:min-inclusive start-str
:max-noninclusive end-str}))
(.getCounts r))
values-before (if (and (.getBefore r) (> (.getBefore r) 0))
(concat [{:count (.getBefore r)
:value (format (if date-range? "[* TO %s]" "[* TO %s}")
(format-range-value (.getStart r) nil true))
:min-inclusive nil
:max-noninclusive (format-range-value (.getStart r) timezone true)}]
values)
values)
values-before-after (if (and (.getAfter r) (> (.getAfter r) 0))
(concat values-before
[{:count (.getAfter r)
:value (format "[%s TO *]"
(format-range-value (.getEnd r) nil false))
:min-inclusive (format-range-value (.getEnd r) timezone false)
:max-noninclusive nil}])
values-before)]
{:name (.getName r)
:values (map #(dissoc % :orig-value) values-before-after)
:start (.getStart r)
:end (.getEnd r)
:gap (.getGap r)
:before (.getBefore r)
:after (.getAfter r)}))
(.getFacetRanges query-results))))
(defn extract-facet-queries
[facet-queries result]
(filter identity
(map (fn [query]
(let [formatted-query (if (string? query) query (format-facet-query query))
count (get result formatted-query)]
(when count
(if (string? query)
{:query query :count count}
(assoc query :count count)))))
facet-queries)))
(defn extract-pivots
[^QueryResponse query-results facet-date-ranges]
(let [^NamedList facet-pivot (.getFacetPivot query-results)]
(when facet-pivot
(into
{}
(map
(fn [index]
(let [facet1-name (.getName facet-pivot index)
^ArrayList pivot-fields (.getVal facet-pivot index)
ranges (into {}
(for [^PivotField pivot-field pivot-fields
:let [facet1-value (.getValue pivot-field)
facet-ranges (extract-facet-ranges pivot-field facet-date-ranges)]
:when (not-empty facet-ranges)]
[facet1-value
(into {}
(map (fn [range]
[(:name range) (:values range)])
facet-ranges))]))
pivot-counts (into {}
(for [^PivotField pivot-field pivot-fields]
(let [facet1-value (.getValue pivot-field)
^List pivot-values (.getPivot pivot-field)]
[facet1-value
(into {}
(map (fn [^PivotField pivot]
(if (.getFacetRanges pivot)
[(.getValue pivot)
{:count (.getCount pivot)
:ranges (extract-facet-ranges pivot facet-date-ranges)}]
[(.getValue pivot)
(.getCount pivot)]))
pivot-values))])))]
;;(println facet1-name)
[facet1-name (cond (and (not-empty ranges) (not-empty pivot-counts) (= (count ranges) (count pivot-counts)))
{:counts pivot-counts :ranges ranges}
(not-empty pivot-counts)
pivot-counts
(not-empty ranges)
ranges
:else nil)]))
(range 0 (.size facet-pivot)))))))
(defn show-query
[q flags]
(trace "Solr Query:")
(trace q)
(trace " Facet filters:")
(if (not-empty (:facet-filters flags))
(doseq [ff (:facet-filters flags)]
(trace (format " %s" (format-facet-query ff))))
(trace " none"))
(trace " Facet queries:")
(if (not-empty (:facet-queries flags))
(doseq [ff (:facet-queries flags)]
(trace (format " %s" (format-facet-query ff))))
(trace " none"))
(trace " Facet fields:")
(if (not-empty (:facet-fields flags))
(doseq [ff (:facet-fields flags)]
(trace (format " %s" (if (map? ff) (pr-str ff) ff))))
(trace " none"))
(let [other (dissoc flags :facet-filters :facet-qieries :facet-fields)]
(when (not-empty other)
(trace " Other parameters to Solr:")
(doseq [[k v] other]
(trace (format " %s: %s" k (pr-str v))))))
)
(def facet-exclude-parameters
#{:name :result-formatter})
(defn search*
"Query solr through solrj.
q: Query field
Optional keys, passed in a map:
:method :get or :post (default :get)
:rows Number of rows to return (default is Solr default: 1000)
:start Offset into query result at which to start returning rows (default 0)
:fields Fields to return
:facet-fields Discrete-valued fields to facet. Can be a string, keyword, or map containing
{:name ... :prefix ...}.
:facet-queries Vector of facet queries, each encoded in a string or a map of
{:name, :value, :formatter}. :formatter is optional and defaults to the raw query formatter.
The result is in the :facet-queries response.
:facet-date-ranges Date fields to facet as a vector or maps. Each map contains
:field Field name
:tag Optional, for referencing in a pivot facet
:start Earliest date (as java.util.Date)
:end Latest date (as java.util.Date)
:gap Faceting gap, as String, per Solr (+1HOUR, etc)
:others Comma-separated string: before,after,between,none,all. Optional.
:include Comma-separated string: lower,upper,edge,outer,all. Optional.
:hardend Boolean (See Solr doc). Optional.
:missing Boolean--return empty buckets if true. Optional.
:facet-numeric-ranges Numeric fields to facet, as a vector of maps. Map fields as for
date ranges, but start, end and gap must be numbers.
:facet-mincount Minimum number of docs in a facet for the bucket to be returned.
:facet-hier-sep Useful for path hierarchy token faceting. A regex, such as \\|.
:facet-filters Solr filter expression on facet values. Passed as a map in the form:
{:name 'facet-name' :value 'facet-value' :formatter (fn [name value] ...) }
where :formatter is optional and is used to format the query.
:facet-pivot-fields Vector of pivots to compute, each a list of facet fields.
If a facet is tagged (e.g., {:tag ts} in :facet-date-ranges)
then the string should be {!range=ts}other-facet. Otherwise,
use comma separated lists: this-facet,other-facet.
:cursor-mark true -- initial cursor; else a previous cursor value from
(:next-cursor-mark (meta result))
Additional keys can be passed, using Solr parameter names as keywords.
Returns the query results as the value of the call, with faceting results as metadata.
Use (meta result) to get facet data."
[q {:keys [method fields facet-fields facet-date-ranges facet-numeric-ranges facet-queries
facet-mincount facet-hier-sep facet-filters facet-pivot-fields cursor-mark] :as flags}]
(show-query q flags)
(let [query (cond (string? q) (SolrQuery. q)
(instance? SolrQuery q) q
:else (throw (Exception. "q parameter must be a string or SolrQuery")))
method (parse-method method)
facet-result-formatters (into {} (map #(if (map? %)
[(:name %) (:result-formatter % identity)]
[% identity])
facet-fields))
facet-key-fields (into {} (map-indexed (fn [i f]
[(format "f%d" i) (if (map? f) (:name f) (name f))])
facet-fields))
facet-field-keys (into {} (map-indexed (fn [i f]
[(if (map? f) (:name f) (name f)) (format "f%d" i)])
facet-fields))]
(doseq [[key value] (dissoc flags :method :facet-fields :facet-date-ranges :facet-numeric-ranges :facet-filters)]
(.setParam query (apply str (rest (str key))) (make-param value)))
(when (not (empty? fields))
(cond (string? fields)
(.setFields query (into-array (str/split fields #",")))
(or (seq? fields) (vector? fields))
(.setFields query (into-array
(map (fn [f]
(cond (string? f) f
(keyword? f) (name f)
:else (throw (Exception. (format "Unsupported field name: %s" f)))))
fields)))
:else (throw (Exception. (format "Unsupported :fields parameter format: %s" fields)))))
;; How to facet the same attribute different ways (using different prefixes)
;; https://stackoverflow.com/questions/31340400/multiple-facet-prefix-on-a-single-facet-field
;; http://192.168.0.200:8983/solr/i2ksearch/select?facet.field={!key=f1%20facet.prefix="prefix1"}attribute&facet.field={!key=f2%20facet.prefix="prefix 2"}attribute&facet.limit=300&facet.query=attribute:<<query>>&facet=on&fq=attribute:<<query>>&rows=0
(let [facet-field-parameters
(for [facet-field facet-fields
:let [field-name (if (map? facet-field)
(:name facet-field)
(name facet-field))
key (get facet-field-keys field-name)]]
(if (map? facet-field)
(let [local-params
(reduce-kv (fn [params k v]
(if (facet-exclude-parameters k)
params
(format "%s facet.%s=\"%s\"" params (name k) v)))
(format "!key=%s" key)
facet-field)]
(format "{%s}%s" local-params field-name))
(format "{!key=%s}%s" key field-name)))]
(when (not-empty facet-field-parameters)
(.addFacetField query (into-array String facet-field-parameters))))
(doseq [facet-query facet-queries]
(cond (string? facet-query)
(.addFacetQuery query facet-query)
(map? facet-query)
(let [formatted-query (format-facet-query facet-query)]
(when (not-empty formatted-query) (.addFacetQuery query formatted-query)))
:else (throw (Exception. "Invalid facet query. Must be a string or a map of {:name, :value, :formatter (optional)}"))))
(doseq [{:keys [field start end gap others include hardend missing mincount tag]} facet-date-ranges]
(if tag
;; This is a workaround for a Solrj bug that causes tagged queries to be improperly formatted.
(do (.setParam query "facet" true)
(.add query "facet.range" (into-array String [(format "{!tag=%s}%s" tag field)]))
(.add query (format "f.%s.facet.range.start" field)
(into-array String [(tformat/unparse (tformat/formatters :date-time-no-ms)
(tcoerce/from-date start))]))
(.add query (format "f.%s.facet.range.end" field)
(into-array String [(tformat/unparse (tformat/formatters :date-time-no-ms)
(tcoerce/from-date end))]))
(.add query (format "f.%s.facet.range.gap" field) (into-array String [gap])))
(.addDateRangeFacet query field start end gap))
(when missing (.setParam query (format "f.%s.facet.missing" field) true))
(when others (.setParam query (format "f.%s.facet.range.other" field) (into-array String others)))
(when include (.setParam query (format "f.%s.facet.range.include" field) (into-array String [include])))
(when hardend (.setParam query (format "f.%s.facet.range.hardend" field) hardend)))
(doseq [{:keys [field start end gap others include hardend missing mincount tag]} facet-numeric-ranges]
(assert (instance? Number start))
(assert (instance? Number end))
(assert (instance? Number gap))
(if tag
;; This is a workaround for a Solrj bug that causes tagged queries to be improperly formatted.
(do (.setParam query "facet" true)
(.add query "facet.range" (into-array String [(format "{!tag=%s}%s" tag field)]))
(.add query (format "f.%s.facet.range.start" field) (into-array String [(.toString start)]))
(.add query (format "f.%s.facet.range.end" field) (into-array String [(.toString end)]))
(.add query (format "f.%s.facet.range.gap" field) (into-array String [(.toString gap)])))
(.addNumericRangeFacet query field start end gap))
(when missing (.setParam query (format "f.%s.facet.missing" field) true))
(when others (.setParam query (format "f.%s.facet.range.other" field) (into-array String others)))
(when include (.setParam query (format "f.%s.facet.range.include" field) (into-array String [include])))
(when hardend (.setParam query (format "f.%s.facet.range.hardend" field) hardend)))
(doseq [field facet-pivot-fields]
(.addFacetPivotField query (into-array String [field])))
(.addFilterQuery query (into-array String (filter not-empty (map format-facet-query facet-filters))))
(.setFacetMinCount query (or facet-mincount 1))
(cond (= cursor-mark true)
(.setParam query ^String (CursorMarkParams/CURSOR_MARK_PARAM) (into-array String [(CursorMarkParams/CURSOR_MARK_START)]))
(not (nil? cursor-mark))
(.setParam query ^String (CursorMarkParams/CURSOR_MARK_PARAM) (into-array String [cursor-mark])))
(trace "Executing query")
(let [query-results (.query *connection* query method)
results (.getResults query-results)]
(trace "Query complete")
(when (:debugQuery flags)
(trace (.getDebugMap query-results)))
(with-meta (map doc-to-hash results)
(merge
(when cursor-mark
(let [next (.getNextCursorMark query-results)]
{:next-cursor-mark next
:cursor-done (.equals next (if (= cursor-mark true)
(CursorMarkParams/CURSOR_MARK_START)
cursor-mark))}))
(when (:debugQuery flags)
{:debug (.getDebugMap query-results)})
(when (.getFieldStatsInfo query-results)
{:statistics
(into {}
(for [[field info] (.getFieldStatsInfo query-results)]
[field {:min (.getMin info)
:max (.getMax info)
:mean (.getMean info)
:stddev (.getStddev info)
:sum (.getSum info)
:count (.getCount info)
:missing (.getMissing info)
}]))})
{:start (.getStart results)
:rows-set (count results)
:rows-total (.getNumFound results)
:highlighting (.getHighlighting query-results)
:facet-fields (extract-facets query-results facet-hier-sep false facet-result-formatters facet-key-fields)
:facet-range-fields (extract-facet-ranges query-results facet-date-ranges)
:limiting-facet-fields (extract-facets query-results facet-hier-sep true facet-result-formatters facet-key-fields)
:facet-queries (extract-facet-queries facet-queries (.getFacetQuery query-results))
:facet-pivot-fields (extract-pivots query-results facet-date-ranges)
:results-obj results
:query-results-obj query-results})))))
(defn search
"Query solr through solrj.
q: Query field
Optional keys:
:method :get or :post (default :get)
:rows Number of rows to return (default is Solr default: 1000)
:start Offset into query result at which to start returning rows (default 0)
:fields Fields to return
:facet-fields Discrete-valued fields to facet. Can be a string, keyword, or map containing
{:name ... :prefix ...}.
:facet-queries Vector of facet queries, each encoded in a string or a map of
{:name, :value, :formatter}. :formatter is optional and defaults to the raw query formatter.
The result is in the :facet-queries response.
:facet-date-ranges Date fields to facet as a vector or maps. Each map contains
:field Field name
:tag Optional, for referencing in a pivot facet
:start Earliest date (as java.util.Date)
:end Latest date (as java.util.Date)
:gap Faceting gap, as String, per Solr (+1HOUR, etc)
:others Comma-separated string: before,after,between,none,all. Optional.
:include Comma-separated string: lower,upper,edge,outer,all. Optional.
:hardend Boolean (See Solr doc). Optional.
:missing Boolean--return empty buckets if true. Optional.
:facet-numeric-ranges Numeric fields to facet, as a vector of maps. Map fields as for
date ranges, but start, end and gap must be numbers.
:facet-mincount Minimum number of docs in a facet for the bucket to be returned.
:facet-hier-sep Useful for path hierarchy token faceting. A regex, such as \\|.
:facet-filters Solr filter expression on facet values. Passed as a map in the form:
{:name 'facet-name' :value 'facet-value' :formatter (fn [name value] ...) }
where :formatter is optional and is used to format the query.
:facet-pivot-fields Vector of pivots to compute, each a list of facet fields.
If a facet is tagged (e.g., {:tag ts} in :facet-date-ranges)
then the string should be {!range=ts}other-facet. Otherwise,
use comma separated lists: this-facet,other-facet.
:cursor-mark true -- initial cursor; else a previous cursor value from
(:next-cursor-mark (meta result))
Returns the query results as the value of the call, with faceting results as metadata.
Use (meta result) to get facet data."
[q & {:keys [method fields facet-fields facet-date-ranges facet-numeric-ranges facet-queries
facet-mincount facet-hier-sep facet-filters facet-pivot-fields] :as flags}]
(search* q flags))
(defn atomically-update!
"Atomically update a solr document:
doc: document fetched from solr previously, or the id of such a document (must not be a map)
unique-key: Name of the attribute that is the document's unique key
changes: Vector of maps containing :attribute, :func [one of :set, :inc, :add], and :value.
e.g.
(atomically-update! doc \"cdid\" [{:attribute :client :func :set :value \"darcy\"}])"
[doc unique-key-field changes]
(let [document (SolrInputDocument.)]
(.addField document (name unique-key-field) (if (map? doc) (get doc unique-key-field) doc))
(doseq [{:keys [attribute func value]} changes]
(.addField document (name attribute) (doto (HashMap. 1) (.put (name func) value))))
(.add *connection* document)))
(defn similar [doc similar-count & {:keys [method]}]
(let [query (SolrQuery. (format "id:%d" (:id doc)))
method (parse-method method)]
(.setParam query "mlt" (make-param true))
(.setParam query "mlt.fl" (make-param "fulltext"))
(.setParam query "mlt.count" (make-param similar-count))
(let [query-results (.query *connection* query method)]
(map doc-to-hash (.get (.get (.getResponse query-results) "moreLikeThis") (str (:id doc)))))))
(defn more-like-this
"Execute a Solr moreLikeThis (mlt) query.
id: unique id of doc to match.
unique-key: Name of key in schema that corresponds to id.
similarity-fields: Fields to match against. Pass as comma-separated list or vector.
params: Map of optional parameters:
match-include? -- this is not clearly documented. See Solr manual.
min-doc-freq -- ignore words that don't occur in at least this many docs. Default 3.
min-term-freq -- ignore terms that occur fewer times than this in a document. Default 2.
min-word-len -- minimum word length for matching. Default 5.
boost? -- Specifies if query will be boosted by interesting term relevance. Default true.
max-query-terms -- Maximum number of query terms in a search. Default 1000.
max-results -- Maximum number of similar docs returned. Default 5.
fields -- fields of docs to return. Pass as vector or comma-separated list.. Default: unique key + score.
method -- Solr Query method.
Other key/value pairs can be passed in params and are passed onto search*, so can be used
for filtering."
[id unique-key similarity-fields
{:keys [match-include?
min-doc-freq
min-term-freq
min-word-len
boost?
max-query-terms
max-results
fields
method]
:or {match-include? false
min-doc-freq (int 3)
min-term-freq (int 2)
min-word-len (int 5)
boost? true
max-results (int 5)
fields "score"
max-query-terms (int 1000)}
:as params}]
(let [query (doto (SolrQuery.)
(.setRequestHandler (str "/" MoreLikeThisParams/MLT))
(.set MoreLikeThisParams/MATCH_INCLUDE (make-param match-include?))
(.set MoreLikeThisParams/MIN_DOC_FREQ (make-param min-doc-freq))
(.set MoreLikeThisParams/MIN_TERM_FREQ (make-param min-term-freq))
(.set MoreLikeThisParams/MIN_WORD_LEN (make-param min-word-len))
(.set MoreLikeThisParams/BOOST (make-param boost?))
(.set MoreLikeThisParams/MAX_QUERY_TERMS (make-param max-query-terms))
(.set MoreLikeThisParams/SIMILARITY_FIELDS (make-param (if (string? similarity-fields)
similarity-fields
(str/join "," similarity-fields))))
(.setQuery (format "%s:\"%s\"" (name unique-key) (str id)))
(.set "fl" (make-param (format "%s,%s" (name unique-key)
(if (string? fields)
fields
(str/join "," fields)))))
(.setRows max-results))
query-results (search* query
(dissoc params
:match-include?
:min-doc-freq
:min-term-freq
:min-word-len
:boost?
:fields
:max-query-terms
:max-results
:method))]
(map doc-to-hash (:results-obj (meta query-results)))))
(defn delete-id! [id]
(.deleteById *connection* id))
(defn delete-query! [q]
(.deleteByQuery *connection* q))
(defn data-import [type]
(let [type (cond (= type :full) "full-import"
(= type :delta) "delta-import")
params (doto (ModifiableSolrParams.)
(.set "qt" (make-param "/dataimport"))
(.set "command" (make-param type)))]
(.query *connection* params)))
(defmacro with-connection [conn & body]
`(binding [*connection* ~conn]
(try
(do ~@body)
(finally (.close *connection*)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.