-
Notifications
You must be signed in to change notification settings - Fork 7
/
files.go
83 lines (71 loc) · 1.57 KB
/
files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
)
func readFile(path string) ([]byte, error) {
bs, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
return bs, nil
}
func repoPath(repo, file string) string {
return filepath.Join(repo, ".github", "autoreadme", file)
}
func localPath(dir, ext string) string {
var dot string
if ext != "" {
dot = "."
}
return filepath.Join(dir, "README.md"+dot+ext)
}
func toJson(bs []byte, err error) (any, error) {
if err != nil {
return nil, err
}
if bs == nil {
return nil, nil
}
var v any
err = json.Unmarshal(bs, &v)
return v, err
}
func fromLines(bs []byte, err error) (map[string]bool, error) {
if err != nil {
return nil, err
}
if bs == nil {
return nil, nil
}
lines := strings.Split(string(bs), "\n")
m := map[string]bool{}
for _, line := range lines {
if line = strings.TrimSpace(line); line != "" {
m[line] = true
}
}
return m, nil
}
func RepoTemplate(repo string) ([]byte, error) {
return readFile(repoPath(repo, "README.md.template"))
}
func RepoData(repo string) (any, error) {
return toJson(readFile(repoPath(repo, "README.md.data")))
}
func RepoIgnore(repo string) (map[string]bool, error) {
return fromLines(readFile(repoPath(repo, "autoreadme.ignore")))
}
func DirTemplate(dir string) ([]byte, error) {
return readFile(localPath(dir, "template"))
}
func DirData(dir string) (any, error) {
return toJson(readFile(localPath(dir, "data")))
}
func DirReadme(dir string) ([]byte, error) {
return readFile(localPath(dir, ""))
}