blob: 7b45b1283fc3391f2a05a7df4fc1b30368609410 (
plain)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
implement Arg;
#
# Copyright © 1997 Roger Peppe
#
include "sys.m";
include "arg.m";
name:= "";
args: list of string;
usagemsg:="";
printusage := 1;
curropt: string;
init(argv: list of string)
{
(curropt, args, name) = (nil, nil, nil);
if (argv == nil)
return;
name = hd argv;
args = tl argv;
}
setusage(u: string)
{
usagemsg = u;
printusage = u != nil;
}
progname(): string
{
return name;
}
# don't allow any more options after this function is invoked
argv(): list of string
{
ret := args;
args = nil;
return ret;
}
earg(): string
{
if (curropt != nil) {
ret := curropt;
curropt = nil;
return ret;
}
if (args == nil)
usage();
ret := hd args;
args = tl args;
return ret;
}
# get next option argument
arg(): string
{
if (curropt != nil) {
ret := curropt;
curropt = nil;
return ret;
}
if (args == nil)
return nil;
ret := hd args;
args = tl args;
return ret;
}
# get next option letter
# return 0 at end of options
opt(): int
{
if (curropt != nil) {
opt := curropt[0];
curropt = curropt[1:];
return opt;
}
if (args == nil)
return 0;
nextarg := hd args;
if (len nextarg < 2 || nextarg[0] != '-')
return 0;
if (nextarg == "--") {
args = tl args;
return 0;
}
opt := nextarg[1];
if (len nextarg > 2)
curropt = nextarg[2:];
args = tl args;
return opt;
}
usage()
{
if(printusage){
if(usagemsg != nil)
u := "usage: "+usagemsg;
else
u = name + ": argument expected";
sys := load Sys Sys->PATH;
sys->fprint(sys->fildes(2), "%s\n", u);
}
raise "fail:usage";
}
|