config.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "sort"
  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, error) {
  15. var results map[string]string = make(map[string]string)
  16. file, err := os.Open(filename)
  17. if err != nil {
  18. return results, err
  19. }
  20. defer file.Close()
  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, nil
  47. }
  48. func SaveConfig(filename string, config map[string]string) error {
  49. file, err := os.Create(filename)
  50. if err != nil {
  51. return err
  52. }
  53. defer file.Close()
  54. // Sort the Keys
  55. var keys []string
  56. for key := range config {
  57. keys = append(keys, key)
  58. }
  59. sort.Strings(keys)
  60. for _, key := range keys {
  61. fmt.Fprintf(file, "%s: %s\n", key, config[key])
  62. }
  63. return nil
  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. (*config)[key] = value
  69. return ok
  70. }