main.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // This program generates env config scripts from config.Config struct tags for
  2. // unix and windows platforms.
  3. // Usage: go run ./cmd/config_generator [platform] [filename]
  4. // Example: go run ./cmd/config_generator unix settings.env
  5. package main
  6. import (
  7. "fmt"
  8. "io"
  9. "os"
  10. "reflect"
  11. "strings"
  12. "github.com/mk6i/retro-aim-server/config"
  13. "github.com/mitchellh/go-wordwrap"
  14. )
  15. var platformKeywords = map[string]struct {
  16. comment string
  17. assignment string
  18. }{
  19. "windows": {
  20. comment: "rem ",
  21. assignment: "set ",
  22. },
  23. "unix": {
  24. comment: "# ",
  25. assignment: "export ",
  26. },
  27. }
  28. func main() {
  29. args := os.Args[1:]
  30. if len(args) < 2 {
  31. fmt.Fprintln(os.Stderr, "usage: go run cmd/config_generator [platform] [filename]")
  32. os.Exit(1)
  33. }
  34. keywords, ok := platformKeywords[args[0]]
  35. if !ok {
  36. fmt.Fprintf(os.Stderr, "unable to find platform `%s`\n", os.Args[1])
  37. os.Exit(1)
  38. }
  39. fmt.Println("writing to", args[1])
  40. f, err := os.Create(args[1])
  41. if err != nil {
  42. fmt.Fprintf(os.Stderr, "error creating file: %s\n", err.Error())
  43. os.Exit(1)
  44. }
  45. defer f.Close()
  46. configType := reflect.TypeOf(config.Config{})
  47. for i := 0; i < configType.NumField(); i++ {
  48. field := configType.Field(i)
  49. comment := field.Tag.Get("description")
  50. if err := writeComment(f, comment, 80, keywords.comment); err != nil {
  51. fmt.Fprintf(os.Stderr, "error writing to file: %s\n", err.Error())
  52. os.Exit(1)
  53. }
  54. varName := field.Tag.Get("envconfig")
  55. val := field.Tag.Get("val")
  56. if err := writeAssignment(f, keywords.assignment, varName, val); err != nil {
  57. fmt.Fprintf(os.Stderr, "error writing to file: %s\n", err.Error())
  58. os.Exit(1)
  59. }
  60. }
  61. }
  62. func writeComment(w io.Writer, comment string, width uint, keyword string) error {
  63. // adjust wrapping threshold to accommodate comment keyword length
  64. width = width - uint(len(keyword))
  65. comment = wordwrap.WrapString(comment, width)
  66. // prepend lines with comment keyword
  67. comment = strings.ReplaceAll(comment, "\n", fmt.Sprintf("\n%s", keyword))
  68. _, err := fmt.Fprintf(w, "%s%s\n", keyword, comment)
  69. return err
  70. }
  71. func writeAssignment(w io.Writer, keyword string, varName string, val string) error {
  72. _, err := fmt.Fprintf(w, "%s%s=%s\n\n", keyword, varName, val)
  73. return err
  74. }