feat: port template-parsing logic from influxdb (#146)
This commit is contained in:
45
pkg/github/normalize.go
Normal file
45
pkg/github/normalize.go
Normal file
@ -0,0 +1,45 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
githubRawContentHost = "raw.githubusercontent.com"
|
||||
githubHost = "github.com"
|
||||
)
|
||||
|
||||
func NormalizeURLToContent(u *url.URL, extensions ...string) *url.URL {
|
||||
if u.Host != githubHost {
|
||||
return u
|
||||
}
|
||||
if len(extensions) > 0 && !extensionMatches(u, extensions) {
|
||||
return u
|
||||
}
|
||||
|
||||
p := u.Path
|
||||
if !strings.HasPrefix(p, "/") {
|
||||
p = "/" + p
|
||||
}
|
||||
parts := strings.Split(p, "/")
|
||||
if len(parts) < 4 {
|
||||
return u
|
||||
}
|
||||
|
||||
normalized := *u
|
||||
normalized.Host = githubRawContentHost
|
||||
normalized.Path = "/" + path.Join(append(parts[:3], parts[4:]...)...)
|
||||
return &normalized
|
||||
}
|
||||
|
||||
func extensionMatches(u *url.URL, extensions []string) bool {
|
||||
ext := path.Ext(u.Path)
|
||||
for _, e := range extensions {
|
||||
if strings.EqualFold(e, "."+ext) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
47
pkg/github/normalize_test.go
Normal file
47
pkg/github/normalize_test.go
Normal file
@ -0,0 +1,47 @@
|
||||
package github_test
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/influxdata/influx-cli/v2/pkg/github"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNormalize(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
in url.URL
|
||||
exts []string
|
||||
out url.URL
|
||||
}{
|
||||
{
|
||||
name: "github URL",
|
||||
in: url.URL{Host: "github.com", Path: "/influxdata/influxdb/blob/master/flags.yml"},
|
||||
out: url.URL{Host: "raw.githubusercontent.com", Path: "/influxdata/influxdb/master/flags.yml"},
|
||||
},
|
||||
{
|
||||
name: "other URL",
|
||||
in: url.URL{Host: "google.com", Path: "/fake.yml"},
|
||||
out: url.URL{Host: "google.com", Path: "/fake.yml"},
|
||||
},
|
||||
{
|
||||
name: "github URL - wrong extension",
|
||||
in: url.URL{Host: "github.com", Path: "/influxdata/influxdb/blob/master/flags.yml"},
|
||||
exts: []string{"json"},
|
||||
out: url.URL{Host: "github.com", Path: "/influxdata/influxdb/blob/master/flags.yml"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
normalized := github.NormalizeURLToContent(&tc.in, tc.exts...)
|
||||
require.Equal(t, tc.out, *normalized)
|
||||
})
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user