Skip to content

Instantly share code, notes, and snippets.

@jeroenvandijk
Last active September 29, 2020 20:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeroenvandijk/55dc9005035bc506493ca279d43b2236 to your computer and use it in GitHub Desktop.
Save jeroenvandijk/55dc9005035bc506493ca279d43b2236 to your computer and use it in GitHub Desktop.
Babashka pod in babashka
(require '[bencode.core :as bencode]
'[clojure.walk :as walk])
(def stdin (java.io.PushbackInputStream. System/in))
(defn write [v]
(bencode/write-bencode System/out v)
(.flush System/out))
(defn read-string [^"[B" v]
(String. v))
(defn read []
(bencode/read-bencode stdin))
(def debug? false)
(defn debug [& strs]
(when debug?
(binding [*out* (io/writer System/err)]
(apply println strs))))
(def lookup {'calculate/+ +})
(def describe-map
'{:format :edn
:namespaces [{:name calculate
:vars [{:name +}]}]
:opts {:shutdown {}}})
(debug describe-map)
(defn -main [& _args]
(loop []
(let [message (try (read)
(catch java.io.EOFException _
(debug :EOF)
::EOF))]
(when-not (identical? ::EOF message)
(debug ["message" message])
(let [op (get message "op")
op (read-string op)
op (keyword op)
id (some-> (get message "id")
read-string)
id (or id "unknown")]
(case op
:describe (do (write describe-map)
(recur))
:invoke (do (try
(let [var (-> (get message "var")
read-string
symbol)
args (get message "args")
args (read-string args)
args (edn/read-string args)]
(if-let [f (lookup var)]
(let [value (pr-str (apply f args))
reply {"value" value
"id" id
"status" ["done"]}]
(write reply))
(throw (ex-info (str "Var not found: " var) {}))))
(catch Throwable e
(debug e)
(let [reply {"ex-message" (ex-message e)
"ex-data" (pr-str
(assoc (ex-data e)
:type (class e)))
"id" id
"status" ["done" "error"]}]
(write reply))))
(recur))
:shutdown (System/exit 0)
(do
(let [reply {"ex-message" "Unknown op"
"ex-data" (pr-str {:op op})
"id" id
"status" ["done" "error"]}]
(write reply))
(recur))))))))
(apply -main *command-line-args*)
(require '[babashka.pods :as pods])
(pods/load-pod ["bb" "pod.bb"])
(println "pod loaded")
(require '[calculate])
(println "calc" (calculate/+ 1 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment