main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "path"
  7. "runtime"
  8. "strings"
  9. "text/template"
  10. "gopkg.in/src-d/hercules.v3"
  11. "github.com/fatih/camelcase"
  12. )
  13. //go:generate go run embed.go
  14. var SHLIB_EXT = map[string]string {
  15. "window": "dll",
  16. "linux": "so",
  17. "darwin": "dylib",
  18. "freebsd": "dylib",
  19. }
  20. func main() {
  21. var outputPath, name, varname, _flag, pkg string
  22. var printVersion bool
  23. flag.StringVar(&name, "n", "", "Name of the plugin, CamelCase. Required.")
  24. flag.StringVar(&outputPath, "o", "", "Output path of the generated plugin code. If not " +
  25. "specified, inferred from -n.")
  26. flag.StringVar(&varname, "varname", "", "Name of the plugin instance variable, If not " +
  27. "specified, inferred from -n.")
  28. flag.StringVar(&_flag, "flag", "", "Name of the plugin activation cmdline flag, If not " +
  29. "specified, inferred from -varname.")
  30. flag.BoolVar(&printVersion, "version", false, "Print version information and exit.")
  31. flag.StringVar(&pkg, "package", "main", "Name of the package.")
  32. flag.Parse()
  33. if printVersion {
  34. fmt.Printf("Version: 3\nGit: %s\n", hercules.GIT_HASH)
  35. return
  36. }
  37. if name == "" {
  38. fmt.Fprintln(os.Stderr, "-n must be specified")
  39. flag.PrintDefaults()
  40. os.Exit(1)
  41. }
  42. splitted := camelcase.Split(name)
  43. if outputPath == "" {
  44. outputPath = strings.ToLower(strings.Join(splitted, "_")) + ".go"
  45. } else if !strings.HasSuffix(outputPath, ".go") {
  46. panic("-o must end with \".go\"")
  47. }
  48. gen := template.Must(template.New("plugin").Parse(PLUGIN_TEMPLATE_SOURCE))
  49. outFile, err := os.Create(outputPath)
  50. if err != nil {
  51. panic(err)
  52. }
  53. defer outFile.Close()
  54. if varname == "" {
  55. varname = strings.ToLower(splitted[0])
  56. }
  57. if _flag == "" {
  58. _flag = strings.Join(splitted, "-")
  59. }
  60. outputBase := path.Base(outputPath)
  61. shlib := outputBase[:len(outputBase)-2] + SHLIB_EXT[runtime.GOOS]
  62. dict := map[string]string{
  63. "name": name, "varname": varname, "flag": _flag, "package": pkg,
  64. "output": outputPath, "shlib": shlib}
  65. err = gen.Execute(outFile, dict)
  66. if err != nil {
  67. panic(err)
  68. }
  69. }