Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created May 7, 2012 22:16
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 zerowidth/2630906 to your computer and use it in GitHub Desktop.
Save zerowidth/2630906 to your computer and use it in GitHub Desktop.
(defn depth-of [line]
(count ((re-find #"^([\s-]*)" line) 1)))
(defn list-depth [line]
(count ((re-find #"^(\s*)" line) 1)))
(declare parse-list)
(defn parse-hash [lines]
(when-let [line (first lines)]
(let [depth (depth-of line)
children (take-while #(> (depth-of %) depth) (rest lines))
remainder (drop (count children) (rest lines))
[k v] (map str/trim (str/split (.substring line depth) #":"))]
(conj
{}
(if (> (count children) 0)
[k (parse-list children)]
[k v])
(parse-hash remainder)))))
(defn parse-list [lines]
(when-let [line (first lines)]
(let [ld (list-depth line)
children (take-while #(> (list-depth %) ld) (rest lines))
remainder (drop (count children) (rest lines))]
(cons
(parse-hash (cons line children))
(parse-list remainder)))))
(defn parse-file [filename] (-> filename slurp str/split-lines parse-hash))
(-> (parse-file "music.yaml")
(get "genres") last
(get "artists") first
(get "albums") first
(get "tracks") last
(get "name")) ; => "But Not For Me"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment