123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- package main
- import (
- "bufio"
- "errors"
- "fmt"
- "log"
- "os"
- "sort"
- "strings"
- )
- func FileExists(path string) bool {
- _, err := os.Stat(path)
- return !errors.Is(err, os.ErrNotExist)
- }
- func LoadConfig(filename string) map[string]string {
- file, err := os.Open(filename)
- if err != nil {
- log.Panicf("Open(%s): %s\n", filename, err)
- }
- defer file.Close()
- var results map[string]string = make(map[string]string)
- scanner := bufio.NewScanner(file)
- for scanner.Scan() {
- line := scanner.Text()
- if len(line) == 0 {
- continue
- }
- if line[0] == '#' {
- continue
- }
- // Ok, I have a line, now what?
- parts := strings.SplitN(line, ": ", 2)
- if len(parts) == 2 {
- parts[1] = strings.Trim(parts[1], " ")
- // Handle quoted values
- if parts[1][0] == '"' && parts[1][len(parts[1])-1] == '"' {
- parts[1] = parts[1][1 : len(parts[1])-1]
- }
- if parts[1][0] == '\'' && parts[1][len(parts[1])-1] == '\'' {
- parts[1] = parts[1][1 : len(parts[1])-1]
- }
- results[parts[0]] = parts[1]
- // } else {
- // fmt.Printf("I'm not sure about [%s]\n", line)
- }
- }
- return results
- }
- func SaveConfig(filename string, config map[string]string) {
- file, err := os.Create(filename)
- if err != nil {
- log.Panicf("Open(%s): %s\n", filename, err)
- }
- defer file.Close()
- // Sort the Keys
- var keys []string
- for key := range config {
- keys = append(keys, key)
- }
- sort.Strings(keys)
- for _, key := range keys {
- fmt.Fprintf(file, "%s: %s\n", key, config[key])
- }
- }
- // SetConfigDefault Set default value (if not present)
- func SetConfigDefault(config *map[string]string, key string, value string) bool {
- _, ok := (*config)[key]
- if !ok {
- (*config)[key] = value
- return true
- }
- return false
- }
|