]> git.jsancho.org Git - guile-click.git/blob - click/args.scm
WIP: Nested commands
[guile-click.git] / click / args.scm
1 ;;; Click --- Command Line Interface Creation Kit for GNU Guile
2 ;;; Copyright © 2021 Javier Sancho <jsf@jsancho.org>
3 ;;;
4 ;;; This file is part of Click.
5 ;;;
6 ;;; Click is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or
9 ;;; (at your option) any later version.
10 ;;;
11 ;;; Click is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 ;;; General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with Click.  If not, see <http://www.gnu.org/licenses/>.
18
19
20 (define-module (click args)
21   #:use-module (ice-9 getopt-long)
22   #:use-module (ice-9 readline)
23   #:use-module (click util)
24   #:export (get-option-default-value
25             get-values
26             parse-args))
27
28
29 (define (parse-args args click-option-spec)
30   "Parse args using an option-spec click formatted"
31   (let ((values (getopt-long args
32                              (getopt-long-option-spec click-option-spec)
33                              #:stop-at-first-non-option #t)))
34     values))
35
36
37 (define (get-values option-spec values)
38   "Return an associated list with values for all the options in option-spec"
39   (cond ((null? option-spec)
40          '())
41         (else
42          (let* ((option (car option-spec))
43                 (option-name (car option))
44                 (value (get-normalized-value values option option-name)))
45            (cons (cons option-name value)
46                  (get-values (cdr option-spec) values))))))
47
48
49 (define (get-normalized-value values option option-name)
50   "Get value for option, converting from string to the appropriate value"
51   (let ((convert-proc (assoc-ref (option-type option) 'convert))
52         (value (option-ref values option-name #f)))
53     (cond ((and value (not (option-property option 'flag)))
54            (convert-proc value))
55           (value
56            value)
57           (else
58            (get-option-default-value option)))))
59
60
61 (define* (get-option-default-value option #:optional (no-prompt #f))
62   "Get default value for option, asking user if prompt property is set"
63   (let ((default (option-property option 'default)))
64     (if (not default)
65         (let ((prompt (option-property option 'prompt)))
66           (if prompt
67               (readline (format #f "~a: " prompt))
68               default))
69         default)))