tool.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package gopp
  2. import (
  3. //"github.com/d5/tengo/v2"
  4. "surdeus.su/core/xgo/v2/stdlib"
  5. "surdeus.su/core/cli/mtool"
  6. //"fmt"
  7. "os"
  8. "log"
  9. "path/filepath"
  10. "context"
  11. )
  12. var Tool = mtool.T("gopp").Func(func(flags *mtool.Flags){
  13. var (
  14. modDir string
  15. render bool
  16. )
  17. log.SetFlags(0)
  18. flags.StringVar(
  19. &modDir,
  20. "mod",
  21. ".",
  22. "set the import directory",
  23. )
  24. flags.BoolVar(
  25. &render,
  26. "render",
  27. false,
  28. "render to xgo instead of preprocessing",
  29. )
  30. filePaths := flags.Parse()
  31. x := NewXGo().SetPreCompile(func(
  32. ctx context.Context, s *Script,
  33. ){
  34. s.SetImports(stdlib.GetModuleMap(
  35. stdlib.AllModuleNames()...,
  36. ))
  37. s.EnableFileImport(true)
  38. s.SetImportDir(modDir)
  39. })
  40. ctx := context.Background()
  41. pp := New(x)
  42. for _, filePath := range filePaths {
  43. pth := filepath.FromSlash(filePath)
  44. file, err := os.Open(pth)
  45. if err != nil {
  46. log.Printf("os.Open(%s): %s\n", pth, err)
  47. continue
  48. }
  49. if render {
  50. err := pp.Render(ctx, file, os.Stdout)
  51. if err != nil {
  52. log.Printf("pp.Render(...): %s\n", err)
  53. }
  54. continue
  55. }
  56. compiled, err := pp.Compile(context.Background(), file)
  57. if err != nil {
  58. log.Printf("pp.Compile(...): %s\n", err)
  59. continue
  60. }
  61. err = pp.XGo().RunContext(
  62. context.Background(),
  63. compiled.Clone(),
  64. pth, os.Stdout,
  65. )
  66. if err != nil {
  67. log.Printf("pp.Xgo().RunContext(...): %s", err)
  68. continue
  69. }
  70. }
  71. }).Usage("[files]")