Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Upgrades mage run-tests (#66108)

bryanb453baf5edfb
diff --git a/.claude/skills/_shared/clojure-commands.md b/.claude/skills/_shared/clojure-commands.md
index 357529033b5..68ea17bf472 100644
--- a/.claude/skills/_shared/clojure-commands.md
+++ b/.claude/skills/_shared/clojure-commands.md
@@ -14,6 +14,12 @@
- **Run a test:** `./bin/mage run-tests namespace/test-name`
- **Run all tests in a namespace:** `./bin/mage run-tests namespace`
+- **Run all tests for a module:** `./bin/mage run-tests test/metabase/notification` Because the module lives in that directory.
+
+Note: the `./bin/mage run-tests` command accepts multiple args, so you can pass
+`./bin/mage run-tests namespace/test-name namespace/other-test namespace/third-test`
+to run 3 tests, or
+`./bin/mage run-tests test/metabase/module1 test/metabase/module2` to run 2 modules.
## Code Readability
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index b8fd9e59537..37bc6821733 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -752,7 +752,10 @@
;; `metabase-enterprise.sandbox.query-processor*-test`
;;
{:pattern "^metabase(?:((?:-enterprise\\.sandbox)?\\.query-processor)|(?:\\.driver\\.sql(?!server)(?!ite))).*-test$"
- :name general-qp-and-driver-test-namespaces}]
+ :name general-qp-and-driver-test-namespaces}
+
+ {:pattern "(?:^mage.*)"
+ :name mage-namespaces}]
:config-in-ns
{test-namespaces
@@ -947,4 +950,11 @@
toucan2.tools.with-temp/with-temp {:message "Use lib.tu/mock-metadata-provider in QP tests. Exceptions: tests for code that doesn't use MPs or models not supported by MPs"}}
:metabase/disallow-hardcoded-driver-names-in-tests
- {:level :warning}}}}}
+ {:level :warning}}}
+
+ mage-namespaces
+ {:linters
+ {:discouraged-java-method
+ {java.lang.System {exit
+ {:level :error
+ :message "Don't use System/exit directly. Instead throw an ex-info with {:babashka/exit <exit-code>} (and optionally :mage/error) let the mage runner handle exiting the process"}}}}}}}
diff --git a/bb.edn b/bb.edn
index 03341d2e08c..6a50f28aaf6 100644
--- a/bb.edn
+++ b/bb.edn
@@ -3,10 +3,11 @@
;; so the namespaces are mage.cli, mage.format, etc.
:paths ["mage/src" "mage/test" "bin/lint-migrations-file/src"]
:deps {dev.weavejester/cljfmt {:mvn/version "0.15.3"}
- org.babashka/json {:mvn/version "0.1.6"}
+ io.github.paintparty/bling {:mvn/version "0.8.8"}
metosin/malli {:mvn/version "0.17.0"}
- table/table {:mvn/version "0.5.0"}
- mvxcvi/puget {:mvn/version "1.3.4"}}
+ mvxcvi/puget {:mvn/version "1.3.4"}
+ org.babashka/json {:mvn/version "0.1.6"}
+ table/table {:mvn/version "0.5.0"}}
:tasks
{:requires [[mage.cli :as cli]
[mage.color :as c]]
@@ -186,24 +187,21 @@
(nrepl-eval "metabase-enterprise.comments.core" code)))}
run-tests
- {:doc "Run a tests (or a single test) against nrepl server"
- :requires [[clojure.string :as str]
- [mage.be-dev :refer [nrepl-eval]]]
- :arg-schema [:tuple [:string {:name "NS/TEST" :desc "or just NS"}]]
- :options [["-p" "--port PORT" "Port to use for the task, defaults to value in .nrepl-port"]]
- :task (let [{:keys [options]
- [test] :arguments} (cli/parse! (current-task))
- test (if (or (str/starts-with? test "test/")
- (str/starts-with? test "enterprise/"))
- ;; paths should come in as strings
- (format "\"%s\"" test)
- ;; ns or var should be a symbol
- (str "'" test))
- code (format
- "(do ((requiring-resolve 'dev.reload/reload!)) (find-and-run-tests-repl {:only %s}))"
- test)]
- (nrepl-eval "mb.hawk.core" (str code) (:port options)))}
-
+ {:doc "Quickly run tests locally. Pass dirs/files as arguments to run them."
+ :examples [["./bin/mage run-tests" "launch interactive test picker"]
+ ["./bin/mage run-tests test/metabase/db" "run tests in test/metabase/db"]
+ ["./bin/mage run-tests test/metabase/logger test/metabase/api_keys" "run tests in test/metabase/logger and src/metabase/api_keys"]
+ ["./bin/mage run-tests test/metabase/config_test.clj" "run all tests in the metabase.config-test namespace"]]
+ ;; TODO: add option to select files as well as dirs from fzf with styles
+ :options [["-s" "--selecting STYLE" "Style of test selection" :default "all"]
+ ;; all, file, dir
+ ["-p" "--port PORT" "Port to use for the task, defaults to value in .nrepl-port"]]
+ :arg-schema [:sequential
+ {:details "If none are given, you will be prompted to select directories recursively from test/ and enterprise/backend/test/"}
+ [:string {:description "Files or directories (recursive) to test"}]]
+ :requires [[mage.quick-test-runner :as qtr]]
+ :task (task! (qtr/go parsed))}
+
affected-modules
{:doc "Prints information about which backend modules have changes compared to a Git ref e.g. `master`"
:examples [["./bin/mage affected-modules master"]
@@ -218,10 +216,11 @@
:requires [[mage.modules]]
:task (task! (mage.modules/cli-can-skip-driver-tests (:arguments parsed)))}
- ls {:doc "List all mage public and private tasks"
- :examples [["./bin/mage ls" "List all tasks"]]
- :requires [[mage.util :as u]]
- :task (task! (u/print-tasks parsed))}
+ ls
+ {:doc "List all mage public and private tasks"
+ :examples [["./bin/mage ls" "List all tasks"]]
+ :requires [[mage.util :as u]]
+ :task (task! (u/print-tasks parsed))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Private Tasks:
@@ -334,6 +333,6 @@
-escherize-fix-whitespace
{:doc "Removes all lines like '^<space>+$' from files in glob pattern."
:requires [[mage.escherize.fix-whitespace :as fix-whitespace]]
- :examples [["mage -escherize-fix-whitespace '**/*.clj'" "Removes all lines like ' ' from all clj files"]]
+ :examples [["mage -escherize-fix-whitespace '**/*.clj{,c,s}'" "Removes all lines like ' ' from all clj files"]]
:arg-schema [:sequential [:string {:description "Glob pattern to match files"}]]
:task (task! (fix-whitespace/run-clean parsed))}}}
diff --git a/bin/mage.bb b/bin/mage.bb
index a60f7eac82c..425f114c012 100755
--- a/bin/mage.bb
+++ b/bin/mage.bb
@@ -62,6 +62,10 @@
(.getCause e)
(assoc :cause (summarize-exception (.getCause e)))))
+(def ^:private ex-message-label (c/red (c/reverse-color "ex-message : ")))
+(def ^:private ex-data-label (c/yellow (c/reverse-color "ex-data : ")))
+(def ^:private mage-error-label (c/blue (c/reverse-color "mage/error : ")))
+
(defn -main [& _]
(cond
;; help
@@ -73,7 +77,9 @@
;; errors
(invalid-task?)
- (do (print-help) (System/exit 1))
+ (do (print-help)
+ #_{:clj-kondo/ignore [:discouraged-java-method]}
+ (System/exit 1))
:else
;; at this point, we always have a valid task, and we are running in bb, so
@@ -101,13 +107,13 @@
(cond-> e
(not (u/env "MAGE_DEBUG" (constantly nil)))
summarize-exception)))
- (when (and message (not (str/blank? message)))
- (println (c/red (c/reverse-color "ex-message : ")) message))
- (when data
- (println (c/yellow (c/reverse-color "ex-data : ")) (pr-str
- (dissoc data :mage/error))))
+ (when (not (str/blank? message))
+ (println ex-message-label message))
+ (when (not-empty (dissoc data :mage/error))
+ (println ex-data-label (u/pp (dissoc data :mage/error))))
(when (:mage/error data)
- (println (c/blue (c/reverse-color "mage/error : ")) (:mage/error data)))
+ (println mage-error-label (:mage/error data)))
+ #_{:clj-kondo/ignore [:discouraged-java-method]}
(System/exit (:babashka/exit data 1))))))))))
(when (= *file* (System/getProperty "babashka.file"))
diff --git a/mage/cmd/fzf_preview.clj b/mage/cmd/fzf_preview.clj
new file mode 100755
index 00000000000..7fc9e4bbf38
--- /dev/null
+++ b/mage/cmd/fzf_preview.clj
@@ -0,0 +1,60 @@
+#!/usr/bin/env bb
+;; This file is meant to be called Through fzf, not directly!
+(ns mage.fzf-preview
+ (:require
+ [babashka.fs :as fs]
+ [babashka.process :as p]
+ [clojure.string :as str]
+ [mage.color :as c]
+ [mage.util :as u]))
+
+(defn- preview-file [file-path]
+ (->> (if (u/can-run? "bat")
+ ["bat" "--color=always" "--style=numbers" file-path]
+ ["cat" file-path])
+ (apply p/shell)))
+
+(defn- preview-dir [dir-path]
+ (let [count-cmd ["fd" "--hidden" "--no-ignore" "." dir-path]
+ count (->> (p/shell count-cmd {:out :string})
+ :out
+ str/split-lines
+ (remove fs/directory?)
+ count)
+
+ size-cmd ["du" "-sh" dir-path]
+ size (-> (p/shell size-cmd {:out :string}) :out (str/trim))
+
+ tree-cmd (cond
+ (binding [u/*skip-warning* true]
+ (u/can-run? "tre"))
+ ["tre" "-c" "-l" "4" dir-path]
+ (binding [u/*skip-warning* true]
+ (u/can-run? "tree"))
+ ["tree" "-C" "-L" "4" dir-path]
+ :else
+ ["ls" "-l" "--color=auto" dir-path])
+
+ tree-out (:out (p/shell tree-cmd {:out :string}))]
+
+ ;; Print nicely
+ (println (str "πŸ“ " dir-path))
+ (println (c/green "--------------------------------"))
+ (println (c/green (format "Files: %s" count)))
+ (println (c/green (format "Size: %s" size)))
+ (println (c/green "--------------------------------"))
+ (println)
+ (println "Tree:")
+ (println tree-out)))
+
+(defn- -main [& args]
+ (let [file-or-dir (first args)]
+ (if (fs/regular-file? file-or-dir)
+ (preview-file file-or-dir)
+ (preview-dir file-or-dir))))
+
+(try
+ (apply -main *command-line-args*)
+ (catch Exception e
+ (println "Error in fzf_preview.clj, args:" *command-line-args*)
+ (throw e)))
diff --git a/mage/src/mage/be_dev.clj b/mage/src/mage/be_dev.clj
index e63608336e5..f7316ea850a 100644
--- a/mage/src/mage/be_dev.clj
+++ b/mage/src/mage/be_dev.clj
@@ -66,7 +66,9 @@
`(let [ns# (symbol ~nns)]
(require ns# :reload)
(in-ns ns#)
- (eval (read-string ~(or code "::loaded")))))
+ (eval (read-string ~(if (str/blank? code)
+ "::loaded"
+ code)))))
(defn nrepl-eval
"Evaluate Clojure code in a running nREPL server. With one arg, reads port from .nrepl-port file.
@@ -83,11 +85,12 @@
(loop []
(let [response (->> (bencode/read-bencode in)
(walk/postwalk consume))]
+ (u/debug "Response:\n-----\n" (with-out-str (pp/pprint response)) "\n-----")
+ (println)
(doseq [[k v] response]
(case k
"out" (print v)
- "err" (binding [*out* *err*]
- (print v))
+ "err" (binding [*out* *err*] (print v))
"value" (reset! final-value v)
nil)) ; Ignore other keys like session, id, status
@@ -97,17 +100,34 @@
(if (some #{"done"} (get response "status"))
(some->> @final-value
(println "\n=> "))
- (recur))))))
+ (recur))))
+ @final-value))
-(comment
+(defn nrepl-open?
+ "Checks if an nREPL server is running on the given port (or the port in .nrepl-port if none given)."
+ [& port]
+ (try
+ (let [port (nrepl-port port)
+ s (java.net.Socket. "localhost" port)]
+ (.close s)
+ true)
+ (catch Exception _ false)))
- (nrepl-eval "metabase.logger.core-test" "(do (println :!! hi) hi)" 59498)
+(defn nrepl-type [& port]
+ (try
+ (let [port (nrepl-port port)
+ type (nrepl-eval "user" "#?(:bb :bb :cljs :cljs :clj :clj)" port)]
+ (keyword type))
+ (catch Exception _ nil)))
+
+(comment
- (nrepl-eval "metabase.logger.core-test" "*ns*")
+ (nrepl-eval "metabase.logger.core-test" "(do (println :!! 'hi) 'hi)" 7888)
- (nrepl-eval "dev.migrate" "(do (rollback! :count 1) ::rollback-done)")
- (nrepl-eval "dev.migrate" "(do (migrate! :up) ::migrate-up-done)")
+ (nrepl-eval "user" "*ns*" 7888)
- (nrepl-eval "dev" "")
+ ;; run migrations from the cli:
+ (nrepl-eval "dev.migrate" "(do (rollback! :count 1) ::rollback-done)" 7888)
+ (nrepl-eval "dev.migrate" "(do (migrate! :up) ::migrate-up-done)" 7888)
- (println code-str))
+ (nrepl-eval "dev" "*ns*" 7888))
diff --git a/mage/src/mage/cli.clj b/mage/src/mage/cli.clj
index 6ba681a8574..a4b1e5e3708 100644
--- a/mage/src/mage/cli.clj
+++ b/mage/src/mage/cli.clj
@@ -74,6 +74,7 @@
(println "\n"
#_:clj-kondo/ignore
((eval usage-fn) current-task)))
+ #_{:clj-kondo/ignore [:discouraged-java-method]}
(System/exit 0))))
(defn- coerce-arguments [arg-schema current-task arguments]
@@ -92,6 +93,7 @@
" got: " (pr-str value))))
(binding [*command-line-args* ["-h"]]
(check-print-help current-task))
+ #_{:clj-kondo/ignore [:discouraged-java-method]}
(System/exit 0))))))
(defn- check-option-errors [option-errors *error-hit? summary]
@@ -104,6 +106,7 @@
(when @*error-hit?
(println "Usage:")
(println summary)
+ #_{:clj-kondo/ignore [:discouraged-java-method]}
(System/exit 0))))
(defn parse!
@@ -134,7 +137,8 @@
(u/debug (c/green "PARSED: ") parsed)
parsed)
(catch Exception e
- (println (c/red "Error: " (.getMessage e)))
+ (println (c/red "Mage CLI parsing Error:") (.getMessage e))
+ #_{:clj-kondo/ignore [:discouraged-java-method]}
(System/exit 1))))
(comment
diff --git a/mage/src/mage/quick_test_runner.clj b/mage/src/mage/quick_test_runner.clj
new file mode 100644
index 00000000000..fa87039d6d9
--- /dev/null
+++ b/mage/src/mage/quick_test_runner.clj
@@ -0,0 +1,173 @@
+(ns mage.quick-test-runner
+ (:require
+ [babashka.fs :as fs]
+ [bling.banner :refer [banner]]
+ [bling.core :as bling]
+ [bling.fonts.drippy]
+ [clojure.edn :as edn]
+ [clojure.string :as str]
+ [mage.be-dev :as backend]
+ [mage.color :as c]
+ [mage.shell :as shell]
+ [mage.util :as u]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private test-path (str u/project-root-directory "/test"))
+(def ^:private enterprise-path (str u/project-root-directory "/enterprise/backend/test/"))
+
+(defn- gather-file-tests []
+ (->> (concat
+ (fs/glob test-path "**.clj{,c}")
+ (fs/glob enterprise-path "**.clj?c"))
+ (mapv (fn [f] (str (fs/relativize u/project-root-directory f))))
+ (remove #(str/includes? % "mage"))
+ vec))
+
+(defn- gather-dir-tests
+ ([]
+ (gather-dir-tests (gather-file-tests)))
+ ([test-files]
+ (->> test-files
+ (mapv (comp str fs/parent fs/file))
+ distinct)))
+
+(defn- gather-tests-all []
+ (let [files (gather-file-tests)
+ dirs (gather-dir-tests files)]
+ (concat files dirs)))
+
+(defn- gather-tests [selecting]
+ (prn ["selecting" selecting])
+ (case selecting
+ "file" (gather-file-tests)
+ "dir" (gather-dir-tests)
+ "all" (gather-tests-all)
+ (throw
+ (ex-info ""
+ {:mage/error (str "Unknown test gathering 'selection': " (c/yellow selecting) ". "
+ "Valid options are: "
+ (c/green "file") ", " (c/green "dir") ", or " (c/green "all") ".")
+ :babashka/exit 1}))))
+
+(defn- quotify [xs]
+ (str/join " " (map #(str "\"" % "\"") xs)))
+
+(defn- run-tests-over-nrepl [test-dirs] ;; todo add dirs
+ (let [start (u/start-timer)
+ the-ns "mb.hawk.core"
+ the-cmd (str "(do (require (quote metabase.test-runner)) "
+ "((requiring-resolve 'dev.reload/reload!)) "
+ "(metabase.test-runner/find-and-run-tests-repl "
+ "{:only [" (quotify test-dirs) "]}))")]
+ (println "Running Code over nrepl:" (c/bold the-cmd))
+ (bling/callout
+ {:type :info
+ :theme :sideline-bold
+ :label-theme :marquee
+ :label "Running tests in"}
+ (str/join "\n" (map #(str " - " %) test-dirs)))
+ (let [out (backend/nrepl-eval the-ns the-cmd)
+ elapsed (u/since-ms start)]
+ (try (u/pp (edn/read-string out)) (catch Exception _ #_:clj-kondo/ignore (prn out)))
+ (println (c/green (str "Tests completed in " elapsed " ms.\n")))
+ (when (u/env "MAGE_DEBUG" (constantly nil))
+ (bling/callout {:type :positive
+ :theme :minimal
+ :label-theme :marquee
+ :label "To Rerun w/ mage -repl"} (c/cyan "mage -repl '" the-cmd "'")))
+ (bling/callout {:type :positive
+ :theme :minimal
+ :label-theme :marquee
+ :label "To Rerun Directly"}
+ (c/cyan "mage run-tests " (str/join " " test-dirs))))))
+
+;; namespaces will be converted to their file paths, so this check will work.
+(defn- check-arg [arg]
+ (or (str/includes? arg ".clj") (str/includes? arg "/")))
+
+(defn add-cljy-suffix-or-throw [partial-file-path maybe-ns]
+ (or (first
+ (keep (fn [suffix]
+ (let [file-path (str partial-file-path suffix)]
+
+ (cond (str/starts-with? maybe-ns "metabase.")
+ ;; src/metabase/...
+ (let [path (str "src/" file-path)]
+ (and (fs/exists? (str u/project-root-directory "/" path)) path))
+
+ (str/starts-with? maybe-ns "metabase-enterprise.")
+ ;; enterprise/backend/src/metabase_enterprise/...
+ (let [path (str "enterprise/backend/" file-path)]
+ (and (fs/exists? (str u/project-root-directory "/" path)) path)))))
+ [".clj" ".cljc" ".bb"]))
+ (throw
+ (ex-info "" {:mage/error (str "Could not find a file for namespace: "
+ (c/yellow partial-file-path)
+ ". Tried appending .clj, .cljs, .cljc, and .bb -- is that a real namespace?")
+ :babashka/exit 1}))))
+
+(defn maybe-convert-ns-to-filename [maybe-ns]
+ (if (or (str/starts-with? maybe-ns "metabase.")
+ (str/starts-with? maybe-ns "metabase-enterprise."))
+ (-> maybe-ns
+ str
+ (str/replace "." "/")
+ (str/replace "-" "_")
+ ;; Cannot tell from the namespace alone if it's a clj, or cljc file. :melty-face:
+ ;; Try to find the file by appending each suffix until we find one that exists:
+ (add-cljy-suffix-or-throw maybe-ns))
+ maybe-ns))
+
+(defn- setup-test-files [arguments {:keys [selecting] :as _options}]
+ (let [tests (if (seq arguments)
+ arguments
+ (-> (gather-tests selecting)
+ (u/fzf-select
+ (str/join " " ["--multi"
+ "--ansi"
+ "--marker" "'βœ“ '"
+ "--bind" "tab:toggle+up,shift-tab:toggle+down,ctrl-a:toggle-all"
+ "--header" "'TAB: toggle+up, Shift-TAB: toggle+down, C-a: toggle all, ENTER: accept'"
+ "--header-first"
+ "--header-border" "rounded"
+ "--preview" (str "'" u/project-root-directory "/mage/cmd/fzf_preview.clj {}'")]))
+ str/split-lines))
+ test-dir-or-nss (mapv maybe-convert-ns-to-filename tests)]
+ (when-not (every? check-arg test-dir-or-nss)
+ (throw (ex-info "" {:mage/error (str
+ "When providing arguments, they must be file paths or directories, got: "
+ (pr-str {:tests tests
+ :test-dir-or-ns test-dir-or-nss}))
+ :babashka/exit 1})))
+ test-dir-or-nss))
+
+(defn- run-tests-cli [test-dirs]
+ (let [cmd (str "clj -X:dev:ee:ee-dev:test :only '[" (quotify test-dirs) "]'")]
+ (bling/callout {:label "Running Command Line"} (c/bold cmd))
+ (shell/sh* "clojure" "-X:dev:dev-ee:ee:test" ":only" (str "[" (quotify test-dirs) "]"))))
+
+(defn go
+ "Interactively select directories to run tests against."
+ [{:keys [arguments options] :as _parsed}]
+ (let [tests (setup-test-files arguments options)]
+ (prn ["TESTS" tests])
+ (if (and (backend/nrepl-open?)
+ ;; No testing against the mage nrepl! (probably noone will hit this)
+ (not= :bb (backend/nrepl-type)))
+ (do
+ (println "Running tests via ⏩🏎️✨" (c/green (c/bold "THE REPL")) "✨🏎️βͺ.")
+ (run-tests-over-nrepl tests))
+ (do
+ (println "Running via " (c/bold (c/magenta "the command line")) "."
+ (c/red " This is " (c/bold "SLOW") " and " (c/bold "NOT RECCOMENDED!! "))
+ "Please consider starting a backend \nFor quicker test runs, use: " (c/magenta " clj -M:test:dev:ee:ee-dev:drivers:drivers-dev:dev-start"))
+ (println "\n" (banner
+ {:font bling.fonts.drippy/drippy
+ :text "Please open a REPL!"
+ :gradient-direction :to-top
+ :gradient-colors [:magenta :red]}))
+ (run-tests-cli tests)))))
+
+
+
diff --git a/mage/src/mage/util.clj b/mage/src/mage/util.clj
index 0c9712990ff..c07d4222937 100644
--- a/mage/src/mage/util.clj
+++ b/mage/src/mage/util.clj
@@ -150,13 +150,15 @@
(finally
(reset! done? true)))))
-(defn- without-slash [s] (str/replace s #"/$" ""))
-
-(defn pp [& xs]
+(defn pp
+ "Pretty prints args in color using puget"
+ [& xs]
(doseq [x xs] (puget/cprint x)))
-(defn pp-line [& xs]
- (doseq [x xs] (puget/cprint x {:width 10e20})))
+(defn pp-line
+ "Prints args in color, on a single line using puget. Good for Returning 'read-string'-able values."
+ [& xs]
+ (doseq [x xs] (puget/cprint x {:width 10e30})))
(defn print-tasks [& _]
(let [task+descriptions (->> "bb.edn"
@@ -165,7 +167,7 @@
edn/read-string
:tasks
(filter (fn [[task _v]] (symbol? task)))
- (sort-by (fn [[task task-data]]
+ (sort-by (fn [[task _task-data]]
(let [task-name (name task)]
(if (str/starts-with? task-name "-")
(str "z" task-name)
@@ -178,3 +180,61 @@
(println "For" (c/bold "more") "information on a task, run:")
(println " mage <task-name> -h")
task+descriptions))
+
+(def ^:dynamic *skip-warning* false)
+
+(defn can-run? [cmd]
+ (try (boolean (sh (str "command -v " cmd)))
+ (catch Exception _
+ (when-not *skip-warning*
+ (println (c/red "MAGE checked if you can run " cmd ", but it is not installed. Consider installing it for a better experience.")))
+ false)))
+
+(defn- check-run!
+ [cmd]
+ (when-not (can-run? cmd)
+ (throw
+ (ex-info
+ nil
+ {:command cmd
+ :mage/error (str "You don't have " (c/yellow cmd) " installed. Please install it to use this task.")
+ :babashka/exit 1}))))
+
+(defn fzf-select
+ "Uses fzf to offer interactive selections.
+
+ If the user doesn't have fzf installed, explains instructions
+
+ See fzf --help for more info.
+ Some useful fzf options:
+ --multi - select multiple options
+ --preview='cat {}'
+
+ Returns stdout of fzf, if you use --multi str/split-lines it."
+ [coll & [fzf-opts]]
+ (try (check-run! "fzf")
+ (catch Exception e
+ (println "You don't have fzf installed.")
+ (if (can-run? "brew")
+ (do
+ (println "Brew Detected: auto-installing it with brew...")
+ (println "Running: " (c/green "brew install fzf"))
+ (sh "brew install fzf"))
+ (throw e))))
+ (->> (shell
+ {:out :string :in (str/join "\n" coll)}
+ (str "fzf"
+ (when (seq fzf-opts) " ")
+ fzf-opts))
+ :out
+ str/trim))
+
+;; Timing functions, parallel to time function in metabase.util
+(defn start-timer
+ "Returns the current time in nanoseconds."
+ []
+ (System/nanoTime))
+
+(defn since-ms
+ "Called on the return value of start-timer, returns the elapsed time in milliseconds."
+ [timer] (/ (- (System/nanoTime) timer) 1e6))