config.go 1.6 KB

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