config.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package cmd
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "github.com/fatih/color"
  10. "github.com/spf13/cobra"
  11. "github.com/spf13/viper"
  12. flag "github.com/spf13/pflag"
  13. )
  14. // shared sets of flags used by multiple commands
  15. var driverFlagSet = flag.NewFlagSet("driver", flag.ExitOnError)
  16. var defaultFlagSet = flag.NewFlagSet("shared", flag.ExitOnError) // used by all commands
  17. var registryFlagSet = flag.NewFlagSet("registry", flag.ExitOnError)
  18. var helmRepoFlagSet = flag.NewFlagSet("helmrepo", flag.ExitOnError)
  19. // config is a shared object used by all commands
  20. var config = &CLIConfig{}
  21. // CLIConfig is the set of shared configuration options for the CLI commands.
  22. // This config is used by viper: calling Set() function for any parameter will
  23. // update the corresponding field in the viper config file.
  24. type CLIConfig struct {
  25. // Driver can be either "docker" or "local", and represents which driver is
  26. // used to run an instance of the server.
  27. Driver string `yaml:"driver"`
  28. Host string `yaml:"host"`
  29. Project uint `yaml:"project"`
  30. Cluster uint `yaml:"cluster"`
  31. Token string `yaml:"token"`
  32. Registry uint `yaml:"registry"`
  33. HelmRepo uint `yaml:"helm_repo"`
  34. }
  35. // InitAndLoadConfig populates the config object with the following precedence rules:
  36. // 1. flag
  37. // 2. env
  38. // 3. config
  39. // 4. default
  40. //
  41. // It populates the shared config object above
  42. func InitAndLoadConfig() {
  43. initAndLoadConfig(config)
  44. }
  45. func InitAndLoadNewConfig() *CLIConfig {
  46. newConfig := &CLIConfig{}
  47. initAndLoadConfig(newConfig)
  48. return newConfig
  49. }
  50. func initAndLoadConfig(_config *CLIConfig) {
  51. initFlagSet()
  52. // check that the .porter folder exists; create if not
  53. porterDir := filepath.Join(home, ".porter")
  54. if _, err := os.Stat(porterDir); os.IsNotExist(err) {
  55. os.Mkdir(porterDir, 0700)
  56. } else if err != nil {
  57. color.New(color.FgRed).Printf("%v\n", err)
  58. os.Exit(1)
  59. }
  60. viper.SetConfigName("porter")
  61. viper.SetConfigType("yaml")
  62. viper.AddConfigPath(porterDir)
  63. // Bind the flagset initialized above
  64. viper.BindPFlags(driverFlagSet)
  65. viper.BindPFlags(defaultFlagSet)
  66. viper.BindPFlags(registryFlagSet)
  67. viper.BindPFlags(helmRepoFlagSet)
  68. // Bind the environment variables with prefix "PORTER_"
  69. viper.SetEnvPrefix("PORTER")
  70. viper.BindEnv("host")
  71. viper.BindEnv("project")
  72. viper.BindEnv("cluster")
  73. viper.BindEnv("token")
  74. err := viper.ReadInConfig()
  75. if err != nil {
  76. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  77. // create blank config file
  78. err := ioutil.WriteFile(filepath.Join(home, ".porter", "porter.yaml"), []byte{}, 0644)
  79. if err != nil {
  80. color.New(color.FgRed).Printf("%v\n", err)
  81. os.Exit(1)
  82. }
  83. } else {
  84. // Config file was found but another error was produced
  85. color.New(color.FgRed).Printf("%v\n", err)
  86. os.Exit(1)
  87. }
  88. }
  89. // unmarshal the config into the shared config struct
  90. viper.Unmarshal(_config)
  91. }
  92. // initFlagSet initializes the shared flags used by multiple commands
  93. func initFlagSet() {
  94. driverFlagSet.StringVar(
  95. &config.Driver,
  96. "driver",
  97. "local",
  98. "driver to use (local or docker)",
  99. )
  100. defaultFlagSet.StringVar(
  101. &config.Host,
  102. "host",
  103. "https://dashboard.getporter.dev",
  104. "host URL of Porter instance",
  105. )
  106. defaultFlagSet.UintVar(
  107. &config.Project,
  108. "project",
  109. 0,
  110. "project ID of Porter project",
  111. )
  112. defaultFlagSet.UintVar(
  113. &config.Cluster,
  114. "cluster",
  115. 0,
  116. "cluster ID of Porter cluster",
  117. )
  118. defaultFlagSet.StringVar(
  119. &config.Token,
  120. "token",
  121. "",
  122. "token for Porter authentication",
  123. )
  124. registryFlagSet.UintVar(
  125. &config.Registry,
  126. "registry",
  127. 0,
  128. "registry ID of connected Porter registry",
  129. )
  130. helmRepoFlagSet.UintVar(
  131. &config.HelmRepo,
  132. "helmrepo",
  133. 0,
  134. "helm repo ID of connected Porter Helm repository",
  135. )
  136. }
  137. func (c *CLIConfig) SetDriver(driver string) error {
  138. viper.Set("driver", driver)
  139. color.New(color.FgGreen).Printf("Set the current driver as %s\n", driver)
  140. err := viper.WriteConfig()
  141. if err != nil {
  142. return err
  143. }
  144. config.Driver = driver
  145. return nil
  146. }
  147. func (c *CLIConfig) SetHost(host string) error {
  148. // a trailing / can lead to errors with the api server
  149. host = strings.TrimRight(host, "/")
  150. viper.Set("host", host)
  151. color.New(color.FgGreen).Printf("Set the current host as %s\n", host)
  152. err := viper.WriteConfig()
  153. if err != nil {
  154. return err
  155. }
  156. config.Host = host
  157. return nil
  158. }
  159. func (c *CLIConfig) SetProject(projectID uint) error {
  160. viper.Set("project", projectID)
  161. color.New(color.FgGreen).Printf("Set the current project as %d\n", projectID)
  162. err := viper.WriteConfig()
  163. if err != nil {
  164. return err
  165. }
  166. config.Project = projectID
  167. return nil
  168. }
  169. func (c *CLIConfig) SetCluster(clusterID uint) error {
  170. viper.Set("cluster", clusterID)
  171. color.New(color.FgGreen).Printf("Set the current cluster as %d\n", clusterID)
  172. err := viper.WriteConfig()
  173. if err != nil {
  174. return err
  175. }
  176. config.Cluster = clusterID
  177. return nil
  178. }
  179. func (c *CLIConfig) SetToken(token string) error {
  180. viper.Set("token", token)
  181. err := viper.WriteConfig()
  182. if err != nil {
  183. return err
  184. }
  185. config.Token = token
  186. return nil
  187. }
  188. func (c *CLIConfig) SetRegistry(registryID uint) error {
  189. viper.Set("registry", registryID)
  190. color.New(color.FgGreen).Printf("Set the current registry as %d\n", registryID)
  191. err := viper.WriteConfig()
  192. if err != nil {
  193. return err
  194. }
  195. config.Registry = registryID
  196. return nil
  197. }
  198. func (c *CLIConfig) SetHelmRepo(helmRepoID uint) error {
  199. viper.Set("helm_repo", helmRepoID)
  200. color.New(color.FgGreen).Printf("Set the current Helm repo as %d\n", helmRepoID)
  201. err := viper.WriteConfig()
  202. if err != nil {
  203. return err
  204. }
  205. config.HelmRepo = helmRepoID
  206. return nil
  207. }
  208. var configCmd = &cobra.Command{
  209. Use: "config",
  210. Short: "Commands that control local configuration settings",
  211. Run: func(cmd *cobra.Command, args []string) {
  212. if err := printConfig(); err != nil {
  213. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  214. os.Exit(1)
  215. }
  216. },
  217. }
  218. var configSetProjectCmd = &cobra.Command{
  219. Use: "set-project [id]",
  220. Args: cobra.ExactArgs(1),
  221. Short: "Saves the project id in the default configuration",
  222. Run: func(cmd *cobra.Command, args []string) {
  223. projID, err := strconv.ParseUint(args[0], 10, 64)
  224. if err != nil {
  225. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  226. os.Exit(1)
  227. }
  228. err = config.SetProject(uint(projID))
  229. if err != nil {
  230. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  231. os.Exit(1)
  232. }
  233. },
  234. }
  235. var configSetClusterCmd = &cobra.Command{
  236. Use: "set-cluster [id]",
  237. Args: cobra.ExactArgs(1),
  238. Short: "Saves the cluster id in the default configuration",
  239. Run: func(cmd *cobra.Command, args []string) {
  240. clusterID, err := strconv.ParseUint(args[0], 10, 64)
  241. if err != nil {
  242. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  243. os.Exit(1)
  244. }
  245. err = config.SetCluster(uint(clusterID))
  246. if err != nil {
  247. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  248. os.Exit(1)
  249. }
  250. },
  251. }
  252. var configSetRegistryCmd = &cobra.Command{
  253. Use: "set-registry [id]",
  254. Args: cobra.ExactArgs(1),
  255. Short: "Saves the registry id in the default configuration",
  256. Run: func(cmd *cobra.Command, args []string) {
  257. registryID, err := strconv.ParseUint(args[0], 10, 64)
  258. if err != nil {
  259. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  260. os.Exit(1)
  261. }
  262. err = config.SetRegistry(uint(registryID))
  263. if err != nil {
  264. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  265. os.Exit(1)
  266. }
  267. },
  268. }
  269. var configSetHelmRepoCmd = &cobra.Command{
  270. Use: "set-helmrepo [id]",
  271. Args: cobra.ExactArgs(1),
  272. Short: "Saves the helm repo id in the default configuration",
  273. Run: func(cmd *cobra.Command, args []string) {
  274. hrID, err := strconv.ParseUint(args[0], 10, 64)
  275. if err != nil {
  276. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  277. os.Exit(1)
  278. }
  279. err = config.SetHelmRepo(uint(hrID))
  280. if err != nil {
  281. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  282. os.Exit(1)
  283. }
  284. },
  285. }
  286. var configSetHostCmd = &cobra.Command{
  287. Use: "set-host [host]",
  288. Args: cobra.ExactArgs(1),
  289. Short: "Saves the host in the default configuration",
  290. Run: func(cmd *cobra.Command, args []string) {
  291. err := config.SetHost(args[0])
  292. if err != nil {
  293. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  294. os.Exit(1)
  295. }
  296. },
  297. }
  298. func init() {
  299. rootCmd.AddCommand(configCmd)
  300. configCmd.AddCommand(configSetProjectCmd)
  301. configCmd.AddCommand(configSetClusterCmd)
  302. configCmd.AddCommand(configSetHostCmd)
  303. configCmd.AddCommand(configSetRegistryCmd)
  304. configCmd.AddCommand(configSetHelmRepoCmd)
  305. }
  306. func printConfig() error {
  307. config, err := ioutil.ReadFile(filepath.Join(home, ".porter", "porter.yaml"))
  308. if err != nil {
  309. return err
  310. }
  311. fmt.Printf(string(config))
  312. return nil
  313. }