command-line-arguments.scm 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. (add-to-load-path (dirname (current-filename)))
  2. (use-modules (ice-9 getopt-long))
  3. (define (string-exact-integer? str)
  4. (exact-integer? (string->number str)))
  5. ;; First we define an option specification.
  6. (define option-spec
  7. ;; - Accept two options "version" and "help".
  8. ;; - They can be abbreviated by the single characters "v" and "h".
  9. ;; - The (value #f) tells getopt-long, that these options do not accept a value.
  10. `((version (single-char #\v) (value #f))
  11. (help (single-char #\h) (value #f))
  12. (user-name (value #t) (required? #f))
  13. (times-hello (value #t)
  14. (single-char #\n)
  15. (required? #f)
  16. (predicate ,string-exact-integer?))))
  17. ;; For each intended argument we have an association list which stores (property-name property-value).
  18. ;; The following properties are available:
  19. ;;
  20. ;; single-char (Single character abbreviation for the option.)
  21. ;; value (Does the option need a value? #t/#f/'optional, Is the option a flag?)
  22. ;; required? (#t/#f)
  23. ;; predicate (specify a procedure that takes the option's value as a string and returns #t or #f depending on whether the string is an acceptable input or not.)
  24. ;; Then we let getopt-long parse the arguments given.
  25. (define options (getopt-long (command-line) option-spec))
  26. ;; Access the value of the parsed options.
  27. ;; - It takes the options that were parsed,
  28. ;; - the options name we inquire about as a symbol,
  29. ;; - and a default value, in case the option was not specified on command line.
  30. (option-ref options 'help #f)
  31. ;; Now a program that uses this stuff.
  32. (define (main)
  33. (let* ([help-wanted (option-ref options 'help #f)]
  34. [version-wanted (option-ref options 'version #f)]
  35. [user-name (option-ref options 'user-name #f)]
  36. [times-say-hello (string->number (option-ref options 'times-hello "1"))])
  37. (cond [(or version-wanted help-wanted)
  38. (when version-wanted
  39. (display "command-line-arguments.scm 1.0.0\n"))
  40. (when help-wanted
  41. (display
  42. (string-join '(""
  43. "getopt-long-example [options]"
  44. "-v, --version Display version"
  45. "-h, --help Display this help"
  46. "")
  47. "\n")))]
  48. [else
  49. (do ([i 0 (1+ i)])
  50. ([>= i times-say-hello])
  51. (display (simple-format #f "Hello, ~a!\n" (if user-name
  52. user-name
  53. "World"))))])))
  54. (main)