|
| 1 | +package fsrepo |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "path/filepath" |
| 10 | + |
| 11 | + "github.com/ipfs/go-ipfs/repo/config" |
| 12 | + |
| 13 | + "gx/ipfs/QmPdKqUcHGFdeSpvjVoaTRPPstGif9GBZb5Q56RVw9o69A/go-ipfs-util" |
| 14 | + "gx/ipfs/QmdYwCmx8pZRkzdcd8MhmLJqYVoVTC1aGsy5Q4reMGLNLg/atomicfile" |
| 15 | +) |
| 16 | + |
| 17 | +// ReadConfigFile reads the config from `filename` into `cfg`. |
| 18 | +func ReadConfigFile(filename string, cfg interface{}) error { |
| 19 | + f, err := os.Open(filename) |
| 20 | + if err != nil { |
| 21 | + return err |
| 22 | + } |
| 23 | + defer f.Close() |
| 24 | + if err := json.NewDecoder(f).Decode(cfg); err != nil { |
| 25 | + return fmt.Errorf("failure to decode config: %s", err) |
| 26 | + } |
| 27 | + return nil |
| 28 | +} |
| 29 | + |
| 30 | +// WriteConfigFile writes the config from `cfg` into `filename`. |
| 31 | +func WriteConfigFile(filename string, cfg interface{}) error { |
| 32 | + err := os.MkdirAll(filepath.Dir(filename), 0775) |
| 33 | + if err != nil { |
| 34 | + return err |
| 35 | + } |
| 36 | + |
| 37 | + f, err := atomicfile.New(filename, 0660) |
| 38 | + if err != nil { |
| 39 | + return err |
| 40 | + } |
| 41 | + defer f.Close() |
| 42 | + |
| 43 | + return encode(f, cfg) |
| 44 | +} |
| 45 | + |
| 46 | +// encode configuration with JSON |
| 47 | +func encode(w io.Writer, value interface{}) error { |
| 48 | + // need to prettyprint, hence MarshalIndent, instead of Encoder |
| 49 | + buf, err := config.Marshal(value) |
| 50 | + if err != nil { |
| 51 | + return err |
| 52 | + } |
| 53 | + _, err = w.Write(buf) |
| 54 | + return err |
| 55 | +} |
| 56 | + |
| 57 | +// Load reads given file and returns the read config, or error. |
| 58 | +func Load(filename string) (*config.Config, error) { |
| 59 | + // if nothing is there, fail. User must run 'ipfs init' |
| 60 | + if !util.FileExists(filename) { |
| 61 | + return nil, errors.New("ipfs not initialized, please run 'ipfs init'") |
| 62 | + } |
| 63 | + |
| 64 | + var cfg config.Config |
| 65 | + err := ReadConfigFile(filename, &cfg) |
| 66 | + if err != nil { |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + |
| 70 | + return &cfg, err |
| 71 | +} |
0 commit comments