Ejemplo n.º 1
2
// LoadConfig loads the config into the Config Struct and returns the // ConfigStruct object. Will load from environmental variables (all caps) if we
// set a flag to true.
func LoadConfig() ConfigStruct {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	viper.AddConfigPath("../")
	viper.AddConfigPath("/etc/")
	viper.AddConfigPath("$GOPATH/src/github.com/GrappigPanda/notorious/")

	err := viper.ReadInConfig()
	if err != nil {
		panic("Failed to open config file")
	}

	if viper.GetBool("UseEnvVariables") == true {
		viper.AutomaticEnv()
		viper.BindEnv("dbuser")
	}

	whitelist, err := strconv.ParseBool(viper.Get("whitelist").(string))
	if err != nil {
		whitelist = false
	}

	return loadSQLOptions(whitelist)
}
Ejemplo n.º 2
0
func main() {
	config.LoadConfig()
	dev := viper.Sub("app.development.twitter")
	fmt.Println(dev)
	fmt.Println(dev.Get("consumerKey"))

	consumerKey := viper.Get("app.development.twitter.consumerKey").(string)
	consumerSecret := viper.Get("app.development.twitter.consumerSecret").(string)
	tokenKey := viper.Get("app.development.twitter.token").(string)
	tokenSecret := viper.Get("app.development.twitter.tokenSecret").(string)

	config := oauth1.NewConfig(consumerKey, consumerSecret)
	token := oauth1.NewToken(tokenKey, tokenSecret)
	httpClient := config.Client(oauth1.NoContext, token)

	client := twitter.NewClient(httpClient)

	userShowParams := &twitter.UserShowParams{ScreenName: "realDonaldTrump"}
	user, _, _ := client.Users.Show(userShowParams)
	fmt.Printf("USERS SHOW:\n%v\n", user)

	f := new(bool)
	*f = false
	userTimelineParams := &twitter.UserTimelineParams{ScreenName: "realDonaldTrump", Count: 1, IncludeRetweets: f}
	tweets, _, _ := client.Timelines.UserTimeline(userTimelineParams)
	for tweet := range tweets {
		t, _ := json.MarshalIndent(tweets[tweet], "", "    ")
		fmt.Println(string(t))
	}
}
Ejemplo n.º 3
0
// GetConfig return configuration instance
func GetConfig() Config {
	config := Config{
		LinguaLeo: linguaLeo{
			Email:    cast.ToString(viper.Get("lingualeo.email")),
			Password: cast.ToString(viper.Get("lingualeo.password")),
		},
	}
	return config
}
Ejemplo n.º 4
0
func main() {
	redmine := redmine.New(
		viper.GetString("redmine.url"),
		viper.GetString("redmine.api_key"),
		cast.ToIntSlice(viper.Get("redmine.closed_statuses")),
		cast.ToIntSlice(viper.Get("redmine.high_priorities")),
	)
	slack := slack.New(redmine, viper.GetString("slack.token"))

	slack.Listen()
}
Ejemplo n.º 5
0
// initConfig reads in config file and ENV variables if set.
func initConfig() {
	mutex.Lock()
	if cfgFile != "" {
		// enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	path := absPathify("$HOME")
	if _, err := os.Stat(filepath.Join(path, ".hydra.yml")); err != nil {
		_, _ = os.Create(filepath.Join(path, ".hydra.yml"))
	}

	viper.SetConfigType("yaml")
	viper.SetConfigName(".hydra") // name of config file (without extension)
	viper.AddConfigPath("$HOME")  // adding home directory as first search path
	viper.AutomaticEnv()          // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf(`Config file not found because "%s"`, err)
		fmt.Println("")
	}

	if err := viper.Unmarshal(c); err != nil {
		fatal("Could not read config because %s.", err)
	}

	if consentURL, ok := viper.Get("CONSENT_URL").(string); ok {
		c.ConsentURL = consentURL
	}

	if clientID, ok := viper.Get("CLIENT_ID").(string); ok {
		c.ClientID = clientID
	}

	if systemSecret, ok := viper.Get("SYSTEM_SECRET").(string); ok {
		c.SystemSecret = []byte(systemSecret)
	}

	if clientSecret, ok := viper.Get("CLIENT_SECRET").(string); ok {
		c.ClientSecret = clientSecret
	}

	if databaseURL, ok := viper.Get("DATABASE_URL").(string); ok {
		c.DatabaseURL = databaseURL
	}

	if c.ClusterURL == "" {
		fmt.Printf("Pointing cluster at %s\n", c.GetClusterURL())
	}
	mutex.Unlock()
}
Ejemplo n.º 6
0
func getTestMenuState(s *Site, t *testing.T) *testMenuState {
	menuState := &testMenuState{site: s, oldBaseURL: viper.Get("baseurl"), oldMenu: viper.Get("menu")}

	menus, err := tomlToMap(CONF_MENU1)

	if err != nil {
		t.Fatalf("Unable to Read menus: %v", err)
	}

	viper.Set("menu", menus["menu"])
	viper.Set("baseurl", "http://foo.local/Zoo/")

	return menuState
}
Ejemplo n.º 7
0
func loadSQLOptions(whitelist bool) ConfigStruct {
	var sqlDeployOption string
	if viper.GetBool("UseMySQL") {
		sqlDeployOption = "mysql"
	} else {
		sqlDeployOption = "postgres"
	}

	var ircCfg *IRCConfig
	if viper.GetBool("UseIRCNotify") {
		ircCfg = loadIRCOptions()
	} else {
		ircCfg = nil
	}

	var useRSS bool
	if viper.GetBool("UseRSSNotify") {
		useRSS = true
	} else {
		useRSS = false
	}

	if viper.Get("dbpass").(string) != "" {
		return ConfigStruct{
			sqlDeployOption,
			viper.Get("dbhost").(string),
			viper.Get("dbport").(string),
			viper.Get("dbuser").(string),
			viper.Get("dbpass").(string),
			viper.Get("dbname").(string),
			whitelist,
			ircCfg,
			useRSS,
		}
	} else {
		return ConfigStruct{
			sqlDeployOption,
			viper.Get("dbhost").(string),
			viper.Get("dbport").(string),
			viper.Get("dbuser").(string),
			"",
			viper.Get("dbname").(string),
			whitelist,
			ircCfg,
			useRSS,
		}
	}
}
Ejemplo n.º 8
0
func loadBundles() {
	target := viper.GetString("WorkingDir")

	tdir := filepath.Join(target, "bundles")

	if _, err := os.Stat(tdir); os.IsNotExist(err) {
		return
	}

	bund := viper.Get("Bundles").([]Bundle)
	filepath.Walk(tdir, func(path string, f os.FileInfo, err error) error {
		name := filepath.Base(path)

		if name == "bundles" {
			return nil
		}

		rpath, _ := filepath.Rel(target, path)
		if s, _ := os.Stat(path); s.IsDir() {
			bund = append(bund, Bundle{name, rpath})
		}
		return nil
	})

	viper.Set("Bundles", bund)
}
Ejemplo n.º 9
0
// Config returns the currently active Hugo config. This will be set
// per site (language) rendered.
func Config() ConfigProvider {
	if currentConfigProvider != nil {
		return currentConfigProvider
	}
	// Some tests rely on this. We will fix that, eventually.
	return viper.Get("currentContentLanguage").(ConfigProvider)
}
Ejemplo n.º 10
0
func (suite *GitConfigTestSuite) SetupTest() {
	assert := assert.New(suite.T())
	viper.SetConfigFile("../../.ayi.example.yml")
	err := viper.ReadInConfig()
	assert.Nil(err)
	assert.Equal(true, viper.Get("debug"))
}
Ejemplo n.º 11
0
func (this *RedisStore) DeactivateLongpollKillswitch() error {
	killswitchKey := viper.Get("longpoll_killswitch")

	return this.redisPendingQueue.RunAsyncTimeout(5*time.Second, func(conn redis.Conn) (result interface{}, err error) {
		return conn.Do("DEL", killswitchKey)
	}).Error
}
Ejemplo n.º 12
0
Archivo: viper.go Proyecto: dyweb/Ayi
// ViperGetStringOrFail returns string without any convertion
// FIXED: https://github.com/dyweb/Ayi/issues/54
func ViperGetStringOrFail(key string) (string, error) {
	v := viper.Get(key)
	s, ok := v.(string)
	if ok {
		return s, nil
	}
	return "", errors.Errorf("%v is not a string", v)
}
Ejemplo n.º 13
0
func loadBoolPtr(key string) *bool {
	val := viper.Get(key)
	if val == nil {
		return nil
	}
	b := viper.GetBool(key)
	return &b
}
Ejemplo n.º 14
0
func loadConfig(c *Config) {
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		log.Error("Fatal error config file.", "error", err)
	} else {
		c.Alert = viper.Get("alert")
	}

}
Ejemplo n.º 15
0
Archivo: site.go Proyecto: h0wn0w/hugo
func (s *Site) initializeSiteInfo() {
	params, ok := viper.Get("Params").(map[string]interface{})
	if !ok {
		params = make(map[string]interface{})
	}

	permalinks, ok := viper.Get("Permalinks").(PermalinkOverrides)
	if !ok {
		permalinks = make(PermalinkOverrides)
	}

	s.Info = SiteInfo{
		BaseUrl:    template.URL(helpers.SanitizeUrl(viper.GetString("BaseUrl"))),
		Title:      viper.GetString("Title"),
		Recent:     &s.Pages,
		Params:     params,
		Permalinks: permalinks,
	}
}
Ejemplo n.º 16
0
func (l *Language) Get(key string) interface{} {
	if l == nil {
		panic("language not set")
	}
	key = strings.ToLower(key)
	if v, ok := l.params[key]; ok {
		return v
	}
	return viper.Get(key)
}
Ejemplo n.º 17
0
func deleteProduct(d Delete) {
	if d.SKU == "" {
		return
	}
	user := viper.Get("User")
	stmt, err := db.Prepare("DELETE FROM products WHERE SKU=? AND User=?")
	errHandle(err)
	_, err = stmt.Exec(d.SKU, user)
	errHandle(err)
}
Ejemplo n.º 18
0
func Update(coreOnly bool, securityOnly bool, checkDisabled bool) (result interface{}, err error) {
	switch viper.Get("app_type") {
	case "drupal":
		result, err = drupalUpdate(coreOnly, securityOnly, checkDisabled)
	case "wpress":
		result, err = wpressUpdate(coreOnly)
	default:
		result, err = nil, errors.New("Not implemented", 0)
	}

	return result, err
}
Ejemplo n.º 19
0
func Revert() (result interface{}, err error) {
	switch viper.Get("app_type") {
	case "drupal":
		result, err = drupalRevert()
		//	case "wpress":
		//		result, err = wpressMigrate()
	default:
		result, err = nil, errors.New("Not implemented", 0)
	}

	return result, err
}
Ejemplo n.º 20
0
// getDateFormat gets the dateFormat value from Params. The dateFormat should
// be a valid time layout. If it isn't set, time.RFC3339 is used.
func getDateFormat() string {
	params := viper.Get("params")
	if params == nil {
		return time.RFC3339
	}
	parms := params.(map[interface{}]interface{})
	layout := parms["DateFormat"]
	if layout == nil || layout == "" {
		return time.RFC3339
	}
	return layout.(string)
}
Ejemplo n.º 21
0
func convertToStringMap(name string) []map[string]string {
	if result, ok := viper.Get(name).([]map[string]string); ok {
		return result
	} else if array, ok := viper.Get(name).([]interface{}); ok {
		result := make([]map[string]string, len(array))
		for index, query := range array {
			if interfaceMap, ok := query.(map[interface{}]interface{}); ok {
				result[index] = make(map[string]string)
				for k, v := range interfaceMap {
					if kstr, ok := k.(string); ok {
						if vstr, ok := v.(string); ok {
							result[index][kstr] = vstr
						}
					}
				}
			}
		}
		return result
	}
	return nil
}
Ejemplo n.º 22
0
func getLanguagePrefix() string {
	if !viper.GetBool("Multilingual") {
		return ""
	}

	defaultLang := viper.GetString("DefaultContentLanguage")
	defaultInSubDir := viper.GetBool("DefaultContentLanguageInSubdir")

	currentLang := viper.Get("CurrentContentLanguage").(*Language).Lang
	if currentLang == "" || (currentLang == defaultLang && !defaultInSubDir) {
		return ""
	}
	return currentLang
}
Ejemplo n.º 23
0
func main() {

	viper.SetConfigFile("commander.json")
	//viper.AddConfigPath("$HOME/")
	viper.AddConfigPath("/Projects/OpenSource/go/Commander")
	err := viper.ReadInConfig()

	if err != nil {
		fmt.Println(err)
	}

	dbDns := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s",
		viper.Get("database.user"),
		viper.Get("database.pass"),
		viper.Get("database.host"),
		viper.Get("database.port"),
		viper.Get("database.name"),
	)

	db, err := sqlx.Open("mysql", dbDns)
	if err != nil {
		// panic?
	}

	defer db.Close()

	jobs := GetJobs(db, Jobs{}).Jobs

	if len(jobs) > 0 {

		for _, job := range jobs {

		}

	}
}
Ejemplo n.º 24
0
func (s *Site) initializeSiteInfo() {
	params, ok := viper.Get("Params").(map[string]interface{})
	if !ok {
		params = make(map[string]interface{})
	}

	permalinks, ok := viper.Get("Permalinks").(PermalinkOverrides)
	if !ok {
		permalinks = make(PermalinkOverrides)
	}

	s.Info = SiteInfo{
		BaseUrl:         template.URL(helpers.SanitizeUrl(viper.GetString("BaseUrl"))),
		Title:           viper.GetString("Title"),
		Author:          viper.GetStringMapString("author"),
		LanguageCode:    viper.GetString("languagecode"),
		Copyright:       viper.GetString("copyright"),
		DisqusShortname: viper.GetString("DisqusShortname"),
		Recent:          &s.Pages,
		Menus:           &s.Menus,
		Params:          params,
		Permalinks:      permalinks,
	}
}
Ejemplo n.º 25
0
func TestHighlight(t *testing.T) {
	if !helpers.HasPygments() {
		t.Skip("Skip test as Pygments is not installed")
	}
	defer viper.Set("PygmentsStyle", viper.Get("PygmentsStyle"))
	viper.Set("PygmentsStyle", "bw")

	tem := tpl.New()

	code := `
{{< highlight java >}}
void do();
{{< /highlight >}}`
	CheckShortCodeMatch(t, code, "\n<div class=\"highlight\" style=\"background: #ffffff\"><pre style=\"line-height: 125%\"><span style=\"font-weight: bold\">void</span> do();\n</pre></div>\n", tem)
}
Ejemplo n.º 26
0
func (suite *GitConfigTestSuite) TestCast() {
	assert := assert.New(suite.T())
	hostsRaw := viper.Get("git.hosts")
	//fmt.Println(hostsRaw)
	hostsSlice := cast.ToSlice(hostsRaw)
	//fmt.Println(hostsSlice)

	for _, host := range hostsSlice {
		hostMap := cast.ToStringMap(host)
		name := cast.ToString(hostMap["name"])
		https := cast.ToBool(hostMap["https"])
		if name == "git.saber.io" {
			assert.Equal(false, https)
		}
	}
}
Ejemplo n.º 27
0
func loadIRCOptions() *IRCConfig {
	return &IRCConfig{
		Nick:   viper.Get("ircnick").(string),
		Pass:   viper.Get("ircpass").(string),
		User:   viper.Get("ircnick").(string),
		Name:   viper.Get("ircnick").(string),
		Server: viper.Get("ircserver").(string),
		Port:   viper.GetInt("ircport"),
		Chan:   viper.Get("ircchan").(string),
	}
}
Ejemplo n.º 28
0
func (this *RedisStore) GetIsLongpollKillswitchActive() (bool, error) {
	killswitchKey := viper.Get("longpoll_killswitch")

	result := this.redisPendingQueue.RunAsyncTimeout(5*time.Second, func(conn redis.Conn) (result interface{}, err error) {
		return conn.Do("TTL", killswitchKey)
	})

	if result.Error == nil {
		if result.Value.(int64) >= -1 {
			return true, nil
		} else {
			return false, nil
		}
	}

	return false, timedOut
}
Ejemplo n.º 29
0
func LiveReloadInject(ct contentTransformer) {
	endBodyTag := "</body>"
	match := []byte(endBodyTag)
	port := viper.Get("port")
	replaceTemplate := `<script data-no-instant>document.write('<script src="/livereload.js?port=%d&mindelay=10"></' + 'script>')</script>%s`
	replace := []byte(fmt.Sprintf(replaceTemplate, port, endBodyTag))

	newcontent := bytes.Replace(ct.Content(), match, replace, 1)
	if len(newcontent) == len(ct.Content()) {
		endBodyTag = "</BODY>"
		replace := []byte(fmt.Sprintf(replaceTemplate, port, endBodyTag))
		match := []byte(endBodyTag)
		newcontent = bytes.Replace(ct.Content(), match, replace, 1)
	}

	ct.Write(newcontent)
}
Ejemplo n.º 30
0
func InitializeConfig() {
	gopath := os.Getenv("GOPATH")
	if len(gopath) == 0 {
		panic("Missing GOPATH on this environment.")
	}
	gopath, _ = filepath.EvalSymlinks(filepath.Join(gopath, "src/"))
	gopath, _ = filepath.Abs(gopath)

	viper.AddConfigPath(Cwd)

	if len(CfgFile) > 0 {
		viper.SetConfigFile(CfgFile)
		err := viper.ReadInConfig()
		if err != nil {
			log.Fatal(err)
		}
	}

	viper.Set("Bundles", make([]Bundle, 0))
	viper.SetDefault("Verbose", false)

	if garf.PersistentFlags().Lookup("verbose").Changed {
		viper.Set("Verbose", Verbose)
	}

	dir, _ := os.Getwd()
	if Cwd != "" {
		viper.Set("WorkingDir", filepath.Join(dir, Cwd))
	} else {
		viper.Set("WorkingDir", dir)
	}

	if Seed != "" {
		viper.Set("SeedDir", Seed)
	} else {
		_, filename, _, _ := runtime.Caller(1)
		dir := filepath.Join(path.Dir(filename), "../template")
		viper.Set("SeedDir", dir)
	}

	dir, _ = filepath.EvalSymlinks(viper.Get("WorkingDir").(string))
	dir, _ = filepath.Abs(dir)
	rootpath, _ := filepath.Rel(gopath, dir)
	viper.Set("rootpath", rootpath)
	viper.Set("engine", engine)
}