generate_plugin.go 4.1 KB

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