internal/config/repository.go (view raw)
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 | package config
import (
"fmt"
"net/url"
"strings"
"github.com/Southclaws/fault"
"github.com/Southclaws/fault/fmsg"
)
type RepoType int
const (
UnknownRepoType = iota
GitHub
)
type Repository struct {
Type RepoType `toml:"" default:"github" comment:"Currently only 'github' is supported."`
Owner string
Repo string
Revision string `toml:"-"`
}
func (r *Repository) GetRawFileURL(path string) (string, error) {
switch r.Type {
case GitHub:
ref := r.Revision
if ref == "" {
ref = "master"
}
u, err := url.JoinPath("https://github.com/", r.Owner, r.Repo, "raw", ref, path)
if err != nil {
return "", fault.Wrap(err, fmsg.With("failed to join path"))
}
return u, nil
default:
return "", fault.Newf(
"don't know how to generate a repository URL for %s",
r.Type.String(),
)
}
}
func (r *Repository) GetFileURL(path string, line ...string) (string, error) {
switch r.Type {
case GitHub:
ref := r.Revision
if ref == "" {
ref = "master"
}
u, err := url.JoinPath("https://github.com/", r.Owner, r.Repo, "blob", ref, path)
if err != nil {
return "", fault.Wrap(err, fmsg.With("failed to join path"))
}
if len(line) > 0 {
u += fmt.Sprintf("#L%s", line[0])
}
return u, nil
default:
return "", fault.Newf(
"don't know how to generate a repository URL for %s",
r.Type.String(),
)
}
}
func (r *Repository) String() string {
switch r.Type {
case GitHub:
u, err := url.JoinPath("https://github.com/", r.Owner, r.Repo)
if err != nil {
panic(err)
}
return u
default:
panic("need repository string implementation for type " + r.Type.String())
}
}
func (f RepoType) String() string {
switch f {
case GitHub:
return "github"
default:
return fmt.Sprintf("RepoType(%d)", f)
}
}
func parseRepoType(name string) (RepoType, error) {
switch strings.ToLower(name) {
case "github":
return GitHub, nil
default:
return UnknownRepoType, fault.Newf("unsupported repo type %s", name)
}
}
func (f *RepoType) UnmarshalText(text []byte) error {
var err error
*f, err = parseRepoType(string(text))
return err
}
func (f RepoType) MarshalText() ([]byte, error) {
return []byte(f.String()), nil
}
|