8356
Wx
www-xonecas-io / files
www-xonecas-io / internal / store / sources.go
2.2 KB
1package store 2 3import ( 4 "bufio" 5 "errors" 6 "fmt" 7 "os" 8 "path/filepath" 9 "slices" 10 "strings" 11) 12 13// Sources reads one clone URL per line from path. Blank lines and # comments are skipped. 14func Sources(path string) ([]string, error) { 15 f, err := os.Open(path) 16 if err != nil { 17 return nil, err 18 } 19 defer f.Close() 20 var urls []string 21 for sc := bufio.NewScanner(f); sc.Scan(); { 22 if line := strings.TrimSpace(sc.Text()); line != "" && !strings.HasPrefix(line, "#") { 23 urls = append(urls, line) 24 } 25 } 26 return urls, err 27} 28 29// Clean returns a source as the sources file keeps it: an https clone URL ending in .git, 30// or the absolute path of a local git repo, for a repo that lives nowhere else. 31func Clean(src string) (string, error) { 32 if rest, ok := strings.CutPrefix(src, "https://"); ok { 33 host, path, _ := strings.Cut(strings.TrimSuffix(strings.TrimSuffix(rest, "/"), ".git"), "/") 34 if host == "" || path == "" { 35 return "", fmt.Errorf("%s is not a clone URL like https://host/owner/name.git", src) 36 } 37 return "https://" + host + "/" + path + ".git", nil 38 } 39 dir, err := filepath.Abs(src) 40 if err == nil { 41 _, err = git("-C", dir, "rev-parse", "--git-dir") 42 } 43 if err != nil { 44 return "", fmt.Errorf("%s is neither an https clone URL nor a local git repo", src) 45 } 46 return dir, nil 47} 48 49// AddSource appends url to the sources file at path, unless it is there already. 50func AddSource(path, url string) error { 51 urls, err := Sources(path) 52 if err != nil { 53 return err 54 } 55 if slices.Contains(urls, url) { 56 return fmt.Errorf("%s is already in %s", url, path) 57 } 58 f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644) 59 if err != nil { 60 return err 61 } 62 _, err = fmt.Fprintln(f, url) 63 return errors.Join(err, f.Close()) 64} 65 66// RemoveSource drops url's line from the sources file at path, keeping every other line. 67func RemoveSource(path, url string) error { 68 b, err := os.ReadFile(path) 69 if err != nil { 70 return err 71 } 72 lines := strings.SplitAfter(string(b), "\n") 73 n := len(lines) 74 lines = slices.DeleteFunc(lines, func(l string) bool { return strings.TrimSpace(l) == url }) 75 if len(lines) == n { 76 return fmt.Errorf("%s is not in %s", url, path) 77 } 78 return os.WriteFile(path, []byte(strings.Join(lines, "")), 0o644) 79}