generate_plugin.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "path"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "text/template"
  13. "github.com/fatih/camelcase"
  14. "github.com/spf13/cobra"
  15. )
  16. //go:generate go run embed.go
  17. // ShlibExts is the mapping between platform names and shared library file name extensions.
  18. var ShlibExts = map[string]string{
  19. "window": "dll",
  20. "linux": "so",
  21. "darwin": "dylib",
  22. "freebsd": "dylib",
  23. }
  24. // generatePluginCmd represents the generatePlugin command
  25. var generatePluginCmd = &cobra.Command{
  26. Use: "generate-plugin",
  27. Short: "Write the plugin source skeleton.",
  28. Long: ``,
  29. Run: func(cmd *cobra.Command, args []string) {
  30. flags := cmd.Flags()
  31. name, _ := flags.GetString("name")
  32. outputDir, _ := flags.GetString("output")
  33. varname, _ := flags.GetString("varname")
  34. flag, _ := flags.GetString("flag")
  35. disableMakefile, _ := flags.GetBool("no-makefile")
  36. pkg, _ := flags.GetString("package")
  37. splitted := camelcase.Split(name)
  38. err := os.MkdirAll(outputDir, os.ModePerm)
  39. if err != nil {
  40. panic(err)
  41. }
  42. outputPath := path.Join(outputDir, strings.ToLower(strings.Join(splitted, "_"))+".go")
  43. gen := template.Must(template.New("plugin").Parse(PluginTemplateSource))
  44. outFile, err := os.Create(outputPath)
  45. if err != nil {
  46. panic(err)
  47. }
  48. defer outFile.Close()
  49. if varname == "" {
  50. varname = strings.ToLower(splitted[0])
  51. }
  52. if flag == "" {
  53. flag = strings.ToLower(strings.Join(splitted, "-"))
  54. }
  55. outputBase := path.Base(outputPath)
  56. shlib := outputBase[:len(outputBase)-2] + ShlibExts[runtime.GOOS]
  57. protoBuf := outputPath[:len(outputPath)-3] + ".proto"
  58. pbGo := outputPath[:len(outputPath)-3] + ".pb.go"
  59. dict := map[string]string{
  60. "name": name, "varname": varname, "flag": flag, "package": pkg,
  61. "output": outputPath, "shlib": shlib, "proto": protoBuf, "protogo": pbGo,
  62. "outdir": outputDir}
  63. err = gen.Execute(outFile, dict)
  64. if err != nil {
  65. panic(err)
  66. }
  67. // write pb file
  68. ioutil.WriteFile(protoBuf, []byte(fmt.Sprintf(`syntax = "proto3";
  69. option go_package = "%s";
  70. message %sResultMessage {
  71. // add fields here
  72. // reference: https://developers.google.com/protocol-buffers/docs/proto3
  73. // example: pb/pb.proto https://github.com/src-d/hercules/blob/master/pb/pb.proto
  74. }
  75. `, pkg, name)), 0666)
  76. // generate the pb Go file
  77. protoc, err := exec.LookPath("protoc")
  78. cmdargs := [...]string{
  79. protoc,
  80. "--gogo_out=" + outputDir,
  81. "--proto_path=" + outputDir,
  82. protoBuf,
  83. }
  84. env := os.Environ()
  85. extraPath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  86. gobin := os.Getenv("GOBIN")
  87. if gobin != "" {
  88. extraPath = gobin + ":" + extraPath
  89. }
  90. env = append(env, fmt.Sprintf("PATH=%s:%s", os.Getenv("PATH"), extraPath))
  91. if err != nil {
  92. panic("protoc was not found at " + env[len(env)-1])
  93. }
  94. protocmd := exec.Cmd{
  95. Path: protoc, Args: cmdargs[:], Env: env, Stdout: os.Stdout, Stderr: os.Stderr}
  96. err = protocmd.Run()
  97. if err != nil {
  98. panic(err)
  99. }
  100. if !disableMakefile {
  101. makefile := path.Join(outputDir, "Makefile")
  102. gen = template.Must(template.New("plugin").Parse(`GO111MODULE = on
  103. all: {{.shlib}}
  104. {{.shlib}}: {{.output}} {{.protogo}}
  105. ` + "\t" + `go build -buildmode=plugin -linkshared {{.output}} {{.protogo}}
  106. {{.protogo}}: {{.proto}}
  107. ` + "\t" + `PATH=$$PATH:$$GOBIN protoc --gogo_out=. --proto_path=. {{.proto}}
  108. `))
  109. buffer := new(bytes.Buffer)
  110. mkrelative := func(name string) {
  111. dict[name] = path.Base(dict[name])
  112. }
  113. mkrelative("output")
  114. mkrelative("protogo")
  115. mkrelative("proto")
  116. gen.Execute(buffer, dict)
  117. ioutil.WriteFile(makefile, buffer.Bytes(), 0666)
  118. }
  119. },
  120. }
  121. func init() {
  122. rootCmd.AddCommand(generatePluginCmd)
  123. generatePluginCmd.SetUsageFunc(generatePluginCmd.UsageFunc())
  124. gpFlags := generatePluginCmd.Flags()
  125. gpFlags.StringP("name", "n", "", "Name of the plugin, CamelCase. Required.")
  126. generatePluginCmd.MarkFlagRequired("name")
  127. gpFlags.StringP("output", "o", ".", "Output directory for the generated plugin files.")
  128. gpFlags.String("varname", "", "Name of the plugin instance variable, If not "+
  129. "specified, inferred from -n.")
  130. gpFlags.String("flag", "", "Name of the plugin activation cmdline flag, If not "+
  131. "specified, inferred from -varname.")
  132. gpFlags.Bool("no-makefile", false, "Do not generate the Makefile.")
  133. gpFlags.String("package", "main", "Name of the package.")
  134. }