This repository has been archived by the owner on Nov 23, 2021. It is now read-only.
/
core.clj
73 lines (64 loc) · 2.21 KB
/
core.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
(ns clj-md2pdf.core
(:require [clojure.java.io :as io]
[clojure.set :refer [rename-keys]]
[clojure.spec.alpha :as spec]
[clj-md2pdf.render :as renderer]
[markdown-to-hiccup.core :refer [file->hiccup hiccup-in]]))
(def spec-pdf (spec/and string? #(re-matches #"^.*\.pdf$" %)))
(def spec-md (spec/and string? #(re-matches #"^.*\.md$" %)))
(def spec-edn (spec/and string? #(re-matches #"^.*\.edn$" %)))
(def spec-edn-options (spec/map-of keyword? spec-edn))
(defn get-body-contents
[hiccup]
(->> (hiccup-in hiccup :body)
(drop 2)))
(defn hiccup-out
[hiccup]
(->> hiccup
(into [:body {}])
(conj [:html {} [:head {}]])))
(defn update-debug
[options]
(if (nil? (:debug options))
options
(update options :debug #(hash-map :display-html? %
:display-options? %))))
(defn parse-edn-opts
[edn-options]
(assert (spec/valid? spec-edn-options edn-options)
"Invalid EDN files found.")
edn-options)
(defn read-options
[options]
(let [option-attrs (->> [:doc :page :styles :watermark :objects]
(select-keys options)
(parse-edn-opts)
(reduce-kv #(assoc %1 %2 ((comp read-string slurp) %3)) {})
(into (select-keys options [:debug :logging])))]
(-> option-attrs
(rename-keys {:logging :logging?})
(update-debug))))
(defn read-md
"Reads the markdown file(s) into hiccup data structures."
[in & ins]
(assert (and (spec/valid? spec-md in)
(every? #(spec/valid? spec-md %) ins))
"Invalid markdown files found.")
(->> (into [in] ins)
(mapcat (comp get-body-contents file->hiccup))
(hiccup-out)))
(defn ->pdf
"Wrapper for `->pdf` in `renderer` which creates parent directories
if non-existant."
[hiccup out options]
(assert (spec/valid? spec-pdf out) "PDF filename invalid.")
(io/make-parents out)
(if (empty? options)
(renderer/->pdf hiccup out)
(renderer/->pdf hiccup out options)))
(defn gen-pdf-from-files
[out ins options]
(let [hiccup (apply read-md ins)]
(->> options
(read-options)
(->pdf hiccup out))))