-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
421 lines (362 loc) · 8.8 KB
/
main.go
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
)
type TargetConfig struct {
Name string
RepoDir string
RootDir string
VersionFile string
ReleaseURL string
DownloadURL string
}
var (
CWD = os.Getenv("PWD")
LenvDir = filepath.Join(os.Getenv("HOME"), ".lenv")
SrcDir = filepath.Join(LenvDir, "src")
CurrentDir = filepath.Join(LenvDir, "current")
CurrentUsed = ""
LuaCfg = &TargetConfig{
Name: "lua",
RootDir: filepath.Join(LenvDir, "lua"),
VersionFile: filepath.Join(LenvDir, "lua_vers.txt"),
ReleaseURL: "http://lua.org/ftp/",
DownloadURL: "http://lua.org/ftp/",
}
LuaJitCfg = &TargetConfig{
Name: "luajit",
RepoDir: filepath.Join(SrcDir, "luajit"),
RootDir: filepath.Join(LenvDir, "luajit"),
VersionFile: filepath.Join(LenvDir, "luajit_vers.txt"),
ReleaseURL: "https://github.com/LuaJIT/LuaJIT.git",
}
LuaRocksCfg = &TargetConfig{
Name: "luarocks",
VersionFile: filepath.Join(LenvDir, "luarocks_vers.txt"),
ReleaseURL: "http://luarocks.github.io/luarocks/releases/",
DownloadURL: "http://luarocks.github.io/luarocks/releases/",
}
)
func init_global_vars(inst_globally bool) {
// get current working directory
wd, err := os.Getwd()
if err != nil {
fatalf("failed to getwd(): %v", err)
}
CWD = wd
if inst_globally {
// set LenvDir to /usr/local/lenv
LenvDir = filepath.Join("/usr/local/lenv")
}
SrcDir = filepath.Join(LenvDir, "src")
CurrentDir = filepath.Join(LenvDir, "current")
CurrentUsed = ""
LuaCfg.RootDir = filepath.Join(LenvDir, "lua")
LuaCfg.VersionFile = filepath.Join(LenvDir, "lua_vers.txt")
LuaJitCfg.RepoDir = filepath.Join(SrcDir, "luajit")
LuaJitCfg.RootDir = filepath.Join(LenvDir, "luajit")
LuaJitCfg.VersionFile = filepath.Join(LenvDir, "luajit_vers.txt")
LuaRocksCfg.VersionFile = filepath.Join(LenvDir, "luarocks_vers.txt")
ResolveCurrentDir()
}
func eprintf(format string, v ...interface{}) {
os.Stderr.WriteString(fmt.Sprintf(format, v...))
os.Stderr.Write([]byte{'\n'})
}
var ExitCode int
func fatalf(format string, v ...interface{}) {
ExitCode = 1
eprintf(format, v...)
runtime.Goexit()
}
func errorf(format string, v ...interface{}) error {
pc, file, line, ok := runtime.Caller(1)
if !ok {
panic("failed to runtime,Caller()")
}
fname := runtime.FuncForPC(pc).Name()
return fmt.Errorf("[%s:%s:%d] "+format, append([]interface{}{file, fname, line}, v...)...)
}
func print(format string, v ...interface{}) {
fmt.Printf(format, v...)
}
func printf(format string, v ...interface{}) {
fmt.Printf(format+"\n", v...)
}
func lstat(file string) (os.FileInfo, error) {
info, err := os.Lstat(file)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
return info, nil
}
func isDir(file string) (bool, error) {
if info, err := lstat(file); err != nil {
return false, errorf("failed to lstat():", err)
} else if info != nil {
return info.IsDir(), nil
}
return false, nil
}
func getFileMode(file string) (os.FileMode, error) {
if info, err := lstat(file); err != nil {
return 0, err
} else if info != nil {
return info.Mode(), nil
}
return 0, nil
}
func mkdir(dirname string) error {
if ok, err := isDir(dirname); err != nil {
return err
} else if ok {
return nil
} else if err = os.MkdirAll(dirname, 0777); err != nil {
return err
}
return nil
}
func createSymlink(oldname, newname string) error {
var tmpName string
if f, err := os.CreateTemp("./", "tmp_symlink_*"); err != nil {
fatalf("failed to tempfile(): %v", err)
} else {
f.Close()
os.Remove(f.Name())
tmpName = f.Name()
}
if err := os.Symlink(oldname, tmpName); err != nil {
return err
}
if dir := filepath.Dir(newname); len(dir) > 0 {
if err := mkdir(dir); err != nil {
return err
}
}
return os.Rename(tmpName, newname)
}
func readSymlink(file string) (string, error) {
if mode, err := getFileMode(file); err != nil {
return "", err
} else if mode == 0 {
return "", nil
} else if mode&os.ModeSymlink == 0 {
return "", ErrNotSymlink
} else if pathname, err := os.Readlink(file); err != nil {
return "", err
} else {
return pathname, nil
}
}
func createFile(file string, perm os.FileMode) (*os.File, error) {
if err := mkdir(filepath.Dir(file)); err != nil {
return nil, err
}
f, err := os.Create(file)
if err != nil {
return nil, err
} else if perm > 0 {
if err = f.Chmod(perm); err != nil {
os.Remove(file)
return nil, err
}
}
return f, nil
}
func openFile(file string) (*os.File, error) {
f, err := os.Open(file)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
return nil, nil
}
return f, nil
}
func writeFile(file string, perm os.FileMode, src io.Reader) error {
f, err := createFile(file, perm)
if err != nil {
return err
}
defer f.Close()
if _, err = io.Copy(f, src); err != nil {
os.Remove(file)
return err
} else if err = f.Sync(); err != nil {
os.Remove(file)
return err
}
return nil
}
func hasRequiredDirs() bool {
// check required directories
for _, dir := range []string{
LenvDir, SrcDir, LuaCfg.RootDir, LuaJitCfg.RootDir,
} {
if info, err := lstat(dir); err != nil {
fatalf("- %q: cannot read metadata - %s", dir, err)
} else if info == nil {
return false
} else if !info.IsDir() {
return false
}
}
return true
}
func checkInitialized() {
if !hasRequiredDirs() {
eprintf(`
ERROR: the required directory does not exists.
please run 'lenv setup' before use.
`)
CmdHelp(1)
}
}
func CheckLuaRocksRootDir() {
if LuaRocksCfg.RootDir == "" {
fatalf("%q does not exist.\nplease run `lenv use <ver>` before installing or uninstalling luarocks", CurrentDir)
}
}
type Target struct {
Config *TargetConfig
Version *VerItem
}
type TargetVersion struct {
Lua *Target
LuaRocks *Target
}
func PickTargetVersion(vers string, exactMatch bool) *TargetVersion {
// check target version
if len(vers) == 0 || vers == ":" {
CmdHelp(1, "no version specified")
}
// check :<luarocks-version>
var rocksVer string
if delim := strings.Index(vers, ":"); delim != -1 {
rocksVer = vers[delim+1:]
vers = vers[:delim]
}
target := &TargetVersion{}
if len(vers) > 0 {
if strings.HasPrefix(vers, "lj-") {
// if `lj-' prefix is specified, then the target is LuaJIT version
target.Lua = &Target{
Config: LuaJitCfg,
Version: PickTargetVersionItem(LuaJitCfg, vers[3:], exactMatch),
}
} else {
// otherwise the target is Lua version.
target.Lua = &Target{
Config: LuaCfg,
Version: PickTargetVersionItem(LuaCfg, vers, exactMatch),
}
}
}
if len(rocksVer) > 0 {
target.LuaRocks = &Target{
Config: LuaRocksCfg,
Version: PickTargetVersionItem(LuaRocksCfg, rocksVer, exactMatch),
}
}
return target
}
func start() {
argv := os.Args[1:]
if len(argv) > 0 {
inst_globally := argv[0] == "-g" || argv[0] == "--global"
if inst_globally {
argv = argv[1:]
}
init_global_vars(inst_globally)
}
if len(argv) == 0 || argv[0] == "help" {
CmdHelp(0)
} else if argv[0] != "setup" {
checkInitialized()
}
switch argv[0] {
case "setup":
CmdSetup()
case "path":
CmdPath(argv[1:])
case "fetch":
CmdFetch()
case "vers":
CmdVers()
case "ls":
CmdList()
case "install":
CmdInstall(argv[1:])
case "uninstall":
CmdUninstall(argv[1:])
case "use":
CmdUse(argv[1:])
default:
CmdHelp(1, "unknown command %q", argv[0])
}
}
var ErrNotSymlink = fmt.Errorf("not a symlink")
func evalSymlink(file string) (string, error) {
if mode, err := getFileMode(file); err != nil {
return "", err
} else if mode == 0 {
return "", nil
} else if mode&os.ModeSymlink == 0 {
return "", ErrNotSymlink
} else if pathname, err := filepath.EvalSymlinks(file); err != nil {
return "", err
} else {
return pathname, nil
}
}
func ResolveCurrentDir() {
abortf := func(format string, v ...interface{}) {
eprintf(format, v...)
os.Exit(1)
}
// resolve CurrentDir
if dir, err := evalSymlink(CurrentDir); err != nil {
if errors.Is(err, ErrNotSymlink) {
abortf("%q is not symlink.\nplease remove it yourself", CurrentDir)
} else if !os.IsNotExist(err) {
abortf("failed to evalSymlink(): %#v", err)
}
os.Remove(CurrentDir)
} else if dir != "" {
if ok, err := isDir(dir); err != nil {
abortf("failed to isDir(): %v", err)
} else if !ok {
abortf("%s -> %q is not directory.\nplease remove it yourself", CurrentDir, dir)
}
CurrentUsed = dir
LuaRocksCfg.RootDir = filepath.Join(dir, "luarocks")
// create luarocks directory if not exist
if ok, err := isDir(LuaRocksCfg.RootDir); err != nil {
abortf("failed to isDir(): %v", err)
} else if !ok {
if err = mkdir(LuaRocksCfg.RootDir); err != nil {
abortf("failed to mkdir: %v", err)
}
}
}
}
func main() {
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
start()
}()
wg.Wait()
os.Exit(ExitCode)
}