Skip to content

Instantly share code, notes, and snippets.

@ghoseb
Last active December 16, 2015 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghoseb/5373212 to your computer and use it in GitHub Desktop.
Save ghoseb/5373212 to your computer and use it in GitHub Desktop.
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