-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconfig.go
114 lines (88 loc) · 2.23 KB
/
config.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"fmt"
"log"
"os"
_ "embed"
"github.com/pelletier/go-toml"
"github.com/pkg/errors"
)
const defaultConfigName = ".vanity-imports.toml"
const sampleConfig = `
domain = "go.example.com"
[index]
description = ""
extra_head = ""
title = "Jane's go packages"
[repos]
[repos."/foobar"]
repo = "https://github.com/jane/foobar"
vcs = "git"
`
//go:embed templates/repo.html
var repoTmpl string
//go:embed templates/index.html
var indexTmpl string
type Config struct {
Repos map[string]Repository `toml:"repos"`
Domain string `toml:"domain"`
Index Index `toml:"index"`
RepoTemplate string `toml:"repo_template"`
IndexTemplate string `toml:"index_template"`
Output string `toml:"output" default:"dist"`
}
type Index struct {
Title string `toml:"title"`
Description string `toml:"description"`
ExtraHead string `toml:"extra_head"`
}
type Repository struct {
URL string `toml:"repo"`
VCS string `vcs:"repo"`
}
func (r Repository) String() string {
return r.URL
}
func newConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, errors.Wrap(err, "cannot open config file")
}
config := &Config{}
err = toml.Unmarshal(data, config)
if err != nil {
return nil, err
}
if config.RepoTemplate == "" {
config.RepoTemplate = repoTmpl
}
if config.IndexTemplate == "" {
config.IndexTemplate = indexTmpl
}
err = config.isValid()
return config, err
}
func (c Config) isValid() error {
if c.Domain == "" {
return errors.New("domain is empty or missing in config")
}
if c.Index == (Index{}) && c.Index.Title == "" {
return errors.New("index.title is empty or missing in config")
}
for path, repo := range c.Repos {
if repo.URL == "" {
return fmt.Errorf("repo.%s.repo is empty or missing in config", path)
}
if repo.VCS == "" {
return fmt.Errorf("repo.%s.vcs is empty or missing in config", path)
}
}
return nil
}
func initSampleConfig() error {
if _, err := os.Stat(defaultConfigName); os.IsNotExist(err) {
return os.WriteFile(defaultConfigName, []byte(sampleConfig), 0777)
}
log.Printf("%s already exists\n", defaultConfigName)
return nil
}