generate_plugin.go 4.0 KB

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