From 9cece7f46cda55e06b6ff4e23419717580db0643 Mon Sep 17 00:00:00 2001 From: Markku Rontu Date: Mon, 31 Oct 2022 16:20:41 +0200 Subject: [PATCH] Autodetect color (#20) * fix: use keyword for default value Parsing doesn't happen on default values, so we must provide the correct format default value. * feat: autodetect color We can now automatically detect if we should use color when printing. Mostly color will be set to off when cq is used in a pipe, because a console is not available. This can be forced on with the command-line flags. * chore: bump org.clojure/tools.cli to the latest version --- deps.edn | 2 +- src/cq/main.clj | 15 +++++++++++++-- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/deps.edn b/deps.edn index 70983da..41a9c3f 100644 --- a/deps.edn +++ b/deps.edn @@ -4,7 +4,7 @@ org.clojure/data.csv {:mvn/version "1.0.0"} org.clojure/data.xml {:mvn/version "0.2.0-alpha6"} org.clojure/data.json {:mvn/version "1.1.0"} - org.clojure/tools.cli {:mvn/version "1.0.206"} + org.clojure/tools.cli {:mvn/version "1.0.214"} org.clojure/tools.reader {:mvn/version "1.3.4"} org.babashka/sci {:mvn/version "0.3.2"} camel-snake-kebab/camel-snake-kebab {:mvn/version "0.4.2"} diff --git a/src/cq/main.clj b/src/cq/main.clj index 97209fb..c3d7ec6 100644 --- a/src/cq/main.clj +++ b/src/cq/main.clj @@ -29,7 +29,7 @@ ["-p" "--[no-]pretty" "Pretty print output - default is true" :default true] [nil "--color COLOR" (str "When pretty printing, whether to use colors: " colors-str " - default is auto") - :default "auto" + :default :auto :parse-fn keyword :validate [colors]] ["-c" nil "Same as --color=on" @@ -110,9 +110,20 @@ (def ^:dynamic *stdin* System/in) (def ^:dynamic *stdout* System/out) +(defn- autodetect-color + "Autodetects whether ANSI color should be enabled. + + REPLs in general support colors, but may not use a console. + + JVM gives us the `System/console`, if we have a console, + and not a plain pipe." + [] + (or (contains? (set (loaded-libs)) 'nrepl.core) + (System/console))) + (defn- handle-auto-options [opts] (update opts :color #(case % - :auto true ; would be nice to detect + :auto (autodetect-color) :on true false)))