blob: ea699db92db2b0f2c0163f698df33820f336f5c2 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
(define-library (csc flag)
(export
*args*
bool-flag
define-bool-flag
define-flag
parse-error-flag
parse-error-msg
parse-error?
parse-flags)
(import (scheme base)
(only (csc hash-map)
compare-strings
key-not-found-error?
lookup
make-map)
(only (csc loop)
loop)
(only (csc strings)
prefix?
contains?))
(begin
(define (bool-flag s)
(cond
((member s '("1" "t" "T" "true" "TRUE" "True"))
#t)
((member s '("0" "f" "F" "false" "FALSE" "False"))
#f)
(else (error "Argument could not be parsed as a boolean" s))))
(define *parsers* (make-map compare-strings))
(define-syntax define-flag
(syntax-rules ()
((define-flag name flag type default)
(define name (begin
(set! *parsers* (insert *parsers* flag (lambda (x) (set! name (type x)))))
default)))))
(define *args* '())
(define-record-type <parse-error>
(make-parse-error msg flag)
parse-error?
(msg parse-error-msg)
(flag parse-error-flag))
(define (parse-flags)
(define args (cdr (command-line)))
; Is this legal?
(define (parse-one)
(match args
('() #f)
((s . _) when (or (not (has-prefix? s "-"))
(string=? "-" s))
#f)
((s . rest) when (string=? "--" s)
(set! args rest)
#f)
((s . rest)
(define name (if (has-prefix? s "--")
(string-copy s 2)
(string-copy s 1)))
(when (or (string=? "" name)
(has-prefix? name "-")
(has-prefix? name "="))
(raise (make-parse-error "bad flag syntax" s)))
; It's a flag. Does it have an argument?
(set! args rest)
(define value (match (split name "=" 2)
((a b)
(set! name a)
b)
(_ #f)))
(define parser (guard (e ((key-not-found-error? e)
(raise (make-parse-error "flag provided but not defined" s))))
(lookup *parsers* name)))
(if (eq? parser bool-flag) ; Special case: doesn't need an arg.
(if value
(parser value)
(parser "true"))
(begin
; It must have a value, which might be the next argument.
(when (and (not value)
(not (null? args)))
; value is the next arg
(set! value (car args))
(set! args (cdr args)))
(unless value
(raise (make-parse-flag "flag needs an argument" s)))
(parser value)))
#t)))
(loop while (parse-one))
(set! *args* args))))
|