Skip to content

Commit eb01dd1

Browse files
authored
CLI: pretty print output by default (#44)
* feat: pretty print by default, -c for compact; CLI as transducers
1 parent e00cb7e commit eb01dd1

File tree

2 files changed

+16
-12
lines changed

2 files changed

+16
-12
lines changed

Diff for: CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ For a list of breaking changes, check [here](#breaking-changes).
1010
- Allow JQ variables to be passed at execution time #38 (Thanks to @charles-dyfis-net)
1111
- API to return a stream of JSON entities #41
1212
- Transducers API #42
13+
- CLI: pretty print output by default, flag `-c` for compact #44
1314

1415
## v1.2.1
1516

Diff for: cli/jq/cli.clj

+15-12
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
(:require [clojure.java.io :as io]
44
[clojure.string :as str]
55
[clojure.tools.cli :as cli]
6-
[jq.api :as jq])
6+
[jq.transducers :as jq])
77
(:import (java.io Reader BufferedReader)))
88

99
(def cli-options
10-
[["-h" "--help"]])
10+
[["-c" "--[no-]compact" "compact instead of pretty-printed output." :default false]
11+
["-h" "--help"]])
1112

1213
(defn handle-args [args]
1314
(cli/parse-opts args cli-options))
@@ -23,16 +24,18 @@
2324
(println "Supported options:")
2425
(println summary))
2526

26-
(defn execute [jq-filter files _]
27-
(let [jq-processor (jq/stream-processor jq-filter)]
28-
(if (seq files)
29-
(doseq [f files
30-
item (jq-processor (jq/string->json-node (slurp f)))]
31-
(println (jq/json-node->string item)))
32-
(when (.ready ^Reader *in*)
33-
(doseq [^String line (line-seq (BufferedReader. *in*))
34-
item (jq-processor (jq/string->json-node line))]
35-
(println (jq/json-node->string item)))))))
27+
(defn printer
28+
([_])
29+
([_ item] (println item)))
30+
(defn execute [jq-expression files opts]
31+
(let [xfs [(when (seq files) (map slurp))
32+
(jq/parse)
33+
(jq/execute jq-expression)
34+
(if (:compact opts) (jq/serialize) (jq/pretty-print))]
35+
xf (apply comp (remove nil? xfs))
36+
values (or (seq files) (when (.ready ^Reader *in*)
37+
(line-seq (BufferedReader. *in*))))]
38+
(transduce xf printer nil values)))
3639

3740
(defn -main [& args]
3841
(let [{:keys [options arguments errors summary]

0 commit comments

Comments
 (0)