forked from oils-for-unix/oils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibc.cc
218 lines (180 loc) · 5.32 KB
/
libc.cc
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// libc.cc: Replacement for pyext/libc.c
#include "cpp/libc.h"
#include <errno.h>
#include <fnmatch.h>
#include <glob.h>
#include <locale.h>
#include <regex.h>
#include <sys/ioctl.h>
#include <unistd.h> // gethostname()
#include <wchar.h>
namespace libc {
Str* gethostname() {
Str* result = OverAllocatedStr(HOST_NAME_MAX);
int status = ::gethostname(result->data_, HOST_NAME_MAX);
if (status != 0) {
throw Alloc<OSError>(errno);
}
// Important: set the length of the string!
result->MaybeShrink(strlen(result->data_));
return result;
}
Str* realpath(Str* path) {
Str* result = OverAllocatedStr(PATH_MAX);
char* p = ::realpath(path->data_, result->data_);
if (p == nullptr) {
throw Alloc<OSError>(errno);
}
result->MaybeShrink(strlen(result->data_));
return result;
}
int fnmatch(Str* pat, Str* str) {
int flags = FNM_EXTMATCH;
int result = ::fnmatch(pat->data_, str->data_, flags);
switch (result) {
case 0:
return 1;
case FNM_NOMATCH:
return 0;
default:
// Other error
return -1;
}
}
List<Str*>* glob(Str* pat) {
glob_t results;
// Hm, it's weird that the first one can't be called with GLOB_APPEND. You
// get a segfault.
int flags = 0;
// int flags = GLOB_APPEND;
// flags |= GLOB_NOMAGIC;
int ret = glob(pat->data_, flags, NULL, &results);
const char* err_str = NULL;
switch (ret) {
case 0: // no error
break;
case GLOB_ABORTED:
err_str = "read error";
break;
case GLOB_NOMATCH:
// No error, because not matching isn't necessarily a problem.
// NOTE: This can be turned on to log overaggressive calls to glob().
// err_str = "nothing matched";
break;
case GLOB_NOSPACE:
err_str = "no dynamic memory";
break;
default:
err_str = "unknown problem";
break;
}
if (err_str) {
throw Alloc<RuntimeError>(StrFromC(err_str));
}
// http://stackoverflow.com/questions/3512414/does-this-pylist-appendlist-py-buildvalue-leak
size_t n = results.gl_pathc;
auto matches = NewList<Str*>();
// Print array of results
size_t i;
for (i = 0; i < n; i++) {
const char* m = results.gl_pathv[i];
matches->append(StrFromC(m));
}
globfree(&results);
return matches;
}
// Raises RuntimeError if the pattern is invalid. TODO: Use a different
// exception?
List<Str*>* regex_match(Str* pattern, Str* str) {
List<Str*>* results = NewList<Str*>();
regex_t pat;
if (regcomp(&pat, pattern->data_, REG_EXTENDED) != 0) {
// TODO: check error code, as in func_regex_parse()
throw Alloc<RuntimeError>(StrFromC("Invalid regex syntax (regex_match)"));
}
int outlen = pat.re_nsub + 1; // number of captures
const char* s0 = str->data_;
regmatch_t* pmatch =
static_cast<regmatch_t*>(malloc(sizeof(regmatch_t) * outlen));
int match = regexec(&pat, s0, outlen, pmatch, 0) == 0;
if (match) {
int i;
for (i = 0; i < outlen; i++) {
int len = pmatch[i].rm_eo - pmatch[i].rm_so;
Str* m = StrFromC(s0 + pmatch[i].rm_so, len);
results->append(m);
}
}
free(pmatch);
regfree(&pat);
if (!match) {
return nullptr;
}
return results;
}
// For ${//}, the number of groups is always 1, so we want 2 match position
// results -- the whole regex (which we ignore), and then first group.
//
// For [[ =~ ]], do we need to count how many matches the user gave?
const int NMATCH = 2;
// Odd: This a Tuple2* not Tuple2 because it's Optional[Tuple2]!
Tuple2<int, int>* regex_first_group_match(Str* pattern, Str* str, int pos) {
regex_t pat;
regmatch_t m[NMATCH];
const char* old_locale = setlocale(LC_CTYPE, NULL);
if (setlocale(LC_CTYPE, "") == NULL) {
throw Alloc<RuntimeError>(StrFromC("Invalid locale for LC_CTYPE"));
}
// Could have been checked by regex_parse for [[ =~ ]], but not for glob
// patterns like ${foo/x*/y}.
if (regcomp(&pat, pattern->data_, REG_EXTENDED) != 0) {
throw Alloc<RuntimeError>(
StrFromC("Invalid regex syntax (func_regex_first_group_match)"));
}
// Match at offset 'pos'
int result = regexec(&pat, str->data_ + pos, NMATCH, m, 0 /*flags*/);
regfree(&pat);
setlocale(LC_CTYPE, old_locale);
if (result != 0) {
return nullptr;
}
// Assume there is a match
regoff_t start = m[1].rm_so;
regoff_t end = m[1].rm_eo;
Tuple2<int, int>* tup = Alloc<Tuple2<int, int>>(pos + start, pos + end);
return tup;
}
// TODO: SHARE with pyext
int wcswidth(Str* s) {
// Behavior of mbstowcs() depends on LC_CTYPE
// Calculate length first
int num_wide_chars = mbstowcs(NULL, s->data_, 0);
if (num_wide_chars == -1) {
throw Alloc<UnicodeError>(StrFromC("mbstowcs() 1"));
}
// Allocate buffer
int buf_size = (num_wide_chars + 1) * sizeof(wchar_t);
wchar_t* wide_chars = static_cast<wchar_t*>(malloc(buf_size));
assert(wide_chars != nullptr);
// Convert to wide chars
num_wide_chars = mbstowcs(wide_chars, s->data_, num_wide_chars);
if (num_wide_chars == -1) {
throw Alloc<UnicodeError>(StrFromC("mbstowcs() 2"));
}
// Find number of columns
int width = ::wcswidth(wide_chars, num_wide_chars);
if (width == -1) {
// unprintable chars
throw Alloc<UnicodeError>(StrFromC("wcswidth()"));
}
free(wide_chars);
return width;
}
int get_terminal_width() {
struct winsize w;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == -1) {
throw Alloc<IOError>(errno);
}
return w.ws_col;
}
} // namespace libc