Last active
December 16, 2015 04:39
-
-
Save letronje/5378571 to your computer and use it in GitHub Desktop.
map-to-properties.clj
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
(ns clj-prop-dump-restore.core | |
(:require [clojure.string :refer [split]] | |
[clojure.java.io :refer [reader writer]]) | |
(:import java.util.Properties)) | |
(defn- split-key | |
"Split a string key to its subparts. | |
foo -> [foo] | |
foo.bar.baz -> [foo bar baz]" | |
[k] | |
(map keyword (split k #"\."))) | |
(defn- load-props | |
"Load a properties file to a Java Properties object." | |
[props-file] | |
(doto (Properties.) | |
(.load (reader props-file)))) | |
(defn parse | |
"Parse a properties file into a Clojure datastructure." | |
[props-file] | |
(let [p (load-props props-file)] | |
(reduce (fn [init [k v]] (assoc-in init (split-key k) v)) {} p))) | |
(defn- flatten-map-to-seq | |
"Flattens a nested map into a sequence of name value pairs. Keys for nested/inner maps are based on the lookup path." | |
([key-prefix, m] | |
(mapcat (fn [[k v]] | |
(let [key-str (name k) | |
inner-prefix (if key-prefix | |
(str key-prefix "." key-str) | |
key-str)] | |
(if (map? v) | |
(flatten-map-to-seq inner-prefix v) | |
[inner-prefix v]))) | |
m)) | |
([m] | |
(flatten-map-to-seq nil m))) | |
(defn- flatten-map [m] | |
(apply hash-map (flatten-map-to-seq m))) | |
(defn dump [m, path] | |
"Dumps an arbitrarily nested map as a properties file" | |
(let [prop (Properties.)] | |
(doseq [[k v] (flatten-map m)] | |
(.setProperty prop k (str v))) | |
(.store prop (writer path) nil))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment