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

     1  /*
     2   Copyright 2022 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 utils
    18  
    19  import (
    20  	"context"
    21  	j "encoding/json"
    22  	"io"
    23  	"os"
    24  	"path/filepath"
    25  
    26  	"github.com/oam-dev/kubevela/pkg/utils/common"
    27  )
    28  
    29  // ReadRemoteOrLocalPath will read a path remote or locally
    30  func ReadRemoteOrLocalPath(pathOrURL string, saveLocal bool) ([]byte, error) {
    31  	var data []byte
    32  	var err error
    33  	fromLocalPath := false
    34  	switch {
    35  	case pathOrURL == "-":
    36  		data, err = io.ReadAll(os.Stdin)
    37  		if err != nil {
    38  			return nil, err
    39  		}
    40  	case IsValidURL(pathOrURL):
    41  		data, err = common.HTTPGetWithOption(context.Background(), pathOrURL, nil)
    42  		if err != nil {
    43  			return nil, err
    44  		}
    45  	default:
    46  		fromLocalPath = true
    47  		data, err = os.ReadFile(filepath.Clean(pathOrURL))
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  	}
    52  	if saveLocal && !fromLocalPath {
    53  		if err = localSave(pathOrURL, data); err != nil {
    54  			return nil, err
    55  		}
    56  	}
    57  	return data, nil
    58  }
    59  
    60  func localSave(url string, body []byte) error {
    61  	var name string
    62  	ext := filepath.Ext(url)
    63  	switch ext {
    64  	case ".json":
    65  		name = "vela.json"
    66  	case ".yaml", ".yml":
    67  		name = "vela.yaml"
    68  	default:
    69  		if j.Valid(body) {
    70  			name = "vela.json"
    71  		} else {
    72  			name = "vela.yaml"
    73  		}
    74  	}
    75  	//nolint:gosec
    76  	return os.WriteFile(name, body, 0644)
    77  }