cmd_env.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright GoFrame gf Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package cmd
  7. import (
  8. "bytes"
  9. "context"
  10. "github.com/olekukonko/tablewriter"
  11. "github.com/gogf/gf/v2/frame/g"
  12. "github.com/gogf/gf/v2/os/gproc"
  13. "github.com/gogf/gf/v2/text/gregex"
  14. "github.com/gogf/gf/v2/text/gstr"
  15. "github.com/gogf/gf/cmd/gf/v2/internal/utility/mlog"
  16. )
  17. var (
  18. Env = cEnv{}
  19. )
  20. type cEnv struct {
  21. g.Meta `name:"env" brief:"show current Golang environment variables"`
  22. }
  23. type cEnvInput struct {
  24. g.Meta `name:"env"`
  25. }
  26. type cEnvOutput struct{}
  27. func (c cEnv) Index(ctx context.Context, in cEnvInput) (out *cEnvOutput, err error) {
  28. result, err := gproc.ShellExec(ctx, "go env")
  29. if err != nil {
  30. mlog.Fatal(err)
  31. }
  32. if result == "" {
  33. mlog.Fatal(`retrieving Golang environment variables failed, did you install Golang?`)
  34. }
  35. var (
  36. lines = gstr.Split(result, "\n")
  37. buffer = bytes.NewBuffer(nil)
  38. )
  39. array := make([][]string, 0)
  40. for _, line := range lines {
  41. line = gstr.Trim(line)
  42. if line == "" {
  43. continue
  44. }
  45. if gstr.Pos(line, "set ") == 0 {
  46. line = line[4:]
  47. }
  48. match, _ := gregex.MatchString(`(.+?)=(.*)`, line)
  49. if len(match) < 3 {
  50. mlog.Fatalf(`invalid Golang environment variable: "%s"`, line)
  51. }
  52. array = append(array, []string{gstr.Trim(match[1]), gstr.Trim(match[2])})
  53. }
  54. tw := tablewriter.NewWriter(buffer)
  55. tw.SetColumnAlignment([]int{tablewriter.ALIGN_LEFT, tablewriter.ALIGN_LEFT})
  56. tw.AppendBulk(array)
  57. tw.Render()
  58. mlog.Print(buffer.String())
  59. return
  60. }