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