main.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. package main
  5. import (
  6. "flag"
  7. "html/template"
  8. "io/ioutil"
  9. "log"
  10. "os"
  11. "path"
  12. "strings"
  13. )
  14. const (
  15. defaultTemplateFile = "coredhcp.go.template"
  16. )
  17. var (
  18. flagTemplate = flag.String("template", defaultTemplateFile, "Template file name")
  19. flagOutfile = flag.String("outfile", "", "Output file path")
  20. )
  21. func main() {
  22. flag.Parse()
  23. data, err := ioutil.ReadFile(*flagTemplate)
  24. if err != nil {
  25. log.Fatalf("Failed to read template file '%s': %v", *flagTemplate, err)
  26. }
  27. t, err := template.New("coredhcp").Parse(string(data))
  28. if err != nil {
  29. log.Fatalf("Template parsing failed: %v", err)
  30. }
  31. var plugins []string
  32. for _, pl := range flag.Args() {
  33. pl := strings.TrimSpace(pl)
  34. if pl == "" {
  35. continue
  36. }
  37. plugins = append(plugins, pl)
  38. }
  39. if len(plugins) == 0 {
  40. log.Fatalf("No plugin specified!")
  41. }
  42. outfile := *flagOutfile
  43. if outfile == "" {
  44. tmpdir, err := ioutil.TempDir("", "coredhcp")
  45. if err != nil {
  46. log.Fatalf("Cannot create temporary directory: %v", err)
  47. }
  48. outfile = path.Join(tmpdir, "coredhcp.go")
  49. }
  50. log.Printf("Generating output file '%s' with %d plugins", outfile, len(plugins))
  51. outFD, err := os.OpenFile(outfile, os.O_CREATE|os.O_WRONLY, 0644)
  52. if err != nil {
  53. log.Fatalf("Failed to create output file '%s': %v", outfile, err)
  54. }
  55. defer func() {
  56. if err := outFD.Close(); err != nil {
  57. log.Printf("Error while closing file descriptor for '%s': %v", outfile, err)
  58. }
  59. }()
  60. if err := t.Execute(outFD, plugins); err != nil {
  61. log.Fatalf("Template execution failed: %v", err)
  62. }
  63. log.Printf("Generated file '%s'. You can build it by running 'go build' in the output directory.", outfile)
  64. }