Created
May 7, 2012 22:16
-
-
Save zerowidth/2630906 to your computer and use it in GitHub Desktop.
clojure test for https://github.com/KeeperPat/music-yaml-parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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