Skip to content

Instantly share code, notes, and snippets.

@hlship
Created June 20, 2018 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlship/7b54f1fc3cf9c5d3ffc8e30f78f45052 to your computer and use it in GitHub Desktop.
Save hlship/7b54f1fc3cf9c5d3ffc8e30f78f45052 to your computer and use it in GitHub Desktop.
(ns extract-docs
(:require
[medley.core :refer [filter-vals]]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.edn :as edn])
(:import
(java.io PrintWriter Writer File)))
(defn full-name [k]
(if-let [n (namespace k)]
(str n "/" (name k))
(name k)))
(defn extend-name [k sep x]
(-> k full-name (str sep (name x)) keyword))
(defn extract [schema]
(let [just-description (fn [m k]
(reduce-kv (fn [m t td]
(assoc m t (:description td)))
m
(get schema k)))
add-args (fn [t]
(fn [m arg-name arg-def]
(assoc m (extend-name t "." arg-name)
(:description arg-def))))
add-fields (fn [t]
(fn [m field-name field-def]
(let [xt (extend-name t "/" field-name)]
(reduce-kv (add-args xt)
(assoc m xt (:description field-def))
(:args field-def)))))
with-fields (fn [m k]
(reduce-kv (fn [m t t-def]
(reduce-kv (add-fields t)
(assoc m t (:description t-def))
(:fields t-def)))
m
(get schema k)))
operation (fn [m k]
(reduce-kv (fn [m o o-def]
(let [ox (extend-name k "/" o)]
(reduce-kv (add-args ox)
(assoc m ox (:description o-def)) (:args o-def))))
m
(get schema k)))]
(filter-vals some?
(merge
(reduce just-description {} [:enums :unions :scalars])
(reduce with-fields {} [:objects :input-objects :interfaces])
(reduce operation {} [:queries :mutations :subscriptions])))))
(defn level [k]
(let [s (str k)]
(apply str (repeat
(+ 1
(if (str/includes? s "/") 1 0)
(if (str/includes? s ".") 1 0))
"#"))))
(defn extract-docs
[schema-path]
(let [doc-path (str/replace schema-path ".edn" ".md")
docs (-> schema-path
io/file
slurp
edn/read-string
extract)
f ^File (io/file doc-path)]
(.createNewFile f)
(with-open [w ^Writer (io/writer f)
pw (PrintWriter. w)]
(printf "Writing %,d descriptions to %s.%n"
(count docs)
doc-path)
(doseq [k (-> docs keys sort)]
(.println pw (format "%s %s\n" (level k) (full-name k)))
(.println pw (-> docs (get k) str/trim))
(.println pw)))))
(comment
(extract-docs "resources/org/example/my-schema.edn")
)
@hlship
Copy link
Author

hlship commented Jun 20, 2018

NO WARRANTY

Doesn't quite sort the output ideally.

You still have to manually edit your schema EDN file to remove all the :description keys, manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment