config.go 8.5 KB

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