gopp/tool.go

80 lines
1.4 KiB
Go
Raw Permalink Normal View History

package gopp
2024-02-26 00:22:09 +03:00
import (
//"github.com/d5/tengo/v2"
"surdeus.su/core/xgo/v2/stdlib"
2024-05-20 20:34:11 +03:00
"surdeus.su/core/cli/mtool"
//"fmt"
2024-02-26 00:22:09 +03:00
"os"
"log"
"path/filepath"
"context"
2024-02-26 00:22:09 +03:00
)
var Tool = mtool.T("gopp").Func(func(flags *mtool.Flags){
2024-06-09 15:35:28 +03:00
var (
modDir string
render bool
2024-06-09 15:35:28 +03:00
)
log.SetFlags(0)
2024-06-09 15:35:28 +03:00
flags.StringVar(
&modDir,
"mod",
".",
"set the import directory",
)
flags.BoolVar(
&render,
"render",
false,
"render to xgo instead of preprocessing",
)
2024-06-09 15:35:28 +03:00
filePaths := flags.Parse()
x := NewXGo().SetPreCompile(func(
ctx context.Context, s *Script,
){
s.SetImports(stdlib.GetModuleMap(
stdlib.AllModuleNames()...,
))
s.EnableFileImport(true)
s.SetImportDir(modDir)
})
2024-06-09 15:35:28 +03:00
ctx := context.Background()
pp := New(x)
2024-02-26 00:22:09 +03:00
for _, filePath := range filePaths {
pth := filepath.FromSlash(filePath)
file, err := os.Open(pth)
if err != nil {
log.Printf("os.Open(%s): %s\n", pth, err)
continue
}
if render {
err := pp.Render(ctx, file, os.Stdout)
if err != nil {
log.Printf("pp.Render(...): %s\n", err)
}
continue
}
compiled, err := pp.Compile(context.Background(), file)
2024-02-26 00:22:09 +03:00
if err != nil {
log.Printf("pp.Compile(...): %s\n", err)
2024-02-26 00:22:09 +03:00
continue
}
err = pp.XGo().RunContext(
context.Background(),
compiled.Clone(),
pth, os.Stdout,
)
2024-02-26 00:22:09 +03:00
if err != nil {
log.Printf("pp.Xgo().RunContext(...): %s", err)
2024-02-26 00:22:09 +03:00
continue
}
}
2024-06-09 15:35:28 +03:00
}).Usage("[files]")