A command line tool for DigitalOcean services

config_file.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. Copyright 2016 The Doctl Authors All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package doit
  14. import (
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "os/user"
  19. "path/filepath"
  20. "gopkg.in/yaml.v2"
  21. )
  22. const (
  23. configFile = ".doctlcfg"
  24. )
  25. // ConfigFile is a doit config file.
  26. type ConfigFile struct {
  27. location string
  28. }
  29. // NewConfigFile creates an instance of ConfigFile.
  30. func NewConfigFile() (*ConfigFile, error) {
  31. usr, err := user.Current()
  32. if err != nil {
  33. return nil, err
  34. }
  35. location := filepath.Join(usr.HomeDir, configFile)
  36. return &ConfigFile{
  37. location: location,
  38. }, nil
  39. }
  40. // Set sets a ConfigFile key to a value. The value should be something
  41. // that serializes to a valid YAML value.
  42. func (cf *ConfigFile) Set(key string, val interface{}) error {
  43. c, err := cf.Open()
  44. if err != nil {
  45. switch err.(type) {
  46. case *os.PathError:
  47. err := cf.createConfigFile()
  48. if err != nil {
  49. return err
  50. }
  51. c, _ = cf.Open()
  52. default:
  53. return err
  54. }
  55. }
  56. b, err := ioutil.ReadAll(c)
  57. if err != nil {
  58. return err
  59. }
  60. var m map[string]interface{}
  61. err = yaml.Unmarshal(b, &m)
  62. if err != nil {
  63. return err
  64. }
  65. if m == nil {
  66. m = map[string]interface{}{}
  67. }
  68. m[key] = val
  69. out, err := yaml.Marshal(m)
  70. if err != nil {
  71. return err
  72. }
  73. return ioutil.WriteFile(cf.location, out, 0600)
  74. }
  75. // Open opens a ConfigFile.
  76. func (cf *ConfigFile) Open() (io.Reader, error) {
  77. _, err := os.Stat(cf.location)
  78. if err != nil {
  79. return nil, err
  80. }
  81. return os.Open(cf.location)
  82. }
  83. func (cf *ConfigFile) createConfigFile() error {
  84. f, err := os.Create(cf.location)
  85. if err != nil {
  86. return err
  87. }
  88. return f.Close()
  89. }