Skip to content

Commit

Permalink
refactor: avoid laziness by wrapping stdin under the IReduceInit (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
dainiusjocas authored Apr 18, 2023
1 parent eb01dd1 commit 2c31bbc
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions cli/jq/cli.clj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
[clojure.string :as str]
[clojure.tools.cli :as cli]
[jq.transducers :as jq])
(:import (java.io Reader BufferedReader)))
(:import (clojure.lang IReduceInit)
(java.io Reader BufferedReader)))

(def cli-options
[["-c" "--[no-]compact" "compact instead of pretty-printed output." :default false]
Expand All @@ -24,17 +25,32 @@
(println "Supported options:")
(println summary))

(defn lines-from-stdin
"Reads lines from the stdin and pushes them further."
[]
(let [^BufferedReader rdr (BufferedReader. *in*)]
(reify IReduceInit
(reduce [_ f init]
(try
(loop [state init]
(if (reduced? state)
state
(if-let [line (.readLine rdr)]
(recur (f state line))
state)))
(finally (.close rdr)))))))

(defn printer
([_])
([_ item] (println item)))

(defn execute [jq-expression files opts]
(let [xfs [(when (seq files) (map slurp))
(jq/parse)
(jq/execute jq-expression)
(if (:compact opts) (jq/serialize) (jq/pretty-print))]
xf (apply comp (remove nil? xfs))
values (or (seq files) (when (.ready ^Reader *in*)
(line-seq (BufferedReader. *in*))))]
values (or (seq files) (when (.ready ^Reader *in*) (lines-from-stdin)))]
(transduce xf printer nil values)))

(defn -main [& args]
Expand Down

0 comments on commit 2c31bbc

Please sign in to comment.