| OLD | NEW |
| 1 // Copyright 2015 The LUCI Authors. All rights reserved. | 1 // Copyright 2015 The LUCI Authors. All rights reserved. |
| 2 // Use of this source code is governed under the Apache License, Version 2.0 | 2 // Use of this source code is governed under the Apache License, Version 2.0 |
| 3 // that can be found in the LICENSE file. | 3 // that can be found in the LICENSE file. |
| 4 | 4 |
| 5 package common | 5 package common |
| 6 | 6 |
| 7 import ( | 7 import ( |
| 8 "encoding/json" | 8 "encoding/json" |
| 9 "fmt" | 9 "fmt" |
| 10 "os" | 10 "os" |
| 11 ) | 11 ) |
| 12 | 12 |
| 13 // ReadJSONFile reads a file and decode it as JSON. | |
| 14 func ReadJSONFile(filePath string, object interface{}) error { | |
| 15 f, err := os.Open(filePath) | |
| 16 if err != nil { | |
| 17 return fmt.Errorf("failed to open %s: %s", filePath, err) | |
| 18 } | |
| 19 defer f.Close() | |
| 20 if err = json.NewDecoder(f).Decode(object); err != nil { | |
| 21 return fmt.Errorf("failed to decode %s: %s", filePath, err) | |
| 22 } | |
| 23 return nil | |
| 24 } | |
| 25 | |
| 26 // WriteJSONFile writes object as json encoded into filePath with 2 spaces | 13 // WriteJSONFile writes object as json encoded into filePath with 2 spaces |
| 27 // indentation. File permission is set to user only. | 14 // indentation. File permission is set to user only. |
| 28 func WriteJSONFile(filePath string, object interface{}) error { | 15 func WriteJSONFile(filePath string, object interface{}) error { |
| 29 d, err := json.MarshalIndent(object, "", " ") | 16 d, err := json.MarshalIndent(object, "", " ") |
| 30 if err != nil { | 17 if err != nil { |
| 31 return fmt.Errorf("failed to encode %s: %s", filePath, err) | 18 return fmt.Errorf("failed to encode %s: %s", filePath, err) |
| 32 } | 19 } |
| 33 | 20 |
| 34 f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) | 21 f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) |
| 35 if err != nil { | 22 if err != nil { |
| 36 return fmt.Errorf("failed to open %s: %s", filePath, err) | 23 return fmt.Errorf("failed to open %s: %s", filePath, err) |
| 37 } | 24 } |
| 38 defer f.Close() | 25 defer f.Close() |
| 39 if _, err := f.Write(d); err != nil { | 26 if _, err := f.Write(d); err != nil { |
| 40 return fmt.Errorf("failed to write %s: %s", filePath, err) | 27 return fmt.Errorf("failed to write %s: %s", filePath, err) |
| 41 } | 28 } |
| 42 return nil | 29 return nil |
| 43 } | 30 } |
| OLD | NEW |