flags.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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 config
  14. import (
  15. "fmt"
  16. "os"
  17. "path/filepath"
  18. "github.com/pkg/errors"
  19. "github.com/spf13/pflag"
  20. "github.com/docker/compose-cli/api/config"
  21. )
  22. // ConfigFlags are the global CLI flags
  23. // nolint stutter
  24. type ConfigFlags struct {
  25. Config string
  26. }
  27. // AddConfigFlags adds persistent (global) flags
  28. func (c *ConfigFlags) AddConfigFlags(flags *pflag.FlagSet) {
  29. flags.StringVar(&c.Config, config.ConfigFlagName, confDir(), "Location of the client config files `DIRECTORY`")
  30. }
  31. func confDir() string {
  32. env := os.Getenv("DOCKER_CONFIG")
  33. if env != "" {
  34. return env
  35. }
  36. home, _ := os.UserHomeDir()
  37. return filepath.Join(home, config.ConfigFileDir)
  38. }
  39. // GetCurrentContext get current context based on opts, env vars
  40. func GetCurrentContext(contextOpt string, configDir string, hosts []string) string {
  41. // host and context flags cannot be both set at the same time -- the local backend enforces this when resolving hostname
  42. // -H flag disables context --> set default as current
  43. if len(hosts) > 0 {
  44. return "default"
  45. }
  46. // DOCKER_HOST disables context --> set default as current
  47. if _, present := os.LookupEnv("DOCKER_HOST"); present {
  48. return "default"
  49. }
  50. res := contextOpt
  51. if res == "" {
  52. // check if DOCKER_CONTEXT env variable was set
  53. if _, present := os.LookupEnv("DOCKER_CONTEXT"); present {
  54. res = os.Getenv("DOCKER_CONTEXT")
  55. }
  56. if res == "" {
  57. config, err := config.LoadFile(configDir)
  58. if err != nil {
  59. fmt.Fprintln(os.Stderr, errors.Wrap(err, "WARNING"))
  60. return "default"
  61. }
  62. res = config.CurrentContext
  63. }
  64. }
  65. if res == "" {
  66. res = "default"
  67. }
  68. return res
  69. }