| 1 |
// Copyright The Notary Project Authors. |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package config |
| 15 |
|
| 16 |
import ( |
| 17 |
"encoding/json" |
| 18 |
"fmt" |
| 19 |
"io/fs" |
| 20 |
"os" |
| 21 |
"path/filepath" |
| 22 |
|
| 23 |
"github.com/notaryproject/notation-go/dir" |
| 24 |
) |
| 25 |
|
| 26 |
// save stores the cfg struct to file |
| 27 |
func save(filePath string, cfg interface{}) error { |
| 28 |
dir := filepath.Dir(filePath) |
| 29 |
if err := os.MkdirAll(dir, 0700); err != nil { |
| 30 |
return err |
| 31 |
} |
| 32 |
|
| 33 |
file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) |
| 34 |
if err != nil { |
| 35 |
return err |
| 36 |
} |
| 37 |
defer file.Close() |
| 38 |
|
| 39 |
encoder := json.NewEncoder(file) |
| 40 |
encoder.SetIndent("", " ") |
| 41 |
return encoder.Encode(cfg) |
| 42 |
} |
| 43 |
|
| 44 |
// load reads file, parses json and stores in cfg struct |
| 45 |
func load(filePath string, cfg interface{}) error { |
| 46 |
path, err := dir.ConfigFS().SysPath(filePath) |
| 47 |
if err != nil { |
| 48 |
return err |
| 49 |
} |
| 50 |
|
| 51 |
// throw error if path is a directory or is a symlink or does not exist. |
| 52 |
fileInfo, err := os.Lstat(path) |
| 53 |
if err != nil { |
| 54 |
return err |
| 55 |
} |
| 56 |
mode := fileInfo.Mode() |
| 57 |
if mode.IsDir() || mode&fs.ModeSymlink != 0 { |
| 58 |
return fmt.Errorf("%q is not a regular file (symlinks are not supported)", path) |
| 59 |
} |
| 60 |
|
| 61 |
file, err := os.Open(path) |
| 62 |
if err != nil { |
| 63 |
return err |
| 64 |
} |
| 65 |
defer file.Close() |
| 66 |
return json.NewDecoder(file).Decode(cfg) |
| 67 |
} |