getopt-long.scm 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. ;;; Copyright (C) 1998, 2001, 2006 Free Software Foundation, Inc.
  2. ;;; Copyright (C) 2017,2018 Jan (janneke) Nieuwenhuizen <janneke@gnu.org>
  3. ;;;
  4. ;; This library is free software; you can redistribute it and/or
  5. ;; modify it under the terms of the GNU Lesser General Public
  6. ;; License as published by the Free Software Foundation; either
  7. ;; version 2.1 of the License, or (at your option) any later version.
  8. ;;
  9. ;; This library is distributed in the hope that it will be useful,
  10. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;; Lesser General Public License for more details.
  13. ;;
  14. ;; You should have received a copy of the GNU Lesser General Public
  15. ;; License along with this library; if not, write to the Free Software
  16. ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. ;;; Author: Russ McManus (rewritten by Thien-Thi Nguyen)
  18. ;;; (regexps removed by Jan (janneke) Nieuwenhuizen)
  19. ;;; (srfi-9 backport by Jan (janneke) Nieuwenhuizen)
  20. ;;; Commentary:
  21. ;;; This module implements some complex command line option parsing, in
  22. ;;; the spirit of the GNU C library function `getopt_long'. Both long
  23. ;;; and short options are supported.
  24. ;;;
  25. ;;; The theory is that people should be able to constrain the set of
  26. ;;; options they want to process using a grammar, rather than some arbitrary
  27. ;;; structure. The grammar makes the option descriptions easy to read.
  28. ;;;
  29. ;;; `getopt-long' is a procedure for parsing command-line arguments in a
  30. ;;; manner consistent with other GNU programs. `option-ref' is a procedure
  31. ;;; that facilitates processing of the `getopt-long' return value.
  32. ;;; (getopt-long ARGS GRAMMAR)
  33. ;;; Parse the arguments ARGS according to the argument list grammar GRAMMAR.
  34. ;;;
  35. ;;; ARGS should be a list of strings. Its first element should be the
  36. ;;; name of the program; subsequent elements should be the arguments
  37. ;;; that were passed to the program on the command line. The
  38. ;;; `program-arguments' procedure returns a list of this form.
  39. ;;;
  40. ;;; GRAMMAR is a list of the form:
  41. ;;; ((OPTION (PROPERTY VALUE) ...) ...)
  42. ;;;
  43. ;;; Each OPTION should be a symbol. `getopt-long' will accept a
  44. ;;; command-line option named `--OPTION'.
  45. ;;; Each option can have the following (PROPERTY VALUE) pairs:
  46. ;;;
  47. ;;; (single-char CHAR) --- Accept `-CHAR' as a single-character
  48. ;;; equivalent to `--OPTION'. This is how to specify traditional
  49. ;;; Unix-style flags.
  50. ;;; (required? BOOL) --- If BOOL is true, the option is required.
  51. ;;; getopt-long will raise an error if it is not found in ARGS.
  52. ;;; (value BOOL) --- If BOOL is #t, the option accepts a value; if
  53. ;;; it is #f, it does not; and if it is the symbol
  54. ;;; `optional', the option may appear in ARGS with or
  55. ;;; without a value.
  56. ;;; (predicate FUNC) --- If the option accepts a value (i.e. you
  57. ;;; specified `(value #t)' for this option), then getopt
  58. ;;; will apply FUNC to the value, and throw an exception
  59. ;;; if it returns #f. FUNC should be a procedure which
  60. ;;; accepts a string and returns a boolean value; you may
  61. ;;; need to use quasiquotes to get it into GRAMMAR.
  62. ;;;
  63. ;;; The (PROPERTY VALUE) pairs may occur in any order, but each
  64. ;;; property may occur only once. By default, options do not have
  65. ;;; single-character equivalents, are not required, and do not take
  66. ;;; values.
  67. ;;;
  68. ;;; In ARGS, single-character options may be combined, in the usual
  69. ;;; Unix fashion: ("-x" "-y") is equivalent to ("-xy"). If an option
  70. ;;; accepts values, then it must be the last option in the
  71. ;;; combination; the value is the next argument. So, for example, using
  72. ;;; the following grammar:
  73. ;;; ((apples (single-char #\a))
  74. ;;; (blimps (single-char #\b) (value #t))
  75. ;;; (catalexis (single-char #\c) (value #t)))
  76. ;;; the following argument lists would be acceptable:
  77. ;;; ("-a" "-b" "bang" "-c" "couth") ("bang" and "couth" are the values
  78. ;;; for "blimps" and "catalexis")
  79. ;;; ("-ab" "bang" "-c" "couth") (same)
  80. ;;; ("-ac" "couth" "-b" "bang") (same)
  81. ;;; ("-abc" "couth" "bang") (an error, since `-b' is not the
  82. ;;; last option in its combination)
  83. ;;;
  84. ;;; If an option's value is optional, then `getopt-long' decides
  85. ;;; whether it has a value by looking at what follows it in ARGS. If
  86. ;;; the next element is does not appear to be an option itself, then
  87. ;;; that element is the option's value.
  88. ;;;
  89. ;;; The value of a long option can appear as the next element in ARGS,
  90. ;;; or it can follow the option name, separated by an `=' character.
  91. ;;; Thus, using the same grammar as above, the following argument lists
  92. ;;; are equivalent:
  93. ;;; ("--apples" "Braeburn" "--blimps" "Goodyear")
  94. ;;; ("--apples=Braeburn" "--blimps" "Goodyear")
  95. ;;; ("--blimps" "Goodyear" "--apples=Braeburn")
  96. ;;;
  97. ;;; If the option "--" appears in ARGS, argument parsing stops there;
  98. ;;; subsequent arguments are returned as ordinary arguments, even if
  99. ;;; they resemble options. So, in the argument list:
  100. ;;; ("--apples" "Granny Smith" "--" "--blimp" "Goodyear")
  101. ;;; `getopt-long' will recognize the `apples' option as having the
  102. ;;; value "Granny Smith", but it will not recognize the `blimp'
  103. ;;; option; it will return the strings "--blimp" and "Goodyear" as
  104. ;;; ordinary argument strings.
  105. ;;;
  106. ;;; The `getopt-long' function returns the parsed argument list as an
  107. ;;; assocation list, mapping option names --- the symbols from GRAMMAR
  108. ;;; --- onto their values, or #t if the option does not accept a value.
  109. ;;; Unused options do not appear in the alist.
  110. ;;;
  111. ;;; All arguments that are not the value of any option are returned
  112. ;;; as a list, associated with the empty list.
  113. ;;;
  114. ;;; `getopt-long' throws an exception if:
  115. ;;; - it finds an unrecognized property in GRAMMAR
  116. ;;; - the value of the `single-char' property is not a character
  117. ;;; - it finds an unrecognized option in ARGS
  118. ;;; - a required option is omitted
  119. ;;; - an option that requires an argument doesn't get one
  120. ;;; - an option that doesn't accept an argument does get one (this can
  121. ;;; only happen using the long option `--opt=value' syntax)
  122. ;;; - an option predicate fails
  123. ;;;
  124. ;;; So, for example:
  125. ;;;
  126. ;;; (define grammar
  127. ;;; `((lockfile-dir (required? #t)
  128. ;;; (value #t)
  129. ;;; (single-char #\k)
  130. ;;; (predicate ,file-is-directory?))
  131. ;;; (verbose (required? #f)
  132. ;;; (single-char #\v)
  133. ;;; (value #f))
  134. ;;; (x-includes (single-char #\x))
  135. ;;; (rnet-server (single-char #\y)
  136. ;;; (predicate ,string?))))
  137. ;;;
  138. ;;; (getopt-long '("my-prog" "-vk" "/tmp" "foo1" "--x-includes=/usr/include"
  139. ;;; "--rnet-server=lamprod" "--" "-fred" "foo2" "foo3")
  140. ;;; grammar)
  141. ;;; => ((() "foo1" "-fred" "foo2" "foo3")
  142. ;;; (rnet-server . "lamprod")
  143. ;;; (x-includes . "/usr/include")
  144. ;;; (lockfile-dir . "/tmp")
  145. ;;; (verbose . #t))
  146. ;;; (option-ref OPTIONS KEY DEFAULT)
  147. ;;; Return value in alist OPTIONS using KEY, a symbol; or DEFAULT if not
  148. ;;; found. The value is either a string or `#t'.
  149. ;;;
  150. ;;; For example, using the `getopt-long' return value from above:
  151. ;;;
  152. ;;; (option-ref (getopt-long ...) 'x-includes 42) => "/usr/include"
  153. ;;; (option-ref (getopt-long ...) 'not-a-key! 31) => 31
  154. ;;; Code:
  155. (define-module (mes getopt-long)
  156. #:use-module (ice-9 optargs)
  157. #:use-module (srfi srfi-1)
  158. #:use-module (srfi srfi-9)
  159. #:export (getopt-long option-ref))
  160. (define-record-type option-spec
  161. (%make-option-spec name value required? option-spec->single-char predicate value-policy)
  162. option-spec?
  163. (name
  164. option-spec->name set-option-spec-name!)
  165. (value
  166. option-spec->value set-option-spec-value!)
  167. (required?
  168. option-spec->required? set-option-spec-required?!)
  169. (option-spec->single-char
  170. option-spec->single-char set-option-spec-single-char!)
  171. (predicate
  172. option-spec->predicate set-option-spec-predicate!)
  173. (value-policy
  174. option-spec->value-policy set-option-spec-value-policy!))
  175. (define (make-option-spec name)
  176. (%make-option-spec name #f #f #f #f #f))
  177. (define (parse-option-spec desc)
  178. (let ((spec (make-option-spec (symbol->string (car desc)))))
  179. (for-each (lambda (desc-elem)
  180. (let ((given (lambda () (cadr desc-elem))))
  181. (case (car desc-elem)
  182. ((required?)
  183. (set-option-spec-required?! spec (given)))
  184. ((value)
  185. (set-option-spec-value-policy! spec (given)))
  186. ((single-char)
  187. (or (char? (given))
  188. (error "`single-char' value must be a char!"))
  189. (set-option-spec-single-char! spec (given)))
  190. ((predicate)
  191. (set-option-spec-predicate!
  192. spec ((lambda (pred)
  193. (lambda (name val)
  194. (or (not val)
  195. (pred val)
  196. (error "option predicate failed:" name))))
  197. (given))))
  198. (else
  199. (error "invalid getopt-long option property:"
  200. (car desc-elem))))))
  201. (cdr desc))
  202. spec))
  203. (define (split-arg-list argument-list)
  204. ;; Scan ARGUMENT-LIST for "--" and return (BEFORE-LS . AFTER-LS).
  205. ;; Discard the "--". If no "--" is found, AFTER-LS is empty.
  206. (let loop ((yes '()) (no argument-list))
  207. (cond ((null? no) (cons (reverse yes) no))
  208. ((string=? "--" (car no)) (cons (reverse yes) (cdr no)))
  209. (else (loop (cons (car no) yes) (cdr no))))))
  210. (define (expand-clumped-singles opt-ls)
  211. ;; example: ("--xyz" "-abc5d") => ("--xyz" "-a" "-b" "-c" "5d")
  212. (let loop ((opt-ls opt-ls) (ret-ls '()))
  213. (cond ((null? opt-ls)
  214. (reverse ret-ls)) ;;; retval
  215. ((let ((opt (car opt-ls)))
  216. (and (eq? (string-ref opt 0) #\-)
  217. (> (string-length opt) 1)
  218. (char-alphabetic? (string-ref opt 1))))
  219. (let* ((opt (car opt-ls))
  220. (n (char->integer (string-ref opt 1)))
  221. (sub (substring opt 1 (string-length opt)))
  222. (end (string-index (substring opt 1 (string-length opt)) (negate char-alphabetic?)))
  223. (end (if end (1+ end) (string-length opt)))
  224. (singles-string (substring opt 1 end))
  225. (singles (reverse
  226. (map (lambda (c)
  227. (string-append "-" (make-string 1 c)))
  228. (string->list singles-string))))
  229. (extra (substring opt end)))
  230. (loop (cdr opt-ls)
  231. (append (if (string=? "" extra)
  232. singles
  233. (cons extra singles))
  234. ret-ls))))
  235. (else (loop (cdr opt-ls)
  236. (cons (car opt-ls) ret-ls))))))
  237. (define (looks-like-an-option string)
  238. (eq? (string-ref string 0) #\-))
  239. (define (process-options specs argument-ls stop-at-first-non-option)
  240. ;; Use SPECS to scan ARGUMENT-LS; return (FOUND . ETC).
  241. ;; FOUND is an unordered list of option specs for found options, while ETC
  242. ;; is an order-maintained list of elements in ARGUMENT-LS that are neither
  243. ;; options nor their values.
  244. (let ((idx (map (lambda (spec)
  245. (cons (option-spec->name spec) spec))
  246. specs))
  247. (sc-idx (map (lambda (spec)
  248. (cons (make-string 1 (option-spec->single-char spec))
  249. spec))
  250. (filter option-spec->single-char specs))))
  251. (let loop ((argument-ls argument-ls) (found '()) (etc '()))
  252. (let ((eat! (lambda (spec ls)
  253. (let ((val!loop (lambda (val n-ls n-found n-etc)
  254. (set-option-spec-value!
  255. spec
  256. ;; handle multiple occurrances
  257. (cond ((option-spec->value spec)
  258. => (lambda (cur)
  259. ((if (list? cur) cons list)
  260. val cur)))
  261. (else val)))
  262. (loop n-ls n-found n-etc)))
  263. (ERR:no-arg (lambda ()
  264. (error (string-append
  265. "option must be specified"
  266. " with argument:")
  267. (option-spec->name spec)))))
  268. (cond
  269. ((eq? 'optional (option-spec->value-policy spec))
  270. (if (or (null? (cdr ls))
  271. (looks-like-an-option (cadr ls)))
  272. (val!loop #t
  273. (cdr ls)
  274. (cons spec found)
  275. etc)
  276. (val!loop (cadr ls)
  277. (cddr ls)
  278. (cons spec found)
  279. etc)))
  280. ((eq? #t (option-spec->value-policy spec))
  281. (if (or (null? (cdr ls))
  282. (looks-like-an-option (cadr ls)))
  283. (ERR:no-arg)
  284. (val!loop (cadr ls)
  285. (cddr ls)
  286. (cons spec found)
  287. etc)))
  288. (else
  289. (val!loop #t
  290. (cdr ls)
  291. (cons spec found)
  292. etc)))))))
  293. (if (null? argument-ls)
  294. (cons found (reverse etc)) ;;; retval
  295. (cond ((let ((opt (car argument-ls)))
  296. (and (eq? (string-ref opt 0) #\-)
  297. (> (string-length opt) 1)
  298. (let ((n (char->integer (string-ref opt 1))))
  299. (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z)))
  300. (and (>= n (char->integer #\a)) (<= n (char->integer #\z)))))))
  301. (let* ((c (substring (car argument-ls) 1 2))
  302. (spec (or (assoc-ref sc-idx c)
  303. (error "no such option:" (car argument-ls)))))
  304. (eat! spec argument-ls)))
  305. ((let ((opt (car argument-ls)))
  306. (and (string-prefix? "--" opt)
  307. (let ((n (char->integer (string-ref opt 2))))
  308. (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z)))
  309. (and (>= n (char->integer #\a)) (<= n (char->integer #\z)))))
  310. (not (string-index opt #\space))
  311. (not (string-index opt #\=))))
  312. (let* ((opt (substring (car argument-ls) 2))
  313. (spec (or (assoc-ref idx opt)
  314. (error "no such option:" (car argument-ls)))))
  315. (eat! spec argument-ls)))
  316. ((let ((opt (car argument-ls)))
  317. (and (string-prefix? "--" opt)
  318. (let ((n (char->integer (string-ref opt 2))))
  319. (or (and (>= n (char->integer #\A)) (<= n (char->integer #\Z)))
  320. (and (>= n (char->integer #\a)) (<= n (char->integer #\z)))))
  321. (or (string-index opt #\=)
  322. (string-index opt #\space))))
  323. (let* ((is (or (string-index (car argument-ls) #\=)
  324. (string-index (car argument-ls) #\space)))
  325. (opt (substring (car argument-ls) 2 is))
  326. (spec (or (assoc-ref idx opt)
  327. (error "no such option:" (substring opt is)))))
  328. (if (option-spec->value-policy spec)
  329. (eat! spec (append
  330. (list 'ignored
  331. (substring (car argument-ls) (1+ is)))
  332. (cdr argument-ls)))
  333. (error "option does not support argument:"
  334. opt))))
  335. (stop-at-first-non-option
  336. (cons found (append (reverse etc) argument-ls)))
  337. (else
  338. (loop (cdr argument-ls)
  339. found
  340. (cons (car argument-ls) etc)))))))))
  341. (define* (getopt-long program-arguments option-desc-list #:key stop-at-first-non-option)
  342. "Process options, handling both long and short options, similar to
  343. the glibc function 'getopt_long'. PROGRAM-ARGUMENTS should be a value
  344. similar to what (program-arguments) returns. OPTION-DESC-LIST is a
  345. list of option descriptions. Each option description must satisfy the
  346. following grammar:
  347. <option-spec> :: (<name> . <attribute-ls>)
  348. <attribute-ls> :: (<attribute> . <attribute-ls>)
  349. | ()
  350. <attribute> :: <required-attribute>
  351. | <arg-required-attribute>
  352. | <single-char-attribute>
  353. | <predicate-attribute>
  354. | <value-attribute>
  355. <required-attribute> :: (required? <boolean>)
  356. <single-char-attribute> :: (single-char <char>)
  357. <value-attribute> :: (value #t)
  358. (value #f)
  359. (value optional)
  360. <predicate-attribute> :: (predicate <1-ary-function>)
  361. The procedure returns an alist of option names and values. Each
  362. option name is a symbol. The option value will be '#t' if no value
  363. was specified. There is a special item in the returned alist with a
  364. key of the empty list, (): the list of arguments that are not options
  365. or option values.
  366. By default, options are not required, and option values are not
  367. required. By default, single character equivalents are not supported;
  368. if you want to allow the user to use single character options, you need
  369. to add a `single-char' clause to the option description."
  370. (let* ((specifications (map parse-option-spec option-desc-list))
  371. (pair (split-arg-list (cdr program-arguments) ))
  372. (split-ls (expand-clumped-singles (car pair)))
  373. (non-split-ls (cdr pair))
  374. (found/etc (process-options specifications split-ls
  375. stop-at-first-non-option))
  376. (found (car found/etc))
  377. (rest-ls (append (cdr found/etc) non-split-ls)))
  378. (for-each (lambda (spec)
  379. (let ((name (option-spec->name spec))
  380. (val (option-spec->value spec)))
  381. (and (option-spec->required? spec)
  382. (or (memq spec found)
  383. (error "option must be specified:" name)))
  384. (and (memq spec found)
  385. (eq? #t (option-spec->value-policy spec))
  386. (or val
  387. (error "option must be specified with argument:"
  388. name)))
  389. (let ((pred (option-spec->predicate spec)))
  390. (and pred (pred name val)))))
  391. specifications)
  392. (cons (cons '() rest-ls)
  393. (let ((multi-count (map (lambda (desc)
  394. (cons (car desc) 0))
  395. option-desc-list)))
  396. (map (lambda (spec)
  397. (let ((name (string->symbol (option-spec->name spec))))
  398. (cons name
  399. ;; handle multiple occurrances
  400. (let ((maybe-ls (option-spec->value spec)))
  401. (if (list? maybe-ls)
  402. (let* ((look (assq name multi-count))
  403. (idx (cdr look))
  404. (val (list-ref maybe-ls idx)))
  405. (set-cdr! look (1+ idx)) ; ugh!
  406. val)
  407. maybe-ls)))))
  408. found)))))
  409. (define (option-ref options key default)
  410. "Return value in alist OPTIONS using KEY, a symbol; or DEFAULT if not found.
  411. The value is either a string or `#t'."
  412. (or (assq-ref options key) default))
  413. ;;; getopt-long.scm ends here