config.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright (c) 2020 Docker Inc.
  3. Permission is hereby granted, free of charge, to any person
  4. obtaining a copy of this software and associated documentation
  5. files (the "Software"), to deal in the Software without
  6. restriction, including without limitation the rights to use, copy,
  7. modify, merge, publish, distribute, sublicense, and/or sell copies
  8. of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be
  11. included in all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  13. EXPRESS OR IMPLIED,
  14. INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  17. HOLDERS BE LIABLE FOR ANY CLAIM,
  18. DAMAGES OR OTHER LIABILITY,
  19. WHETHER IN AN ACTION OF CONTRACT,
  20. TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH
  22. THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24. package context
  25. import (
  26. "encoding/json"
  27. "fmt"
  28. "os"
  29. "path/filepath"
  30. )
  31. // LoadConfigFile loads the docker configuration
  32. func LoadConfigFile(configDir string, configFileName string) (*ConfigFile, error) {
  33. filename := filepath.Join(configDir, configFileName)
  34. configFile := &ConfigFile{
  35. Filename: filename,
  36. }
  37. if _, err := os.Stat(filename); err == nil {
  38. file, err := os.Open(filename)
  39. if err != nil {
  40. return nil, fmt.Errorf("can't read %s: %w", filename, err)
  41. }
  42. // nolint errcheck
  43. defer file.Close()
  44. err = json.NewDecoder(file).Decode(&configFile)
  45. if err != nil {
  46. err = fmt.Errorf("can't read %s: %w", filename, err)
  47. }
  48. return configFile, err
  49. } else if !os.IsNotExist(err) {
  50. // if file is there but we can't stat it for any reason other
  51. // than it doesn't exist then stop
  52. return nil, fmt.Errorf("can't read %s: %w", filename, err)
  53. }
  54. return configFile, nil
  55. }
  56. // ConfigFile contains the current context from the docker configuration file
  57. type ConfigFile struct {
  58. Filename string `json:"-"` // Note: for internal use only
  59. CurrentContext string `json:"currentContext,omitempty"`
  60. }