forked from yuin/gopher-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoslib.go
More file actions
389 lines (352 loc) · 8.99 KB
/
Copy pathoslib.go
File metadata and controls
389 lines (352 loc) · 8.99 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package lua
import (
"os"
"strings"
"time"
)
var startedAt time.Time
func init() {
startedAt = time.Now()
}
// Locale categories (Lua 5.3 compatible)
const (
LocaleCategoryAll = "all"
LocaleCategoryCollate = "collate"
LocaleCategoryCtype = "ctype"
LocaleCategoryMonetary = "monetary"
LocaleCategoryNumeric = "numeric"
LocaleCategoryTime = "time"
)
// currentLocales stores the current locale settings for each category
var currentLocales = map[string]string{
LocaleCategoryAll: "C",
LocaleCategoryCollate: "C",
LocaleCategoryCtype: "C",
LocaleCategoryMonetary: "C",
LocaleCategoryNumeric: "C",
LocaleCategoryTime: "C",
}
// isValidLocale checks if a locale name is potentially valid
// Since Go doesn't have full locale support, we accept any non-empty string
func isValidLocale(locale string) bool {
// Accept any non-empty locale string
// Common locale names: C, POSIX, en_US, en_US.UTF-8, ru_RU, ru_RU.UTF-8, etc.
if locale == "" {
return false
}
// Basic validation: locale names typically contain letters, numbers, underscores, dots, and hyphens
for _, c := range locale {
if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-') {
return false
}
}
return true
}
// getCategory returns the category string from the argument
func getCategory(L *LState, index int) string {
if L.GetTop() < index {
return LocaleCategoryAll
}
cat := L.CheckString(index)
switch strings.ToLower(cat) {
case "all":
return LocaleCategoryAll
case "collate":
return LocaleCategoryCollate
case "ctype":
return LocaleCategoryCtype
case "monetary":
return LocaleCategoryMonetary
case "numeric":
return LocaleCategoryNumeric
case "time":
return LocaleCategoryTime
default:
// Invalid category
return ""
}
}
// setLocaleForCategory sets the locale for a specific category
// In Go, we can't actually change locale, so we just store it
// Returns the old locale, or "" if the locale is not supported
func setLocaleForCategory(category, locale string) string {
// Check if locale is supported
// Common supported locales: "C", "", "POSIX"
// On Windows, some locales like "ptb" may not be supported for all categories
supportedLocales := []string{"C", "", "POSIX"}
isSupported := false
for _, sl := range supportedLocales {
if locale == sl {
isSupported = true
break
}
}
// On Windows, try to set the locale using C runtime
// If it fails, the locale is not supported
if !isSupported {
// Try to set locale using setlocale (C runtime)
// This is a simple check - in real implementation, we would use CGO
// For now, assume unknown locales are not supported
// Return empty string to indicate failure (Lua 5.3 behavior)
return ""
}
// If setting "all", update all categories
if category == LocaleCategoryAll {
oldLocale := currentLocales[LocaleCategoryAll]
for cat := range currentLocales {
currentLocales[cat] = locale
}
return oldLocale
}
// Setting a specific category
oldLocale := currentLocales[category]
currentLocales[category] = locale
return oldLocale
}
func getIntField(L *LState, tb *LTable, key string, v int) int {
ret := tb.RawGetString(key)
switch lv := ret.(type) {
case LNumber:
return int(lv.Int64())
case LString:
slv := string(lv)
slv = strings.TrimLeft(slv, " ")
if strings.HasPrefix(slv, "0") && !strings.HasPrefix(slv, "0x") && !strings.HasPrefix(slv, "0X") {
// Standard lua interpreter only support decimal and hexadecimal
slv = strings.TrimLeft(slv, "0")
if slv == "" {
return 0
}
}
if num, err := parseNumber(slv); err == nil {
return int(num.Int64())
}
default:
return v
}
return v
}
func getBoolField(L *LState, tb *LTable, key string, v bool) bool {
ret := tb.RawGetString(key)
if lb, ok := ret.(LBool); ok {
return bool(lb)
}
return v
}
func OpenOs(L *LState) int {
osmod := L.RegisterModule(OsLibName, osFuncs)
L.Push(osmod)
return 1
}
var osFuncs = map[string]LGFunction{
"clock": osClock,
"difftime": osDiffTime,
"execute": osExecute,
"exit": osExit,
"date": osDate,
"getenv": osGetEnv,
"remove": osRemove,
"rename": osRename,
"setenv": osSetEnv,
"setlocale": osSetLocale,
"time": osTime,
"tmpname": osTmpname,
}
func osClock(L *LState) int {
L.Push(LNumberFloat(float64(time.Now().Sub(startedAt)) / float64(time.Second)))
return 1
}
func osDiffTime(L *LState) int {
L.Push(LNumberInt(L.CheckInt64(1) - L.CheckInt64(2)))
return 1
}
func osExecute(L *LState) int {
// Lua 5.3: os.execute() without arguments returns true if shell is available
if L.GetTop() == 0 {
// On Windows, we assume cmd.exe is always available
// On Unix-like systems, /bin/sh is assumed available
L.Push(LTrue)
return 1
}
var procAttr os.ProcAttr
procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr}
cmd, args := popenArgs(L.CheckString(1))
args = append([]string{cmd}, args...)
process, err := os.StartProcess(cmd, args, &procAttr)
if err != nil {
L.Push(LFalse)
L.Push(LString("error running command"))
L.Push(LNumberInt(1))
return 3
}
ps, err := process.Wait()
if err != nil || !ps.Success() {
L.Push(LFalse)
L.Push(LString("command failed"))
L.Push(LNumberInt(1))
return 3
}
L.Push(LTrue)
return 1
}
func osExit(L *LState) int {
L.Close()
os.Exit(L.OptInt(1, 0))
return 1
}
func osDate(L *LState) int {
t := time.Now()
isUTC := false
cfmt := "%c"
if L.GetTop() >= 1 {
cfmt = L.CheckString(1)
if strings.HasPrefix(cfmt, "!") {
cfmt = strings.TrimLeft(cfmt, "!")
isUTC = true
}
if L.GetTop() >= 2 {
t = time.Unix(L.CheckInt64(2), 0)
}
if isUTC {
t = t.UTC()
}
if strings.HasPrefix(cfmt, "*t") {
ret := L.NewTable()
ret.RawSetString("year", LNumberInt(int64(t.Year())))
ret.RawSetString("month", LNumberInt(int64(t.Month())))
ret.RawSetString("day", LNumberInt(int64(t.Day())))
ret.RawSetString("hour", LNumberInt(int64(t.Hour())))
ret.RawSetString("min", LNumberInt(int64(t.Minute())))
ret.RawSetString("sec", LNumberInt(int64(t.Second())))
ret.RawSetString("wday", LNumberInt(int64(t.Weekday()+1)))
// TODO yday & dst
ret.RawSetString("yday", LNumberInt(0))
ret.RawSetString("isdst", LFalse)
L.Push(ret)
return 1
}
}
L.Push(LString(strftime(t, cfmt)))
return 1
}
func osGetEnv(L *LState) int {
v := os.Getenv(L.CheckString(1))
if len(v) == 0 {
L.Push(LNil)
} else {
L.Push(LString(v))
}
return 1
}
func osRemove(L *LState) int {
err := os.Remove(L.CheckString(1))
if err != nil {
L.Push(LNil)
L.Push(LString(err.Error()))
return 2
} else {
L.Push(LTrue)
return 1
}
}
func osRename(L *LState) int {
err := os.Rename(L.CheckString(1), L.CheckString(2))
if err != nil {
L.Push(LNil)
L.Push(LString(err.Error()))
return 2
} else {
L.Push(LTrue)
return 1
}
}
// os.setlocale([locale [, category]])
// Lua 5.3 compatible implementation
func osSetLocale(L *LState) int {
// Get locale argument (default: empty string = query current locale)
locale := L.OptString(1, "")
// Get category argument (default: "all")
category := getCategory(L, 2)
if category == "" {
// Invalid category
L.ArgError(2, "invalid category")
return 0
}
// If locale is empty string, return current locale for the category
if locale == "" {
if category == LocaleCategoryAll {
// Return the "all" locale
L.Push(LString(currentLocales[LocaleCategoryAll]))
} else {
L.Push(LString(currentLocales[category]))
}
return 1
}
// Validate locale name
if !isValidLocale(locale) {
L.Push(LNil)
L.Push(LString("invalid locale name"))
return 2
}
// Set the locale for the specified category
oldLocale := setLocaleForCategory(category, locale)
// Lua 5.3: return nil if locale is not supported
if oldLocale == "" {
L.Push(LNil)
} else {
// Return the previous locale for the category
L.Push(LString(oldLocale))
}
return 1
}
func osSetEnv(L *LState) int {
err := os.Setenv(L.CheckString(1), L.CheckString(2))
if err != nil {
L.Push(LNil)
L.Push(LString(err.Error()))
return 2
} else {
L.Push(LTrue)
return 1
}
}
func osTime(L *LState) int {
if L.GetTop() == 0 {
L.Push(LNumberInt(time.Now().Unix()))
} else {
lv := L.CheckAny(1)
if lv == LNil {
L.Push(LNumberInt(time.Now().Unix()))
} else {
tbl, ok := lv.(*LTable)
if !ok {
L.TypeError(1, LTTable)
}
sec := getIntField(L, tbl, "sec", 0)
min := getIntField(L, tbl, "min", 0)
hour := getIntField(L, tbl, "hour", 12)
day := getIntField(L, tbl, "day", -1)
month := getIntField(L, tbl, "month", -1)
year := getIntField(L, tbl, "year", -1)
isdst := getBoolField(L, tbl, "isdst", false)
t := time.Date(year, time.Month(month), day, hour, min, sec, 0, time.Local)
// TODO dst
if false {
print(isdst)
}
L.Push(LNumberInt(t.Unix()))
}
}
return 1
}
func osTmpname(L *LState) int {
file, err := os.CreateTemp("", "")
if err != nil {
L.RaiseError("unable to generate a unique filename")
}
file.Close()
os.Remove(file.Name()) // ignore errors
L.Push(LString(file.Name()))
return 1
}
//