Skip to content

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

mage: Replace blank lines with empty strings + mage ls (#61987)

bryanba8f1f3ccf3c
diff --git a/bb.edn b/bb.edn
index 7b6650f6aca..b8c92b31bac 100644
--- a/bb.edn
+++ b/bb.edn
@@ -156,6 +156,11 @@
:requires [[mage.stats-repl :as stats-repl]]
:task (stats-repl/connect (cli/parse! (current-task)))}
+ 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:
;; These tasks are more for internal tooling, e.g. for use from git hooks etc.
@@ -260,4 +265,11 @@
{:doc "Print a day's PR summary for the metabase/metabase repo"
:requires [[mage.escherize.pr-summary :as eps]]
:examples [["./bin/mage -escherize-pr-summary | pbcopy" "Copy your daily"]]
- :task (task! (eps/summarize-prs parsed))}}}
+ :task (task! (eps/summarize-prs parsed))}
+
+ -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"]]
+ :arg-schema [:sequential [:string {:description "Glob pattern to match files"}]]
+ :task (task! (fix-whitespace/run-clean parsed))}}}
diff --git a/mage/mage/escherize/fix_whitespace.clj b/mage/mage/escherize/fix_whitespace.clj
new file mode 100644
index 00000000000..8175910b3a1
--- /dev/null
+++ b/mage/mage/escherize/fix_whitespace.clj
@@ -0,0 +1,97 @@
+(ns mage.escherize.fix-whitespace
+ (:require
+ [babashka.fs :as fs]
+ [clojure.string :as str]
+ [mage.color :as c]
+ [mage.util :as u])
+ (:import [java.util.concurrent Callable Executors TimeUnit]))
+
+(set! *warn-on-reflection* true)
+
+(defn- clean-whitespace-lines
+ "Remove lines that contain only whitespace characters"
+ [file-path]
+ (try
+ (let [original-lines (str/split-lines (slurp file-path))
+ cleaned-lines (map #(if (re-matches #"^\s*$" %) "" %) original-lines)
+ changes-made? (not= original-lines cleaned-lines)]
+ (when changes-made?
+ (spit file-path (str/join "\n" cleaned-lines)))
+ {:file file-path
+ :changed changes-made?
+ :error nil})
+ (catch Exception e
+ {:file file-path
+ :changed false
+ :error (str e)})))
+
+(defn- find-files-from-glob
+ "Find files matching the glob pattern"
+ [glob-pattern]
+ (->> (fs/glob u/project-root-directory glob-pattern)
+ (filter fs/regular-file?)
+ (map str)
+ distinct))
+
+(defn- clamp "Clamp n to the range [lo, hi]." [n lo hi] (max lo (min hi n)))
+(def ^:private pool-size (clamp (* 2 (.availableProcessors (Runtime/getRuntime))) 4 32))
+
+(defn- process-files
+ "Process all files and clean whitespace-only lines using thread pool"
+ [files]
+ (let [_ (u/debug (c/yellow "Using thread pool size: " pool-size))
+ executor (Executors/newFixedThreadPool pool-size)]
+ (try
+ (let [callables (mapv (fn [f] #(clean-whitespace-lines f)) files)
+ futures (.invokeAll executor callables)
+ results (mapv deref futures)
+ changed-files (filter :changed results)
+ error-files (filter :error results)]
+
+ ;; Report errors
+ (doseq [{:keys [file error]} error-files]
+ (println (c/red "Error processing " file ": " error)))
+
+ ;; Report changes
+ (doseq [{:keys [file]} changed-files]
+ (println (c/green "Cleaned: " file)))
+
+ {:total-files (count files)
+ :changed-files (count changed-files)
+ :error-files (count error-files)})
+ (finally
+ (.shutdown executor)
+ (.awaitTermination executor 10 TimeUnit/SECONDS)))))
+
+(defn run-clean
+ "Main entry point for whitespace cleaning"
+ [{:keys [arguments]}]
+ (when (empty? arguments)
+ (throw (ex-info
+ nil
+ {:mage/error (c/yellow "Please specify a glob pattern, e.g.: **/*.clj")
+ :babashka/exit 1})))
+
+ (let [start-time (System/nanoTime)
+ glob-pattern (first arguments)
+ files (find-files-from-glob glob-pattern)
+ _ (println "Found" (c/yellow (count files)) "files matching pattern:" (c/cyan glob-pattern))
+ {:keys [total-files changed-files error-files]} (process-files files)
+ duration-ms (/ (- (System/nanoTime) start-time) 1e6)]
+
+ (println "Completed in:" (format "%.0f" duration-ms) "ms")
+ (println "Files processed:" (c/yellow total-files))
+ (println "Files changed: " ((if (zero? changed-files) c/green c/yellow) changed-files))
+ (when (> error-files 0)
+ (println "Files with errors:" (c/red error-files)))
+
+ (if (zero? error-files)
+ (println (c/green "OK: Whitespace cleaning completed successfully."))
+ (throw (ex-info nil
+ {:mage/error (str (c/red "Errors occurred during processing."))
+ :babashka/exit 1})))))
+
+;; Usage examples:
+;; (run-clean {:arguments ["**/*.clj"]}) ; Clean all .clj files
+;; (run-clean {:arguments ["src/**/*.cljs"]}) ; Clean .cljs files in src/
+;; (run-clean {:arguments ["**/*.{clj,cljs,cljc}"]}) ; Clean all Clojure files
diff --git a/mage/mage/util.clj b/mage/mage/util.clj
index 38b6fb39858..73b32d91ffa 100644
--- a/mage/mage/util.clj
+++ b/mage/mage/util.clj
@@ -6,7 +6,8 @@
[clojure.java.io :as io]
[clojure.string :as str]
[mage.color :as c]
- [puget.printer :as puget]))
+ [puget.printer :as puget]
+ [table.core :as table]))
(set! *warn-on-reflection* true)
@@ -155,3 +156,24 @@
(defn pp-line [& xs]
(doseq [x xs] (puget/cprint x {:width 10e20})))
+
+(defn print-tasks [& _]
+ (let [task+descriptions (->> "bb.edn"
+ (str project-root-directory "/")
+ slurp
+ edn/read-string
+ :tasks
+ (filter (fn [[task _v]] (symbol? task)))
+ (sort-by (fn [[task task-data]]
+ (let [task-name (name task)]
+ (if (str/starts-with? task-name "-")
+ (str "z" task-name)
+ task-name))))
+ (map (fn [[task task-data]]
+ {:task (name task)
+ :description (:doc task-data)})))]
+ (println "Available" (c/bold ((rand-nth [c/red c/blue c/green]) "Mage")) "Tasks:")
+ (table/table task+descriptions :style :unicode)
+ (println "For" (c/bold "more") "information on a task, run:")
+ (println " mage <task-name> -h")
+ task+descriptions))