]> git.jsancho.org Git - guile-click.git/blob - click/util.scm
Type conversion
[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 (click constant)
22   #:export (getopt-long-option-spec
23             option-property
24             option-type
25             program-name
26             %program-name))
27
28
29 (define %program-name (make-fluid "guile"))
30 (define (program-name)
31   (fluid-ref %program-name))
32
33
34 (define (getopt-long-option-spec option-spec)
35   "Transform click option spec into getopt-long format"
36   (map (lambda (option)
37          (cons (car option)
38                (cons (list 'value (not (option-property option 'flag)))
39                      (filter (lambda (property)
40                                (not (memq (car property) CLICK_PROPERTIES)))
41                              (cdr option)))))
42        option-spec))
43
44
45 (define* (option-property option property-name #:optional (default #f))
46   "Return the option property with a given name"
47   (let ((property (assq property-name (cdr option))))
48     (if property
49         (cadr property)
50         default)))
51
52
53 ;; Types
54 (define TYPE-TEXT
55   `((description . "TEXT")
56     (convert . ,identity)))
57 (define TYPE-INTEGER
58   `((description . "INTEGER")
59     (convert . ,string->number)))
60 (define TYPE-NUMBER
61   `((description . "NUMBER")
62     (convert . ,string->number)))
63
64 (define (option-type option)
65   "Return allowed type for the value in the option"
66   (let ((default (option-property option 'default)))
67     (cond ((not default)
68            TYPE-TEXT)
69           ((integer? default)
70            TYPE-INTEGER)
71           ((number? default)
72            TYPE-NUMBER)
73           (else
74            TYPE-TEXT))))