Skip to content

Instantly share code, notes, and snippets.

@jmglov
Created December 10, 2015 09:41
Show Gist options
  • Save jmglov/633ab44ea89ff8720c81 to your computer and use it in GitHub Desktop.
Save jmglov/633ab44ea89ff8720c81 to your computer and use it in GitHub Desktop.
Basic command-line arguments parser for Pixie
#!/usr/bin/env pxi
(ns cli
"pxi cli.pxi --verbose --bar 42 --hello 'world!'
{:verbose true, :bar 42, :hello world!}"
(:require [pixie.string :as string]))
(defn- arg?
"Returns true if the string is an argument to an option"
[s]
(and s (not (string/starts-with? s "--"))))
(defn- ->key [opt]
(-> opt
(string/replace-first "--" "")
keyword))
(defn- ->val [opt arg numeric-opts]
(if (contains? numeric-opts (->key opt))
(read-string arg)
arg))
(defn parse-args
([args] (parse-args args {} #{}))
([args default-cfg numeric-opts]
(merge default-cfg
(loop [cfg {}
args args]
(let [[opt arg & args] args]
(if (nil? opt)
cfg
(if (arg? arg)
(recur (assoc cfg (->key opt) (->val opt arg numeric-opts)) args)
(recur (assoc cfg (->key opt) true) (cons arg args)))))))))
(println (parse-args program-arguments))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment