github.com/oam-dev/kubevela@v1.9.11/pkg/addon/reader_local.go (about)

     1  /*
     2  Copyright 2021 The KubeVela Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package addon
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"path/filepath"
    23  	"strings"
    24  )
    25  
    26  type localReader struct {
    27  	dir  string
    28  	name string
    29  }
    30  
    31  func (l localReader) ListAddonMeta() (map[string]SourceMeta, error) {
    32  	metas := SourceMeta{Name: l.name}
    33  	if err := recursiveFetchFiles(l.dir, &metas); err != nil {
    34  		return nil, err
    35  	}
    36  	return map[string]SourceMeta{l.name: metas}, nil
    37  }
    38  
    39  func (l localReader) ReadFile(path string) (string, error) {
    40  	path = strings.TrimPrefix(path, l.name+"/")
    41  	// for windows
    42  	path = strings.TrimPrefix(path, l.name+"\\")
    43  	b, err := os.ReadFile(filepath.Clean(filepath.Join(l.dir, path)))
    44  	if err != nil {
    45  		return "", err
    46  	}
    47  	return string(b), nil
    48  }
    49  
    50  func (l localReader) RelativePath(item Item) string {
    51  	file := strings.TrimPrefix(item.GetPath(), filepath.Clean(l.dir))
    52  	return filepath.Join(l.name, file)
    53  }
    54  
    55  func recursiveFetchFiles(path string, metas *SourceMeta) error {
    56  	files, err := os.ReadDir(path)
    57  	if err != nil {
    58  		return err
    59  	}
    60  	for _, file := range files {
    61  		if file.IsDir() {
    62  			if err := recursiveFetchFiles(fmt.Sprintf("%s/%s", path, file.Name()), metas); err != nil {
    63  				return err
    64  			}
    65  		} else {
    66  			metas.Items = append(metas.Items, OSSItem{tp: "file", path: filepath.Join(path, file.Name()), name: file.Name()})
    67  		}
    68  	}
    69  	return nil
    70  }