func parseConfig() *viper.Viper { if verbose { logrus.SetLevel(logrus.DebugLevel) logrus.SetOutput(os.Stderr) } // Get home directory for current user homeDir, err := homedir.Dir() if err != nil { fatalf("Cannot get current user home directory: %v", err) } if homeDir == "" { fatalf("Cannot get current user home directory") } // By default our trust directory (where keys are stored) is in ~/.notary/ mainViper.SetDefault("trust_dir", filepath.Join(homeDir, filepath.Dir(configDir))) // If there was a commandline configFile set, we parse that. // If there wasn't we attempt to find it on the default location ~/.notary/config if configFile != "" { configFileExt = strings.TrimPrefix(filepath.Ext(configFile), ".") configFileName = strings.TrimSuffix(filepath.Base(configFile), filepath.Ext(configFile)) configPath = filepath.Dir(configFile) } else { configPath = filepath.Join(homeDir, filepath.Dir(configDir)) } // Setup the configuration details into viper mainViper.SetConfigName(configFileName) mainViper.SetConfigType(configFileExt) mainViper.AddConfigPath(configPath) // Find and read the config file err = mainViper.ReadInConfig() if err != nil { logrus.Debugf("Configuration file not found, using defaults") // If we were passed in a configFile via -c, bail if it doesn't exist, // otherwise ignore it: we can use the defaults if configFile != "" || !os.IsNotExist(err) { fatalf("error opening config file %v", err) } } // At this point we either have the default value or the one set by the config. // Either way, the command-line flag has precedence and overwrites the value if trustDir != "" { mainViper.Set("trust_dir", trustDir) } // Expands all the possible ~/ that have been given, either through -d or config // If there is no error, use it, if not, attempt to use whatever the user gave us expandedTrustDir, err := homedir.Expand(mainViper.GetString("trust_dir")) if err == nil { mainViper.Set("trust_dir", expandedTrustDir) } logrus.Debugf("Using the following trust directory: %s", mainViper.GetString("trust_dir")) return mainViper }
func GetIdentity(path string, dirs Dirs) (*repo.Identity, error) { if len(path) == 1 { return dirs[path], nil } // Traverse directory -> id map from config for dir, _ := range dirs { // Expand path to include home directory if prefixed with tilde expandedDir, err := homedir.Expand(dir) if err != nil { return nil, err } // Expects the path to not have a trailing slash match, err := regexp.MatchString("^"+path+"/?$", expandedDir) if err != nil { return nil, err } if match { return dirs[dir], nil } } // No match, try parent directory return GetIdentity(filepath.Dir(path), dirs) }
func rootDir() (string, error) { cachedirRoot, err := homedir.Expand(cacheDir) if err != nil { return "", maskAny(err) } return cachedirRoot, nil }
func AddDefaults(c *viper.Viper) { c.SetDefault("marathon", kv("host", "http://localhost:8080")) c.SetDefault("mesos", kv("master", "localhost:5050")) c.SetDefault("zk", kv("host", "localhost:2181")) cachePath, _ := homedir.Expand("~/.marathonctl/packages") c.SetDefault("package-cache-path", cachePath) c.SetDefault("package-repo", "github.com/ashwanthkumar/marathonctl-universe") }
// SendMessage reads the configuration file, and posts a message about Kocho's invocation to Slack. func SendMessage(version, build string) error { expanded, err := homedir.Expand(configPath) if err != nil { return err } if _, err := os.Stat(expanded); os.IsNotExist(err) { return errgo.Mask(ErrNotConfigured, errgo.Any) } slackConfiguration := SlackConfiguration{ NotificationUsername: "******", EmojiIcon: ":robot_face:", } configFile, err := os.Open(expanded) if err != nil { return errgo.WithCausef(err, ErrInvalidConfiguration, "couldn't open Slack configuration file") } defer configFile.Close() if err := json.NewDecoder(configFile).Decode(&slackConfiguration); err != nil { return errgo.WithCausef(err, ErrInvalidConfiguration, "couldn't decode Slack configuration") } client := slack.New(slackConfiguration.Token) params := slack.PostMessageParameters{} params.Attachments = []slack.Attachment{ slack.Attachment{ Color: "#2484BE", Text: fmt.Sprintf("*Kocho*: %s ran `%s`", slackConfiguration.Username, strings.Join(os.Args, " ")), Fields: []slack.AttachmentField{ slack.AttachmentField{ Title: "Kocho Version", Value: version, Short: true, }, slack.AttachmentField{ Title: "Kocho Build", Value: build, Short: true, }, }, MarkdownIn: []string{"text"}, }, } params.Username = slackConfiguration.NotificationUsername params.IconEmoji = slackConfiguration.EmojiIcon if _, _, err := client.PostMessage(slackConfiguration.NotificationChannel, "", params); err != nil { return err } return nil }
// HomeDir is the home directory for the user. Light wrapper on the homedir lib. func HomeDir() (string, error) { homish, err := homedir.Dir() if err != nil { return "", fmt.Errorf("Unable to acquire home directory: %v", err) } home, err := homedir.Expand(homish) if err != nil { return "", fmt.Errorf("Unable to expand home directory: %v", err) } return home, nil }
func getPath(key string, value string) string { path := os.Getenv(key) if path == "" { path = value } path, err := homedir.Expand(path) if err != nil { fail(1, err) } return path }
func GetConfig() (Dirs, error) { file, err := homedir.Expand(CONFIG_FILE) if err != nil { return nil, err } source, err := ioutil.ReadFile(file) if err != nil { return nil, errors.New(FILE_READ_ERR) } dirs := make(Dirs) err = yaml.Unmarshal(source, dirs) if err != nil { return dirs, err } return dirs, nil }
func loadInifile(path string) ini.File { path, err := homedir.Expand(path) if err != nil { log.Fatalf("doesn't exist: %v\n", err) } if file, err := os.Open(path); err != nil { log.Fatalf("failed to open: %v\n", err) } else { inifile, err := ini.Load(file) if err != nil { log.Fatalf("%v\n", err) } return inifile } // Never reach return nil }
// WriteConfig writes the given SlackConfiguration to the configuration file. func WriteConfig(config SlackConfiguration) error { expanded, err := homedir.Expand(configPath) if err != nil { return err } configFolder := filepath.Dir(expanded) if err := os.MkdirAll(configFolder, 0777); err != nil { return err } configFile, err := os.Create(expanded) if err != nil { return err } defer configFile.Close() if err := json.NewEncoder(configFile).Encode(config); err != nil { return err } return nil }
func (n *notaryCommander) parseConfig() (*viper.Viper, error) { n.setVerbosityLevel() // Get home directory for current user homeDir, err := homedir.Dir() if err != nil { return nil, fmt.Errorf("cannot get current user home directory: %v", err) } if homeDir == "" { return nil, fmt.Errorf("cannot get current user home directory") } config := viper.New() // By default our trust directory (where keys are stored) is in ~/.notary/ defaultTrustDir := filepath.Join(homeDir, filepath.Dir(configDir)) // If there was a commandline configFile set, we parse that. // If there wasn't we attempt to find it on the default location ~/.notary/config.json if n.configFile != "" { config.SetConfigFile(n.configFile) } else { config.SetConfigFile(filepath.Join(defaultTrustDir, "config.json")) } // Setup the configuration details into viper config.SetDefault("trust_dir", defaultTrustDir) config.SetDefault("remote_server", map[string]string{"url": defaultServerURL}) // Find and read the config file if err := config.ReadInConfig(); err != nil { logrus.Debugf("Configuration file not found, using defaults") // If we were passed in a configFile via command linen flags, bail if it doesn't exist, // otherwise ignore it: we can use the defaults if n.configFile != "" || !os.IsNotExist(err) { return nil, fmt.Errorf("error opening config file: %v", err) } } // At this point we either have the default value or the one set by the config. // Either way, some command-line flags have precedence and overwrites the value if n.trustDir != "" { config.Set("trust_dir", pathRelativeToCwd(n.trustDir)) } if n.tlsCAFile != "" { config.Set("remote_server.root_ca", pathRelativeToCwd(n.tlsCAFile)) } if n.tlsCertFile != "" { config.Set("remote_server.tls_client_cert", pathRelativeToCwd(n.tlsCertFile)) } if n.tlsKeyFile != "" { config.Set("remote_server.tls_client_key", pathRelativeToCwd(n.tlsKeyFile)) } if n.remoteTrustServer != "" { config.Set("remote_server.url", n.remoteTrustServer) } // Expands all the possible ~/ that have been given, either through -d or config // If there is no error, use it, if not, just attempt to use whatever the user gave us expandedTrustDir, err := homedir.Expand(config.GetString("trust_dir")) if err == nil { config.Set("trust_dir", expandedTrustDir) } logrus.Debugf("Using the following trust directory: %s", config.GetString("trust_dir")) return config, nil }
Use: "init", Short: "Initialize configuration file", Run: func(cmd *cobra.Command, args []string) { var err error configuration := config.GetConfig() file := cfgFile if strings.TrimSpace(file) == "" { file = viper.ConfigFileUsed() if strings.TrimSpace(file) == "" { log.Fatal("Configuration file not found") } } file, err = home.Expand(file) if err != nil { log.Fatalln(err.Error()) } reader := bufio.NewReader(os.Stdin) var input string getInputValue := func(fieldName string, currentValue string) string { fmt.Print("Enter " + fieldName + " (leave empty to use current value: '" + currentValue + "'): ") input, err = reader.ReadString('\n') if err != nil { panic(err) } input = strings.TrimSpace(input) result := currentValue