Review Request: Validation in contrib.command-line

0 views
Skip to first unread message

Andrew Gwozdziewycz

unread,
Oct 25, 2010, 4:10:16 PM10/25/10
to clo...@googlegroups.com
Hey All,

I'd have posted this to clojure-dev if I wasn't still pending access (I'm sure the queue is large, so no worries), but, the fine folks in IRC said here would be appropriate as well.

This morning I was looking to do some command line parsing and went with clojure.contrib.command_line that chouser wrote. It's a great library, and works as expected, but command line arguments are inherently typed in certain cases, say a port number, which is one thing I was passing via the command line.

So, I've attached a patch that makes it possible to specify a validation function, which either throws an Exception or returns nil, in the case the the attribute is not valid, or returns a coerced value if it is.

Here's an example:


user=> (pp (make-map ["--port" "80" "--ok-if-foo" "foo"]
                [['port 'p "the port" 80 #(Integer/parseInt %)]
                 ['ok-if-foo 'o "only ok if foo" #(= "foo" %)]]))
{"ok-if-foo" true,  ;;; coerced to true
"" [],
:cmdspec
[[port
  p
  "the port"
  80
  #<user$eval1281$fn__1282 user$eval1281$fn__1282@7991ba7>]
 [ok-if-foo
  o
  "only ok if foo"
  #<user$eval1281$fn__1284 user$eval1281$fn__1284@6600b925>]],
"port" 80  ;;; coerced to integer 80
}

However, if we swap the arguments around --port foo --ok-if-foo 80, you see we get an "Invalid value for port"
user=> (make-map ["--port" "foo" "--ok-if-foo" "80"]                    
                 [['port 'p "the port" 80 #(Integer/parseInt %)] 
                  ['ok-if-foo 'o "only ok if foo" #(= "foo" %)]])
java.lang.Exception: Invalid value for port (NO_SOURCE_FILE:0)

And of course, it's still backwards compatible:

user=> (pp (make-map ["--verbose" "--port" "80"]
                 [['verbose? 'v? "verbose" false]
                  ['port 'p "port to listen on"]]))
{"port" "80",
 "verbose?" true,
 "" [],
 :cmdspec [[verbose? v? "verbose" false] [port p "port to listen on"]]}


I've attached the patch, and would love suggestions, feedback, criticism, etc.

Thanks,

Andrew
contrib.command-line.validation.diff
Reply all
Reply to author
Forward
0 new messages