This commit is contained in:
Yann Hamon 2025-05-10 23:12:14 +02:00
parent fd6904f2b4
commit ecc042d7f9
7 changed files with 107 additions and 46 deletions

71
pkg/loader/file.go Normal file
View file

@ -0,0 +1,71 @@
package loader
import (
"fmt"
"github.com/santhosh-tekuri/jsonschema/v6"
"github.com/yannh/kubeconform/pkg/cache"
gourl "net/url"
"os"
"path/filepath"
"runtime"
"strings"
)
// FileLoader loads json file url.
type FileLoader struct {
cache cache.Cache
}
func (l FileLoader) Load(url string) (any, error) {
path, err := l.ToFile(url)
if err != nil {
return nil, err
}
if l.cache != nil {
if cached, err := l.cache.Get(path); err == nil {
return cached, nil
}
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
s, err := jsonschema.UnmarshalJSON(f)
if err != nil {
return nil, err
}
if l.cache != nil {
if err = l.cache.Set(path, s); err != nil {
return nil, fmt.Errorf("failed to write cache to disk: %s", err)
}
}
return s, nil
}
// ToFile is helper method to convert file url to file path.
func (l FileLoader) ToFile(url string) (string, error) {
u, err := gourl.Parse(url)
if err != nil {
return "", err
}
if u.Scheme != "file" {
return "", fmt.Errorf("invalid file url: %s", u)
}
path := u.Path
if runtime.GOOS == "windows" {
path = strings.TrimPrefix(path, "/")
path = filepath.FromSlash(path)
}
return path, nil
}
func NewFileLoader(cache cache.Cache) *FileLoader {
return &FileLoader{
cache: cache,
}
}

View file

@ -19,6 +19,12 @@ type HTTPURLLoader struct {
}
func (l *HTTPURLLoader) Load(url string) (any, error) {
if l.cache != nil {
if cached, err := l.cache.Get(url); err == nil {
return cached, nil
}
}
resp, err := l.client.Get(url)
if err != nil {
msg := fmt.Sprintf("failed downloading schema at %s: %s", url, err)
@ -41,12 +47,18 @@ func (l *HTTPURLLoader) Load(url string) (any, error) {
msg := fmt.Sprintf("failed parsing schema from %s: %s", url, err)
return nil, errors.New(msg)
}
if l.cache != nil {
// To implement
s, err := jsonschema.UnmarshalJSON(bytes.NewReader(body))
if err != nil {
return nil, err
}
return jsonschema.UnmarshalJSON(bytes.NewReader(body))
if l.cache != nil {
if err = l.cache.Set(url, s); err != nil {
return nil, fmt.Errorf("failed to write cache to disk: %s", err)
}
}
return s, nil
}
func NewHTTPURLLoader(skipTLS bool, cache cache.Cache) (*HTTPURLLoader, error) {