ParseConfig read config file content, return default config if file doesn't exist.
(configPath string)
| 58 | // ParseConfig read config file content, return default config |
| 59 | // if file doesn't exist. |
| 60 | func ParseConfig(configPath string) Config { |
| 61 | cfg, err := ini.LoadSources( |
| 62 | ini.LoadOptions{ |
| 63 | IgnoreContinuation: true, |
| 64 | IgnoreInlineComment: true, |
| 65 | }, |
| 66 | configPath) |
| 67 | |
| 68 | if err != nil { |
| 69 | defaultConfig := config{ |
| 70 | path: configPath, |
| 71 | content: getDefaultConfig(), |
| 72 | } |
| 73 | if err := defaultConfig.Write(); err != nil { |
| 74 | PrintWarning(fmt.Sprintf("Failed to save config: %s", err.Error())) |
| 75 | } else { |
| 76 | PrintSuccess("Default config-xpui.ini generated") |
| 77 | } |
| 78 | return defaultConfig |
| 79 | } |
| 80 | |
| 81 | needRewrite := false |
| 82 | for sectionName, keyList := range configLayout { |
| 83 | section, err := cfg.GetSection(sectionName) |
| 84 | if err != nil { |
| 85 | section, _ = cfg.NewSection(sectionName) |
| 86 | needRewrite = true |
| 87 | } |
| 88 | for keyName, defaultValue := range keyList { |
| 89 | if _, err := section.GetKey(keyName); err != nil { |
| 90 | section.NewKey(keyName, defaultValue) |
| 91 | needRewrite = true |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | if needRewrite { |
| 97 | PrintSuccess("Config is updated") |
| 98 | cfg.SaveTo(configPath) |
| 99 | } |
| 100 | |
| 101 | return config{ |
| 102 | path: configPath, |
| 103 | content: cfg, |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | // Write writes content to config file. |
| 108 | func (c config) Write() error { |
no test coverage detected