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
119
120
121
122
123
124
125
126
127
128
129
|
/* This file is part of Mailfromd. -*- c -*-
Copyright (C) 2008 Sergey Poznyakoff
This program 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, or (at your option)
any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>. */
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
MF_VAR(optarg, STRING);
MF_VAR(optind, NUMBER);
MF_DEFUN_VARARGS(getopt, STRING, NUMBER argc, NUMBER argoff)
{
int rc;
int long_idx;
static char xargc;
static char **xargv;
static struct option *option;
static char *optstr;
static char *loptstr;
if (argc) {
size_t i, n;
size_t serial = 256;
xargc = argc + 1;
xargv = xcalloc(xargc+1, sizeof(xargv[0]));
xargv[0] = script_file;
for (i = 0; i < argc; i++)
xargv[i+1] = MF_VASTRING(argoff + i);
xargv[i+1] = NULL;
n = MF_VA_COUNT();
if (n) {
size_t i, j;
size_t len;
char *str;
size_t size, lsize, lcnt;
MF_VA_START();
size = lsize = lcnt = 0;
for (i = 0; i < n; i++) {
MF_VA_ARG(i, STRING, str);
len = strcspn(str, ",");
size += len;
if (str[len]) {
lcnt++;
lsize += strlen(str + len);
}
}
optstr = xrealloc(optstr, size + 1);
loptstr = xrealloc(loptstr, lsize + 1);
option = xrealloc(option,
(lcnt + 1) * sizeof(option[0]));
size = 0;
lsize = 0;
for (i = j = 0; i < n; i++) {
size_t len;
int val;
MF_VA_ARG(i, STRING, str);
len = strcspn(str, ",");
if (len > 0) {
memcpy(optstr + size, str, len);
size += len;
val = str[0];
} else
val = serial++;
if (str[len]) {
option[j].name = loptstr + lsize;
strcpy(loptstr + lsize,
str + len + 1);
lsize += strlen(str + len) + 1;
if (str[1] == ':')
option[j].has_arg =
(str[2] == ':') ?
optional_argument :
required_argument;
else
option[j].has_arg =
no_argument;
option[j].flag = NULL;
option[j].val = val;
j++;
}
}
MF_VA_END();
optstr[size] = 0;
loptstr[lsize] = 0;
memset(&option[j], 0, sizeof option[0]);
} else
option = NULL;
}
optind = (int) MF_VAR_REF(optind);
rc = getopt_long(xargc, xargv, optstr, option, &long_idx);
if (rc == EOF)
MF_RETURN_STRING("");
MF_VAR_REF(optind, optind);
MF_VAR_SET_STRING(optarg, optarg);
if (rc < 256) {
char s[2];
s[0] = rc;
s[1] = 0;
MF_RETURN_STRING(s);
}
MF_RETURN_STRING(option[long_idx].name);
}
END
MF_INIT
|