Skip to content

Instantly share code, notes, and snippets.

@kanaka
Created November 4, 2022 15:38
Show Gist options
  • Save kanaka/dab28f1b2977f67c5b64c9c4c669060a to your computer and use it in GitHub Desktop.
Save kanaka/dab28f1b2977f67c5b64c9c4c669060a to your computer and use it in GitHub Desktop.
Example nbb script using neodoc and promesa (and shell invoke trick)
#!/bin/bash
true;exec "$(dirname $0)/node_modules/.bin/nbb" "$(which "$0")" "$@" || exit
(ns foo
(:require [clojure.string :as S]
[clojure.pprint :refer [pprint]]
[promesa.core :as P]
[cljs-bean.core :refer [->clj ->js]]
["fs/promises" :as fs]
["path" :as path]
["neodoc" :as neodoc]))
(def usage "
Usage:
foo [options] <file1> <file2>
Load files file1 and file2 and split the lines.
Options:
-v..., --verbose... Verbose output [env: VERBOSE]
--some-opt OPT Some option [default: blah]
")
(defn clean-opts [arg-map]
(reduce (fn [o [a v]]
(let [k (keyword (S/replace a #"^[-<]*([^>]*)[>]*$" "$1"))]
(assoc o k (or (get o k) v))))
{} arg-map))
(defn parse-opts [usage argv & [opts]]
(-> usage
(neodoc/run (clj->js (merge {:laxPlacement true
:smartOptions true
:argv (or argv [])}
opts)))
js->clj
clean-opts))
;; async function
(defn get-lines [file]
(P/-> (fs/readFile file "utf8")
(S/split #"\n")))
(P/let
[opts (parse-opts usage *command-line-args*)
{:keys [verbose some-opt file1 file2]} opts
_ (when verbose (pprint opts))
;; implicit await due to P/let
lines1 (get-lines file1)
;; Wrapped so no implicit await
[lines2-prom] [(get-lines file2)]
;; implicit await
lines2 lines2-prom
result {:lines1 lines1
:lines2 lines2}]
(println "lines2-prom is a promise:" lines2-prom)
(println (js/JSON.stringify (->js result) nil 2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment