Skip to content

Instantly share code, notes, and snippets.

@asimjalis
Created October 23, 2015 20:00
Show Gist options
  • Save asimjalis/1ad5a039c56bffaada9e to your computer and use it in GitHub Desktop.
Save asimjalis/1ad5a039c56bffaada9e to your computer and use it in GitHub Desktop.
; Note: This script requires lein exec
; Follow instructions for installing lein and lein-exec
; Then run this as lein exec snipr.clj FILE.md
(require '[clojure.string :as str])
(require '[clojure.java.io :as io])
(defn load-script [script]
(load-file
(->> [(System/getenv "HOME") "Dropbox" "Env" "clj" script] (str/join "/"))))
(defn load-me []
(load-script "snipr.clj"))
(defn ll [] (load-me))
(defn drop-until [f coll] (drop-while (complement f) coll))
(defn take-until [f coll] (take-while (complement f) coll))
(defn extract-by-delimiters [begin? end? coll]
(lazy-seq
(when-let [coll (->> coll (drop-until begin?) seq)]
(let [head (->> coll first)
body (->> coll next (take-until end?))
block (cons head body)
remaining (->> coll next (drop-until end?))]
(cons block (extract-by-delimiters begin? end? remaining))))))
(defn java-to-package [j]
(->> j (re-find #"package\s+([\w.]+)") second))
(defn java-to-class [j]
(->> j (re-find #"(?:class|interface)\s+(\w+)") second))
(defn java-package-to-path [package]
(if (nil? package) "."
(str/replace package #"\." "/")))
(defn java-class-to-file [class]
(str class ".java"))
(defn java-to-path [j]
(let [package (java-to-package j)
class (java-to-class j)
dir (java-package-to-path package)
file (java-class-to-file class)
path (->> [dir file] (str/join "/"))]
path))
(defn java-write [j]
(let [path (java-to-path j)]
(io/make-parents path)
(spit path j)
path))
(defn markdown-java-start [s]
(and (re-find #"^```java" s)))
(defn markdown-java-end [s]
(re-find #"^```" s))
(defn lec-to-snippets [lec]
(->> lec str/split-lines
(extract-by-delimiters markdown-java-start markdown-java-end)
; Skip fence header
(map rest)
; Join lines
(map #(str/join "\n" %))))
(defn snippet-write [snippet]
(java-write snippet))
(defn lec-write [lec]
(->> lec
(lec-to-snippets)
(map snippet-write)
(doall)))
(def lec-path (->> *command-line-args* (second)))
(->> lec-path
(slurp)
(lec-write)
(map println)
(doall))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment