|
| 1 | +package aspell |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "gopkg.in/yaml.v3" |
| 10 | +) |
| 11 | + |
| 12 | +func fetchRemoteFile(aspell Aspell) ([]string, error) { |
| 13 | + url := aspell.RemoteFile.URL |
| 14 | + if url == "" { |
| 15 | + return []string{}, nil |
| 16 | + } |
| 17 | + |
| 18 | + req, err := http.NewRequest("GET", url, nil) |
| 19 | + if err != nil { |
| 20 | + return nil, err |
| 21 | + } |
| 22 | + |
| 23 | + if aspell.RemoteFile.HeaderFromENV != "" { |
| 24 | + envValue := os.Getenv(aspell.RemoteFile.HeaderFromENV) |
| 25 | + req.Header.Set(aspell.RemoteFile.HeaderFromENV, envValue) |
| 26 | + } |
| 27 | + |
| 28 | + client := &http.Client{} |
| 29 | + resp, err := client.Do(req) |
| 30 | + if err != nil { |
| 31 | + return nil, err |
| 32 | + } |
| 33 | + |
| 34 | + defer resp.Body.Close() |
| 35 | + |
| 36 | + var data map[string]interface{} |
| 37 | + err = json.NewDecoder(resp.Body).Decode(&data) |
| 38 | + if err != nil { |
| 39 | + return nil, err |
| 40 | + } |
| 41 | + |
| 42 | + var allowedWords []string |
| 43 | + |
| 44 | + items, ok := data[aspell.RemoteFile.AllowedItemsKey].([]interface{}) |
| 45 | + if !ok { |
| 46 | + content, ok := data[aspell.RemoteFile.AllowedItemsKey].(string) |
| 47 | + if !ok { |
| 48 | + return nil, nil |
| 49 | + } |
| 50 | + if strings.HasPrefix(content, "```yaml\n") && strings.HasSuffix(content, "\n```") { |
| 51 | + content = strings.TrimPrefix(content, "```yaml\n") |
| 52 | + content = strings.TrimSuffix(content, "\n```") |
| 53 | + err = yaml.Unmarshal([]byte(content), &allowedWords) |
| 54 | + if err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + |
| 58 | + return allowedWords, nil |
| 59 | + } |
| 60 | + allowedWords = strings.Split(content, "\n") |
| 61 | + } |
| 62 | + |
| 63 | + for _, item := range items { |
| 64 | + allowedWords = append(allowedWords, item.(string)) |
| 65 | + } |
| 66 | + |
| 67 | + return allowedWords, nil |
| 68 | +} |
0 commit comments