Skip to content

Instantly share code, notes, and snippets.

@ghoseb ghoseb/props.clj
Last active Dec 16, 2015

Embed
What would you like to do?
A simple problem that I solved at the April '13 meetup of Pune Clojure Users' Group. The problem is about parsing a Java properties file into Clojure & back.
(ns props.core
(:require [clojure.string :refer [split]]
[clojure.java.io :refer [reader]])
(: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)))
;;; Example:
;;; (parse "sample.properties")
;;; => {:ring {:handler {:protocol "binary", :ns "some-ring-handler-ns"}},
;;; :name "configuration-clj",
;;; :db {:host "example.org", :name "whacko-db", :port "4567"},
;;; :version "0.2.4"}
;;; HOMEWORK: Write function dump that'll do the opposite of parse.
name = configuration-clj
version = 0.2.4
db.name = whacko-db
db.host = example.org
db.port = 4567
ring.handler.ns = some-ring-handler-ns
ring.handler.protocol = binary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.