Created
December 10, 2015 09:41
-
-
Save jmglov/633ab44ea89ff8720c81 to your computer and use it in GitHub Desktop.
Basic command-line arguments parser for Pixie
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
#!/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