Skip to content

Commit

Permalink
backport src/compojure/api/help.clj
Browse files Browse the repository at this point in the history
  • Loading branch information
frenchy64 committed May 14, 2024
1 parent 6e3b5d6 commit c0c072e
Showing 1 changed file with 71 additions and 0 deletions.
71 changes: 71 additions & 0 deletions src/compojure/api/help.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
(ns compojure.api.help
(:require [schema.core :as s]
[clojure.string :as str]))

(def Topic (s/maybe s/Keyword))
(def Subject (s/maybe (s/cond-pre s/Str s/Keyword s/Symbol)))

;;
;; content formatting
;;

(defn text [& s]
(->> s
(map #(if (seq? %) (apply text %) %))
(str/join "\n")))

(defn title [& s]
(str "\u001B[32m" (text s) "\u001B[0m"))

(defn code [& s]
(str "\u001B[33m" (text s) "\u001B[0m"))

(defmulti help-for (fn [topic subject] [topic subject]) :default ::default)

(defn- subject-text [topic subject]
(text
""
(title subject)
""
(help-for topic subject)
""))

(defn- topic-text [topic]
(let [subjects (-> (methods help-for)
(dissoc ::default)
(keys)
(->> (filter #(-> % first (= topic)))))]
(text
"Topic:\n"
(title topic)
"\nSubjects:"
(->> subjects
(map (partial apply subject-text))
(map (partial str "\n"))))))

(defn- help-text []
(let [methods (dissoc (methods help-for) ::default)]
(text
"Usage:"
""
(code
"(help)"
"(help topic)"
"(help topic subject)")
"\nTopics:\n"
(title (->> methods keys (map first) (distinct) (sort)))
"\nTopics & subjects:\n"
(title (->> methods keys (map (partial str/join " ")) (sort))))))

(defmethod help-for ::default [_ _] (help-text))

(s/defn ^:always-validate help
([]
(println "------------------------------------------------------------")
(println (help-text)))
([topic :- Topic]
(println "------------------------------------------------------------")
(println (topic-text topic)))
([topic :- Topic, subject :- Subject]
(println "------------------------------------------------------------")
(println (subject-text topic subject))))

0 comments on commit c0c072e

Please sign in to comment.