|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fgit-go/shared" |
| 6 | + "fmt" |
| 7 | + "io/ioutil" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | +) |
| 11 | + |
| 12 | +type ConfModel struct { |
| 13 | + GithubProxy string `json:"github_proxy"` |
| 14 | + RawProxy string `json:"raw_proxy"` |
| 15 | + DownloadProxy string `json:"download_proxy"` |
| 16 | +} |
| 17 | + |
| 18 | +func (c *ConfModel) Apply() { |
| 19 | + if c.GithubProxy != "" { |
| 20 | + shared.GitMirror = c.GithubProxy |
| 21 | + } |
| 22 | + if c.RawProxy != "" { |
| 23 | + shared.RawMirror = c.RawProxy |
| 24 | + } |
| 25 | + if c.DownloadProxy != "" { |
| 26 | + shared.DownloadMirror = c.DownloadProxy |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func (c *ConfModel) SaveConfig() { |
| 31 | + target, err := ensureConfigPath() |
| 32 | + if err != nil { |
| 33 | + fmt.Println("Construct path failed") |
| 34 | + return |
| 35 | + } |
| 36 | + s, err := json.Marshal(c) |
| 37 | + if err != nil { |
| 38 | + fmt.Println("Parse conf to json failed") |
| 39 | + return |
| 40 | + } |
| 41 | + err = ioutil.WriteFile(filepath.Join(target, "config.json"), s, 0644) |
| 42 | + if err != nil { |
| 43 | + fmt.Println("Write to file failed") |
| 44 | + return |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func ensureConfigPath() (path string, err error) { |
| 49 | + path, err = os.UserHomeDir() |
| 50 | + if err != nil { |
| 51 | + fmt.Println("Get Home Directory Failed") |
| 52 | + return |
| 53 | + } |
| 54 | + path = filepath.Join(path, ".config", "fgit-go") |
| 55 | + err = os.MkdirAll(path, os.ModePerm) |
| 56 | + if err != nil { |
| 57 | + fmt.Println("Create Configuation Path Failed") |
| 58 | + } |
| 59 | + return |
| 60 | +} |
| 61 | + |
| 62 | +func ReadConfig() { |
| 63 | + target, err := ensureConfigPath() |
| 64 | + shared.CheckErr(err, "Construct path failed", 1) |
| 65 | + if err != nil { |
| 66 | + fmt.Println() |
| 67 | + return |
| 68 | + } |
| 69 | + target = filepath.Join(target, "config.json") |
| 70 | + if !shared.IsExists(target) { |
| 71 | + conf := ConfModel{ |
| 72 | + GithubProxy: shared.GitMirror, |
| 73 | + RawProxy: shared.RawMirror, |
| 74 | + DownloadProxy: shared.DownloadMirror, |
| 75 | + } |
| 76 | + conf.SaveConfig() |
| 77 | + return |
| 78 | + } |
| 79 | + jsonFile, err := os.Open(target) |
| 80 | + if err != nil { |
| 81 | + fmt.Println(err) |
| 82 | + return |
| 83 | + } |
| 84 | + defer jsonFile.Close() |
| 85 | + |
| 86 | + byteValue, _ := ioutil.ReadAll(jsonFile) |
| 87 | + |
| 88 | + var conf ConfModel |
| 89 | + err = json.Unmarshal(byteValue, &conf) |
| 90 | + if err != nil { |
| 91 | + return |
| 92 | + } |
| 93 | + conf.Apply() |
| 94 | +} |
0 commit comments