config.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "log"
  7. "os"
  8. "sort"
  9. "strings"
  10. )
  11. func FileExists(path string) bool {
  12. _, err := os.Stat(path)
  13. return !errors.Is(err, os.ErrNotExist)
  14. }
  15. func LoadConfig(filename string) map[string]string {
  16. file, err := os.Open(filename)
  17. if err != nil {
  18. log.Panicf("Open(%s): %s\n", filename, err)
  19. }
  20. defer file.Close()
  21. var results map[string]string = make(map[string]string)
  22. scanner := bufio.NewScanner(file)
  23. for scanner.Scan() {
  24. line := scanner.Text()
  25. if len(line) == 0 {
  26. continue
  27. }
  28. if line[0] == '#' {
  29. continue
  30. }
  31. // Ok, I have a line, now what?
  32. parts := strings.SplitN(line, ": ", 2)
  33. if len(parts) == 2 {
  34. parts[1] = strings.Trim(parts[1], " ")
  35. // Handle quoted values
  36. if parts[1][0] == '"' && parts[1][len(parts[1])-1] == '"' {
  37. parts[1] = parts[1][1 : len(parts[1])-1]
  38. }
  39. if parts[1][0] == '\'' && parts[1][len(parts[1])-1] == '\'' {
  40. parts[1] = parts[1][1 : len(parts[1])-1]
  41. }
  42. results[parts[0]] = parts[1]
  43. // } else {
  44. // fmt.Printf("I'm not sure about [%s]\n", line)
  45. }
  46. }
  47. return results
  48. }
  49. func SaveConfig(filename string, config map[string]string) {
  50. file, err := os.Create(filename)
  51. if err != nil {
  52. log.Panicf("Open(%s): %s\n", filename, err)
  53. }
  54. defer file.Close()
  55. // Sort the Keys
  56. var keys []string
  57. for key := range config {
  58. keys = append(keys, key)
  59. }
  60. sort.Strings(keys)
  61. for _, key := range keys {
  62. fmt.Fprintf(file, "%s: %s\n", key, config[key])
  63. }
  64. }
  65. // SetConfigDefault Set default value (if not present)
  66. func SetConfigDefault(config *map[string]string, key string, value string) bool {
  67. _, ok := (*config)[key]
  68. if !ok {
  69. (*config)[key] = value
  70. return true
  71. }
  72. return false
  73. }