]> git.jsancho.org Git - guile-click.git/blobdiff - click/args.scm
WIP: Nested commands
[guile-click.git] / click / args.scm
diff --git a/click/args.scm b/click/args.scm
new file mode 100644 (file)
index 0000000..b59914d
--- /dev/null
@@ -0,0 +1,69 @@
+;;; Click --- Command Line Interface Creation Kit for GNU Guile
+;;; Copyright © 2021 Javier Sancho <jsf@jsancho.org>
+;;;
+;;; This file is part of Click.
+;;;
+;;; Click is free software; you can redistribute it and/or modify it
+;;; under the terms of the GNU General Public License as published by
+;;; the Free Software Foundation; either version 3 of the License, or
+;;; (at your option) any later version.
+;;;
+;;; Click is distributed in the hope that it will be useful, but
+;;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;;; General Public License for more details.
+;;;
+;;; You should have received a copy of the GNU General Public License
+;;; along with Click.  If not, see <http://www.gnu.org/licenses/>.
+
+
+(define-module (click args)
+  #:use-module (ice-9 getopt-long)
+  #:use-module (ice-9 readline)
+  #:use-module (click util)
+  #:export (get-option-default-value
+            get-values
+            parse-args))
+
+
+(define (parse-args args click-option-spec)
+  "Parse args using an option-spec click formatted"
+  (let ((values (getopt-long args
+                             (getopt-long-option-spec click-option-spec)
+                             #:stop-at-first-non-option #t)))
+    values))
+
+
+(define (get-values option-spec values)
+  "Return an associated list with values for all the options in option-spec"
+  (cond ((null? option-spec)
+         '())
+        (else
+         (let* ((option (car option-spec))
+                (option-name (car option))
+                (value (get-normalized-value values option option-name)))
+           (cons (cons option-name value)
+                 (get-values (cdr option-spec) values))))))
+
+
+(define (get-normalized-value values option option-name)
+  "Get value for option, converting from string to the appropriate value"
+  (let ((convert-proc (assoc-ref (option-type option) 'convert))
+        (value (option-ref values option-name #f)))
+    (cond ((and value (not (option-property option 'flag)))
+           (convert-proc value))
+          (value
+           value)
+          (else
+           (get-option-default-value option)))))
+
+
+(define* (get-option-default-value option #:optional (no-prompt #f))
+  "Get default value for option, asking user if prompt property is set"
+  (let ((default (option-property option 'default)))
+    (if (not default)
+        (let ((prompt (option-property option 'prompt)))
+          (if prompt
+              (readline (format #f "~a: " prompt))
+              default))
+        default)))