]> git.jsancho.org Git - guile-click.git/blob - click/util.scm
e83e15319a915d16cb43e2ab4cfc14efe207126b
[guile-click.git] / click / util.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 util)
21   #:use-module (ice-9 getopt-long)
22   #:use-module (ice-9 readline)
23   #:use-module (click constant)
24   #:export (getopt-long-option-spec
25             get-option-default-value
26             get-values
27             option-default-value
28             option-property
29             program-name
30             %program-name))
31
32
33 (define %program-name (make-fluid "guile"))
34 (define (program-name)
35   (fluid-ref %program-name))
36
37 (define (getopt-long-option-spec option-spec)
38   (map (lambda (option)
39          (cons (car option)
40                (cons (list 'value (not (option-property option 'flag)))
41                      (filter (lambda (property)
42                                (not (memq (car property) CLICK_PROPERTIES)))
43                              (cdr option)))))
44        option-spec))
45
46 (define* (option-property option property-name #:optional (default #f))
47   (let ((property (assq property-name (cdr option))))
48     (if property
49         (cadr property)
50         default)))
51
52 (define (get-values option-spec values)
53   "Return an associated list with values for all the options in option-spec"
54   (cond ((null? option-spec)
55          '())
56         (else
57          (let* ((option (car option-spec))
58                 (option-name (car option))
59                 (value (or (option-ref values option-name #f)
60                            (get-option-default-value option))))
61            (cons (cons option-name value)
62                  (get-values (cdr option-spec) values))))))
63
64
65 (define* (get-option-default-value option #:optional (no-prompt #f))
66   "Get value for option, asking user if prompt property is set"
67   (let ((default (option-property option 'default)))
68     (if (not default)
69         (let ((prompt (option-property option 'prompt)))
70           (if prompt
71               (readline (format #f "~a: " prompt))
72               default))
73         default)))